循环设置strokeStyle导致无法画线

代码如下

ctx.beginPath();
ctx.moveTo(0, 0);
for (let i=1; i<=255; i++) {
    // ctx.strokeStyle = 'red'; 如果只设置一样的颜色是可以正常画线的
    ctx.strokeStyle = `#${i.toString(16).repeat(3)}`;
    ctx.lineTo(i, i);
    ctx.stroke();
}
ctx.closePath();

我想要实现的就是每个点都是一种颜色,以此来达到一个渐变的效果。我知道strokeStyle可以直接设置渐变,但是我想这样试试。

阅读 2.1k
1 个回答

stroke() 会把整个path上色,包括之前每次循环中lineTo画的部分。你可能需要在for内也每次beginPath()。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题