4

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?

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
necrofish666
  • 75
  • 1
  • 7
  • 24

1 Answers1

7

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 and height. These are both optional and can also be set using DOM properties. When no width and height 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>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71