JS Canvas Lines

What About Close, Evenly Spaced Lines?

Let's try an experiment with drawing evenly spaced lines. Using a for loop we should be able to draw a line from the top of the canvas to the bottom every other pixel. But what we get is a solid pink square, with a thin white stripe on the right side.

This is because the 1px wide lines are drawn on the canvas so that they slightly overlap with the pixel next to them. If we draw a line every other pixel they both overlap the middle pixel. Try raising and lowering the line spacing and line width to see the stripes emerge. Notice that lines with odd widths are blurry, but lines with even widths are not!


        ctx.clearRect(0, 0, 100, 100);
        ctx.lineWidth = parseInt(lineWidth);
        ctx.beginPath();
        for (var i = 0; i < 100; i += parseInt(spacing) + 1) {
          ctx.moveTo(i, 0);
          ctx.lineTo(i, 100);
        }
        ctx.stroke();
        ctx.closePath();
        ctx.lineWidth = 1;
      

  • Canvases are scaled 4x.