【问题标题】:Pen color change within a loop in Canvas画布循环内的笔颜色变化
【发布时间】: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();
&lt;canvas id="canvas" class="plot" width="300" height="300"&gt;&lt;/canvas&gt;

【问题讨论】:

  • shift % 10 == 0 for array [0, 10, 20, 30, ... ] 总是给出相同的值
  • DraganS 是对的。但这不是唯一的原因。即使我们试图改变 shift 的增量值以使测试并不总是具有相同的值,我们也会得到相同的结果。这是因为您只调用一次 stroke 方法,并且由于它是在屏幕上绘制的 stroke 方法,它只会使用分配给 strokeStyle 的最后一种颜色进行绘制。

标签: javascript html5-canvas


【解决方案1】:

这可能没问题

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();
}
&lt;canvas id="canvas" width="300" height="300"&gt;&lt;/canvas&gt;

【讨论】:

    猜你喜欢
    • 2015-02-09
    • 1970-01-01
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多