Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can anyone tell me why this isn't creating a square? [duplicate]

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?

like image 535
necrofish666 Avatar asked Mar 02 '23 23:03

necrofish666


1 Answers

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>
like image 96
Scott Marcus Avatar answered Mar 05 '23 14:03

Scott Marcus