Size of HTML5 Canvas via CSS versus element attributes

CssHtmlCanvas

Css Problem Overview


I don't get why the following pieces of code produce different results, because css would scale the canvas as it was zoomed in,

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

In contrast with this approach (that works as expected):

<canvas id="canvas" width="800px" height="600px"></canvas>

Css Solutions


Solution 1 - Css

Think about what happens if you have a JPG that is 32x32 (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/

Solution 2 - Css

The explanation is 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 intrinsic dimensions of the canvas element equal the size of the coordinate space, with the numbers interpreted in CSS pixels. However, the element can be sized arbitrarily by a style sheet. During rendering, the image is scaled to fit this layout size.

Solution 3 - Css

The best way to size your canvas is to include in a div and style your div with the size that you want.

Here is the CSS

<style>
#divCanvas{
    width: 800px;
    height: 600px;
}
</style>

Here is the HTML

<div id="divCanvas">
    <canvas id="canvas"></canvas>
</div>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoaqu&#237;n L. RoblesView Question on Stackoverflow
Solution 1 - CssPhrogzView Answer on Stackoverflow
Solution 2 - CssJoaquín L. RoblesView Answer on Stackoverflow
Solution 3 - CssDiego MartinsView Answer on Stackoverflow