canvas常用方法和属性一---直线与虚线

360 阅读1分钟

1、画直线

  • beginPath() 开启一个路径
  • moveTo(x,y) 定义线条开始坐标
  • lineTo(x,y) 定义线条结束坐标
  • strokeStyle 属性设置或返回用于笔触的颜色、渐变或模式
  • lineWidth 设置线宽
  • stroke() 绘制一条路径
  • closePath() 关闭一个路径
const cvs = document.querySelector('.canvas')
const ctx = cvs.getContext('2d')
ctx.beginPath()
ctx.moveTo(100, 100)
ctx.lineTo(200, 100)
ctx.stroke()
ctx.closePath()

2、多彩矩形

 //多彩矩形
        ctx.beginPath()
        ctx.moveTo(100, 100)
        ctx.lineTo(300, 100)
        ctx.strokeStyle = 'red'
        ctx.lineWidth = '3'
        ctx.stroke()
        ctx.closePath()

        ctx.beginPath()
        ctx.moveTo(300, 100)
        ctx.lineTo(300, 300)
        ctx.strokeStyle = 'green'
        ctx.lineWidth = '3'
        ctx.stroke()
        ctx.closePath()

        ctx.beginPath()
        ctx.moveTo(300, 300)
        ctx.lineTo(100, 300)
        ctx.strokeStyle = 'blue'
        ctx.lineWidth = '3'
        ctx.stroke()
        ctx.closePath()

        ctx.beginPath()
        ctx.moveTo(100, 300)
        ctx.lineTo(100, 100)
        ctx.strokeStyle = 'pink'
        ctx.lineWidth = '3'
        ctx.stroke()
        ctx.closePath()

优化代码,对其封装成一个方法

        drawLine(100,100,300,100,'red','3')
        drawLine(300,100,300,300,'green','3')
        drawLine(300,300,100,300,'blue','3')
        drawLine(100,300,100,100,'pink','3')

        //封装画矩形的方法
        function drawLine(x1, y1, x2, y2, color, width) {
            ctx.beginPath()
            ctx.moveTo(x1, y1)
            ctx.lineTo(x2, y2)
            ctx.strokeStyle = color
            ctx.lineWidth = width
            ctx.stroke()
            ctx.closePath()
        }

虚线

通过设置直线的长度,来画出虚线

 //画虚线
        for (let i = 0; i < 20; i++) {
            drawLine(350 + 10 * i, 100 + i * 10 /3, 355 + 10 * i, 100 + i * 10/3, 'red', '3')
        }

        //封装画矩形的方法
        function drawLine(x1, y1, x2, y2, color, width) {
            ctx.beginPath()
            ctx.moveTo(x1, y1)
            ctx.lineTo(x2, y2)
            ctx.strokeStyle = color
            ctx.lineWidth = width
            ctx.stroke()
            ctx.closePath()
        }