HTML and CSS Reference
In-Depth Information
You can specify the bitmap pixel dimensions using attributes on the
canvas
element,
either in the markup or with a
setAttribute(...)
call. You can also resize the
canvas
element by using CSS styling on the width/height, but this has the effect of shrinking
or stretching the
canvas
element while keeping the existing pixel dimensions, rather
than actually changing them.
For instance, let's say you wanted a full-page
canvas
element that resized itself with the
window. If you want that sizing to be achieved by stretching or shrinking the
canvas
element while maintaining the same pixel dimensions, use CSS, like this:
#mycanvas {
width:100%; height:100%;
}
However, if you want a
canvas
element that keeps resizing its bitmap pixel dimensions
along with the dimensions of the browser window, you need to use JavaScript:
window.onresize = function() {
mycanvas
.width
= document.documentElement.clientWidth;
mycanvas
.height
= document.documentElement.clientHeight;
};
You can resize the
canvas
element as often as you like. However, each time you resize
it, the drawing space will be cleared. This is actually a useful trick, as you can quickly
clear the
canvas
by simply setting its
width
to be the same as its current width:
function clear(mycanvas) {
mycanvas.width = mycanvas.width;
}
See Also
9.4 Using Gradients, Patterns, and Line Styles
Problem
You want to create gradients and other drawing styles.
Solution
Each time you render a path to the
canvas
element, the color and style for that drawing
are picked up from the currently set stroke and fill styles.
For instance, to vary the way that line segments are drawn on paths, you can control
the stroke styles with
lineWidth
,
lineCap
, and
lineJoin
: