HTML5 canvas size using CSS attributes and elements

I don’t understand why the following code snippets produce different results because css will scale the canvas as it has been enlarged,

<style> #canvas { width: 800px; height: 600px; } </style> <canvas id="canvas"></canvas> 

Unlike this approach (which works as expected):

 <canvas id="canvas" width="800px" height="600px"></canvas> 
+42
css html5 canvas
Feb 17 2018-11-17T00:
source share
2 answers

Explanation here: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#attr-canvas-width , as seen in another post, thanks!

The inner dimensions of the canvas element are equal to the size of the coordinate space, with numbers interpreted in CSS pixels. However, an element can be arbitrarily defined by a stylesheet. During rendering, the image is scaled to fit the size of the layout .

+50
Feb 17 2018-11-21 at
source share

Think about what happens if you have a JPG 32x32 (it has exactly 1024 common pixels), but specify through CSS that it should look like width:800px; height:16px width:800px; height:16px . The same goes for HTML Canvas:

  • The width and height attributes of the canvas element itself determine how many pixels you can draw. If you did not specify the height and width of the canvas element, then for the specifications :
    "the default attribute width is 300, and the default attribute height is 150.

  • The CSS width and height properties control the size that the item displays on the screen. If CSS sizes are not set, the layout uses its own element size.

If you specify in CSS a different size than the actual size of the canvas, it should be stretched and crushed by the browser as necessary for display. You can see an example of this here: http://jsfiddle.net/9bheb/5/

+44
Feb 18 '11 at 19:15
source share



All Articles