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>
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With