Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size of HTML5 Canvas via CSS versus element attributes

Tags:

html

css

canvas

People also ask

How do I change the size of my canvas in HTML?

Resizing the canvas on the fly is quite easy. To do it, simply set the width and height properties of the Canvas object, and then redraw the canvas contents: Canvas . width = 600 ; Canvas .

Does a canvas have CSS properties?

In Canvas the code we have access to uses two languages, HTML (HyperText Markup Language) and CSS (Cascading Style Sheets). You can view and edit this code by clicking the "HTML Editor" link in the upper right corner of the Rich Content Editor in Canvas.

What is the default height and width of the canvas element?

By default, the browser creates canvas elements with a width of 300 pixels and a height of 150 pixels. You can change the size of a canvas element by specifying the width and height attributes.


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/


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.