canvas画折线

今天需要一个折线的效果,考虑方案有两个,一种是通过div进行选择一定的角度获得折线代码操作如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>canva学习</title>
</head>
<body>
    <style>
        div{
            position:relative;
            margin:50px auto;
            width:100px;
            height:100px;
            line-height:120px;
            text-indent:5px;
        }

        div::before{
            content:"";
            position:absolute;
            left:0;
            top:0;
            width:100%;
            height:50px;
            box-sizing:border-box;
            border-bottom:1px solid deeppink;
            transform-origin:bottom center;
            transform:rotateZ(45deg) scale(1);
        }
    </style>
    <div></div>
</body>
</html>

后来觉得这样的画绘制一个折线还需要两个div太麻烦了,于是决定用<canvas>标签进行绘图,canvas的基本原理是展开一个画布,然后你可以用这个画布画各种线,圆,图形,这里我需要的是画一根折线,效果大概是这样的:


折线.png

代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>canvas</title>
</head>
<body>
    <canvas width="300px" height="300px" id="testcanvas"></canvas>
</body>
<script>
    var canvas = document.getElementById('testcanvas');
    if (canvas.getContext) {
      let ctx = canvas.getContext("2d")
      ctx.lineWidth = 2       // 折线的宽度
      ctx.setLineDash([5, 5])   // 虚线:第一个参数代表虚线每一截的长度,第二个参数代表每个间隙的宽度
      ctx.beginPath()
      ctx.moveTo(0, 0)      // 折线的起点坐标
      ctx.lineTo(50, 50)      // 折线的折点坐标
      ctx.lineTo(100, 50)      // 折线的终点坐标
      ctx.strokeStyle = "blue";                 // 线的颜色
      ctx.stroke()                                  // 开始绘制
      ctx.closePath()                               // 结束绘制
    }
</script>
</html>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。