Size of HTML5 Canvas via CSS versus element attributes

Think about what happens if you have a JPG that is 32×32 (it has exactly 1024 total pixels) but specify via CSS that it should appear as width:800px; height:16px. The same thing applies to HTML Canvas:

  • The width and height attributes of the canvas element itself decide how many pixels you can draw on. If you don’t specify the height and width of the canvas element, then per the specs:
    “the width attribute defaults to 300, and the height attribute defaults to 150.”

  • The width and height CSS properties control the size that the element displays on screen. If the CSS dimensions are not set, the intrinsic size of the element is used for layout.

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

Leave a Comment