Search code examples
javascripttypescriptcanvasgraphicshtml5-canvas

HTML5 Canvas diagonal lines get thicker or bolder after drawing another line somewhere else on the canvas (not on top)


For horizontal and vertical lines, using translation of 0.5 for odd stroke widths produces crisper/sharper lines. How about the diagonal lines?

Link to jsfiddle

<!DOCTYPE html>
<html lang="en">

<body style="background: black">
    <button id="btn">Draw Next Line</button>
    <br> 
    <canvas style="border: 2px solid red" id="cnv"></canvas>
    <script>
        const ctx = document.getElementById("cnv").getContext("2d");

        debugger;

        const delta = 25;
        const color = 'white';

        const W = window.innerWidth - 80;
        const H = window.innerHeight - 100;
        ctx.canvas.width = W;
        ctx.canvas.height = H;

        ctx.lineWidth = 1;
        ctx.strokeStyle = color;

        // diagonal line.
        ctx.moveTo(0.5, 0);
        ctx.lineTo(W, H);


        ctx.stroke();
        
        // vertical lines
        let i = 0.5;
        document.getElementById("btn").onclick = () => {
            ctx.moveTo(i * delta, 0);
            ctx.lineTo(i * delta, H);
            ctx.stroke();
            i++;
        }


    </script>
</body>

</html>

As can be seen on the demo, after adding another line previously drawn diagonal lines get bolder or thicker. How to get consistent thickness/sharpness irrespective of whether the diagonal line is drawn first or last?


Solution

  • You're missing a ctx.beginPath(); call before each new line:

    <!DOCTYPE html>
    <html lang="en">
    
    <body style="background: black">
        <button id="btn">Draw Next Line</button>
        <br> 
        <canvas style="border: 2px solid red" id="cnv"></canvas>
        <script>
            const ctx = document.getElementById("cnv").getContext("2d");
    
            debugger;
    
            const delta = 25;
            const color = 'white';
    
            const W = window.innerWidth - 80;
            const H = window.innerHeight - 100;
            ctx.canvas.width = W;
            ctx.canvas.height = H;
    
            ctx.lineWidth = 1;
            ctx.strokeStyle = color;
    
            // diagonal line.
            ctx.moveTo(0.5, 0);
            ctx.lineTo(W, H);
    
    
            ctx.stroke();
            
            // vertical lines
            let i = 0.5;
            document.getElementById("btn").onclick = () => {
                ctx.beginPath(); // <------------------------ Here
                ctx.moveTo(i * delta, 0);
                ctx.lineTo(i * delta, H);
                ctx.stroke();
                i++;
            }
    
    
        </script>
    </body>
    
    </html>