yeeen
yeeen

Reputation: 4945

HTML5 Canvas Draw Rect - Got Border of Diff Width?

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

Upvotes: 9

Views: 18443

Answers (1)

Some Guy
Some Guy

Reputation: 16210

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

Upvotes: 7

Related Questions