【发布时间】:2021-11-23 23:21:17
【问题描述】:
我正在将一些 Windows 程序迁移到 Web 技术。基本上使用 System.Drawing,所以我使用 JavaScript,当然还有 Canvas。作为概念实践,我尝试在 Canvas 上绘制网格(见图),酷,我非常接近,但我无法让暗线的颜色交替出现。我该怎么办?
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>
【问题讨论】:
-
shift % 10 == 0 for array [0, 10, 20, 30, ... ] 总是给出相同的值
-
DraganS 是对的。但这不是唯一的原因。即使我们试图改变 shift 的增量值以使测试并不总是具有相同的值,我们也会得到相同的结果。这是因为您只调用一次 stroke 方法,并且由于它是在屏幕上绘制的 stroke 方法,它只会使用分配给 strokeStyle 的最后一种颜色进行绘制。