Canvas中循环内的笔颜色改变

3
我正在将一些Windows程序迁移到Web技术上。基本上使用System.Drawing,所以我正在使用JavaScript,当然还有Canvas。作为一个概念实践,我尝试在Canvas上绘制网格(见图像)。很酷,我已经非常接近了,但是我无法让深色线条的颜色交替。我应该怎么做?

Sample

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.translate(0.5, 0.5) // waiting a line of one pixel

let shift = 0;
let w = canvas.clientWidth;

while (shift <= w) {
  ctx.strokeStyle = shift % 40 == 0 ? 'gray' : 'silver';
  ctx.moveTo(shift, w)
  ctx.lineTo(w, w - shift);
  shift += 10;
}
ctx.stroke();
<canvas id="canvas" class="plot" width="300" height="300"></canvas>


2
对于数组 [0, 10, 20, 30, ... ],shift % 10 == 0 总是返回相同的值。 - DraganS
2
DraganS是正确的。但这不是唯一的原因。即使我们尝试更改移位的增量值,以便测试不总是具有相同的值,我们仍将得到相同的结果。这是因为您只调用stroke方法一次,而且由于strokeStyle是分配给最后一个颜色的方法,它只会使用最后一个颜色绘制在屏幕上。 - Med Okl
1个回答

5

这可能很不错。

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.translate(0.5, 0.5) // waiting a line of one pixel

let shift = 0;
let w = canvas.clientWidth;

while (shift <= w) {
  ctx.strokeStyle = shift % 100 == 0 ? 'gray' : 'silver';
  ctx.beginPath();
  ctx.moveTo(shift, w)
  ctx.lineTo(w, w - shift);
  shift += 10;
  ctx.stroke();
}
<canvas id="canvas" width="300" height="300"></canvas>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接