Pen color change within a loop in Canvas

Viewed 104

I am migrating some Windows programs to Web technologies. Basically use System.Drawing, so I'm using JavaScript, and of course Canvas. As a conceptual practice, I try to draw a mesh on Canvas (see image), Cool, I am very close, but I can't get the color of the dark lines alternates. What should I do?

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>

1 Answers

This might be fine

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>

Related