Search code examples
htmlcanvasstroke

Thinner html canvas stroke width


I have set the 2d context line width to its apparent minimum 1:

  let context = this._canvas.getContext("2d");
  context.lineWidth = 1;
  context.stroke();

But that is still fairly wide : maybe 20 pixels. Is there any way to get it less?

enter image description here


Solution

  • The key is to ensuring that you've the same number of virtual pixels as you have actual ones. More screen pixels and the image is scaled larger. Fewer screen pixels and the image is shrunk. Scaling up a 1 pixel wide line produces rectangles, but what happens when we scale down a 1 pixel line? The simple answer is it becomes less intense.

    The following example draws 2 canvases the same size. The key difference though, is the size of the pixel buffer they each have. The first has 10,000 pixels - 100x100. The second has just 100 pixels - 10x10. Even though we've just drawn a 1 pixel wide line, you can see the very different appearances of these lines.

    window.addEventListener('load', onLoaded, false);
    function onLoaded(evt)
    {
      let can = document.querySelector('canvas');
      let ctx = can.getContext('2d');
      ctx.moveTo(0,0);
      ctx.lineTo(can.width,can.height);
      ctx.stroke();
      
      let can2 = document.querySelectorAll('canvas')[1];
      let ctx2 = can2.getContext('2d');
      ctx2.moveTo(0,0);
      ctx2.lineTo(can2.width,can2.height);
      ctx2.stroke();
    }
    canvas
    {
      width: 100px;
      height: 100px;
    }
    <canvas width=100 height=100></canvas><br>
    <canvas width=10 height=10></canvas>