Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 283
yeeen Avatar asked Nov 06 '11 14:11

yeeen


People also ask

How do you draw a rounded rectangle in canvas?

To draw a rectangle in HTML, use the canvas element. With canvas, use the rect() method to draw a rectangle. But, for creating a rounded rectangle, using the rect() method won't work. We will be using the lineTo() and quadraticCurveTo() method to create a rounded rectangle.

How do I draw a rectangle in HTML canvas?

Canvas has the following APIs to draw rectangles: fillRect(x, y, width, height) : Draws a filled rectangle. strokeRect(x, y, width, height) : Draws a rectangular outline. clearRect(x, y, width, height) : Clears the specified rectangular area, making it fully transparent.

How do I add a border to an element in canvas?

By default, a canvas has no border and no content. Note: Always specify an id attribute (to be referred to in a script), and a width and height attribute to define the size of the canvas. To add a border, use the style attribute.


1 Answers

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

like image 160
Some Guy Avatar answered Oct 24 '22 17:10

Some Guy