HTML and CSS Reference
In-Depth Information
9.3 Setting <canvas> Dimensions
Problem
You want to explicitly specify the width and height of your canvas element to be dif-
ferent than the default dimensions.
Solution
Add the width and height attributes, and their corresponding values, to your canvas
element:
<canvas id="mycanvas" width="200" height="200" ></canvas>
You may also want to change the width and/or height of your canvas element with
JavaScript. If you want to change how much width or height (i.e., pixels for rendering)
is available in your canvas element, you must change the attributes of the canvas element
(not the CSS style properties of width and height , as you might assume):
mycanvas. setAttribute ("width", "200"); // will change the bitmap dimensions
mycanvas. setAttribute ("height", "200");
You can also set the width and height properties directly on the element:
mycanvas. width = 200; // will change the bitmap dimensions
mycanvas. height = 200;
Either approach will allow your canvas element to use 200 pixels in the horizontal
direction and 200 pixels in the vertical direction.
By contrast, controlling the size of your canvas element with CSS—either with CSS
rules or by directly setting CSS properties in JavaScript— does not affect the bitmap
dimensions of your canvas element, but rather takes the existing canvas element (at its
existing bitmap dimensions) and stretches or shrinks its physical dimensions, as
necessary:
mycanvas. style.width = "200px"; // will shrink the horizontal rendering
mycanvas. style.height = "200px"; // will stretch the vertical rendering
Discussion
The default dimensions of a canvas element are 300 pixels wide by 150 pixels high. In
practice, you'll usually want to define different dimensions for your canvas element.
As with all block-level HTML elements, if you make your canvas abso-
lutely positioned, it does not necessarily default to having any physical
dimensions to render. You need to explicitly define the physical ren-
dering dimensions via CSS, in addition to the bitmap pixel dimensions.
To keep a consistent rendering ratio, make sure the physical dimensions
match the bitmap pixel dimensions.
Search WWH ::




Custom Search