前端-你会画三角形吗?

459 阅读2分钟

有时候CSS的掌握情况的评判,不是通过生硬的问答,而是简单的案例

写了案例,建议打开上手尝试一下噢!!codepen.io/nexttime8/p…

image.png

border

设置宽高为0,其中一个border-方向为颜色+具体值,垂直的两个方向设置为transparent+具体值的二分之一

linear-gradient

div {
  width: 100px;
  height: 100px;
  background: linear-gradient(45deg, deeppink, deeppink 50%, transparent 50%, transparent 100%);
}

transform

  1. 以左下角为原点,顺时针旋转45度,右下角会超出.triangle元素的边界。
  2. 且由于.triangle元素设置了overflow: hidden,因此超出部分不会显示,从而出现了三角形的效果
  3. 建议在codepen.io/nexttime8/e… codepen上尝试注释掉overflow: hidden和调整widthheight查看效果。
.triangle {
  width: 141px;
  height: 100px;
  position: relative;
  overflow: hidden;

  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: deeppink;
    transform-origin: left bottom;
    transform: rotate(45deg);
  }

svg

  1. SVG(可缩放矢量图形)是一种基于XML的矢量图像格式,非常适合在网页上绘制图形。
  2. <polygon>标签中,points属性定义了三角形的顶点坐标。fillstroke属性分别用于设置填充色和边框色。
<svg width="100" height="100">  
  <polygon points="50,10 10,90 90,90" style="fill:lime;stroke:purple;stroke-width:1" />  
</svg>

canvas

  1. HTML5的<canvas>元素提供了在网页上绘制图形的能力。
  2. 首先获取<canvas>元素的上下文,然后使用beginPathmoveTolineTo方法定义三角形的路径,最后使用stroke方法绘制三角形。
<canvas id="myCanvas" width="200" height="200"></canvas>  
<script>  
  var canvas = document.getElementById('myCanvas');  
  var ctx = canvas.getContext('2d');  
  ctx.beginPath();  
  ctx.moveTo(50, 50);  
  ctx.lineTo(150, 50);  
  ctx.lineTo(100, 150);  
  ctx.closePath();  
  ctx.strokeStyle = 'blue';  
  ctx.lineWidth = 5;  
  ctx.stroke();  
</script>

clip-path

  1. clip-path属性可以创建一个只显示元素的部分区域的剪切区域。
  2. clip-pathpolygon函数定义了三角形的顶点坐标,从而实现了三角形的剪切效果。
<div class="clip-triangle"></div>  
<style>  
  .clip-triangle {  
    width: 100px;  
    height: 100px;  
    background: red;  
    clip-path: polygon(50% 0%, 0% 100%, 100% 100%);  
  }  
</style>

总结

一共用了6种方式呈现三角形效果,不要忘记比较一下它们的视觉效果、兼容性等各方面哦~