I'm following a tutorial to learn about canvas, and I'm unstuck pretty early on.
Here is the code:
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.lineWidth = 3;
context.strokeStyle = "blue";
context.lineJoin = "square";
context.strokeRect(10,10,200,200);
#canvas{
border: 1px solid black;
display: block;
width: 900px;
height: 600px;
margin: 0 auto;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>HTML Canvas</title>
<link rel="stylesheet" href="stylesheet.css" type="text/css">
</head>
<body>
<canvas id="canvas"></canvas>
<script src="script.js" type="text/javascript"></script>
</body>
</html>
It seems like it should be pretty straight-forward, but it's not doing what I expect. Can anyone advise?
The height
and width
of the canvas should initially be set in HTML or via DOM properties, not CSS to avoid resizing.
From MDN:
Indeed, the element has only two attributes,
width
andheight
. These are both optional and can also be set using DOM properties. When nowidth
andheight
attributes are specified, the canvas will initially be 300 pixels wide and 150 pixels high. The element can be sized arbitrarily by CSS, but during rendering the image is scaled to fit its layout size: if the CSS sizing doesn't respect the ratio of the initial canvas, it will appear distorted.
Because of this, your square was also being resized to the same size of the canvas and could no longer fit completely within it.
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.lineWidth = 3;
context.strokeStyle = "blue";
context.lineJoin = "square";
context.strokeRect(10,10,200,200);
#canvas{
border: 1px solid black;
display: block;
margin: 0 auto;
}
<canvas id="canvas" height="600" width="900"></canvas>
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