canvas 同时画两条直线,颜色和线宽交替变换,如何才能实现同时绘制不同颜色和宽度的直线啊?

当我开两个定时器准备绘制两条不同颜色和宽度的直线时,出现了问题:
两条线的颜色和宽度都不停地在变换。

代码如下:

https://img4.mukewang.com/5c51162c0001a35303940786.jpg

当第一条浅在绘制的时候是这样的:
https://img3.mukewang.com/5c51163d0001743801950139.jpg

当第二条线开始绘制是就开始变了:
https://img.mukewang.com/5c5116400001d18402770162.jpghttps://img4.mukewang.com/5c5116450001796d01520093.jpg

最后,想要实现开多个定时器绘制不同颜色宽度的直线应该怎样实现?


ibeautiful
浏览 1879回答 1
1回答

largeQ

<!DOCTYPE html><html><head>&nbsp; &nbsp; <meta charset="UTF-8">&nbsp; &nbsp; <title>Document</title></head><body>&nbsp; &nbsp; <canvas id="aa"></canvas>&nbsp; &nbsp; <script>&nbsp; &nbsp; &nbsp; &nbsp; let oC = document.getElementById('aa');&nbsp; &nbsp; &nbsp; &nbsp; let ctx = oC.getContext('2d');&nbsp; &nbsp; &nbsp; &nbsp; for (let i = 0; i < 100; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setTimeout(function () {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ctx.beginPath();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ctx.save();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ctx.lineWidth = 5;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ctx.strokeStyle = 'red';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(i, i * 600)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ctx.moveTo(i - 1, i - 1);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ctx.lineTo(i, i);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ctx.stroke();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ctx.restore();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ctx.closePath();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }, i * 600)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; for (let j = 10; j < 100; j++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setTimeout(function () {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ctx.beginPath();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ctx.save();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ctx.strokeStyle = 'blue';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ctx.lineWidth = 10;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ctx.moveTo(j - 1, 10 + j - 1)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ctx.lineTo(j, 10 + j);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ctx.stroke();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ctx.restore();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ctx.closePath();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }, j * 800)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; </script></body></html>每次都需要beginPath和closePath。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript