Reputation: 79
Recently i've been coding a simple platformer in HTML5 and Js. My background image, which has a width of 600 pixels and a height of 400 pixels, is rendered differently depending on how i define the size of my canvas.
If i use element attributes and define its size like so: <canvas width="600" height="400">
i get the desired outcome; the image sits perfectly within the canvas.
On the other hand, if i define the canvas size by giving the canvas an ID
and then style it within a CSS file like so: #canvas { width: 600px; height: 400px; }
, or simply style it inline, the image appears stretched and simply doesn't fit properly within the canvas, although the values are identical.
Why don't these declaration methods render similarly?
Upvotes: 0
Views: 123
Reputation: 700442
There is a difference between the canvas dimensions and the canvas display size.
The HTML attributes sets the canvas dimensions, which determines how objects are measured that you draw on the canvas.
The CSS style sets the canvas display size, which determines how large the canvas is drawn in the browser. If the display size is different from the dimensions, the canvas will be stretched when drawn.
If you only define the dimensions, that will also be used as the display size, i.e. the canvas is drawn at scale 1:1.
If you only define the display size, the dimensions will get the default value 300 times 150.
Upvotes: 3