JS Canvas Lines

Maybe just use rectangles?

In pixel space a line is really just a rectangle. The JS Canvas API also has a ctx.fillRect() method that will draw a filled-in rectangle. Rectangles on the JS Canvas are drawn with the to left corner at a specified point so we avoid the half pixel blurriness, but lines are still jagged, and we have to write a wrapper function to draw diagonal lines.


        ctx.clearRect(0, 0, 100, 100);
        var lineWidth = parseInt(lineWidth);
        // Line 1
        ctx.fillRect(0, 0, lineWidth, 40);
        // Line 2
        //ctx.fillRect(25, 0, 1, 40)
        function drawRectLine(ctx, sx, sy, ex, ey, w) {
          ctx.translate(sx, sy);
          var yD = ey - sy;
          var xD = ex - sx;
          ctx.rotate(-Math.atan(xD / yD));
          ctx.translate(-sx, -sy);
          var l = Math.sqrt((yD * yD) + (xD * xD));
          ctx.fillRect(sx, sy, w, l);
          ctx.resetTransform();
        }
        drawRectLine(ctx, 25, 0, 60, 40, lineWidth)
        // Stripes
        for (var i = 0; i < 100; i += parseInt(spacing) + 1) {
          ctx.fillRect(i, 50, lineWidth, 50);
        }
      

  • Canvases are scaled 4x.