HTML5 Canvas Draw Rect - Got Border of Diff Width?

17,581

That's because your border is being cut off at the top and the left, because that's where the canvas starts, and if your rectangle starts at (0,0), the left border's left end's x co-ordinate will be -30.

Make the starting co-ordinates anything above 30 (so that the end of your borders aren't negative), and it'll work fine.

Demo

Share:
17,581
yeeen
Author by

yeeen

Updated on June 17, 2022

Comments

  • yeeen
    yeeen almost 2 years

    The result of the square border turns out to be different width, it seems that the right and the bottom border's width is 2x wider than the left and the top border's width. Why so weird? I want the border of all sides to have the same width.

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>HTML5 Test</title>
    <script type="text/javascript">
      function draw () {
        var canvas = document.getElementById('rectangle');
        var ctx = canvas.getContext('2d');
    
        ctx.save();
        ctx.lineWidth = 30;
        ctx.fillStyle = "black";
        ctx.fillRect(0,0,100,100);
        ctx.strokeStyle = "red";
        ctx.strokeRect(0,0,100,100);        
        ctx.restore();
      }
    </script>
    </head>
    
    <body onload="draw()">
    <canvas id="rectangle"></canvas>
    </body>
    </html>
    

    enter image description here