HTML and CSS Reference
In-Depth Information
The canvas element is an ordinary citizen of the document so it can be styled similarly to any other
element, adding background colors, background images, fonts, borders, margins, padding, and so on.
Those CSS styles won't affect the drawings within the rendered box, only the box itself and any fallback
content inside it.
Although the markup for the canvas element is very simple, it offers a wide window into a very complex
realm. The element itself doesn't do anything more than provide a space where JavaScript can draw, and
the script does all the real work. An instance of the canvas element opens up one or more rendering
contexts with a range of associated JavaScript methods. The only official rendering context at present is
2D, for two-dimensional drawings, but a 3D context is in the works, awaiting wider implementation in
browsers. Soon you'll be able to dynamically draw three-dimensional shapes in virtual space, right there in
a web browser. But for now you're limited to a flat plane.
Each shape in a canvas drawing is generated and positioned in JavaScript code. For instance, these few
lines of script will draw a blue square:
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.fillStyle = "lightblue"; // Set the fill color
context.fillRect(50, 40, 150, 150); // Draw the filled rectangle
The first two lines establish some variables, first specifying the canvas element on which to draw, then
invoking that canvas ' 2D rendering context. The next two lines produce the drawing, first declaring a fill
color and then drawing the filled rectangle on the canvas , 50 pixels from the left, 40 pixels from the top,
150 pixels wide and 150 pixels tall. That's not so hard, is it? You can see the result in Figure 5-12 (we've
added a border to the canvas element here, just so you can see it; a rendered canvas has no border or
background by default).
Figure 5-12. A filled square drawn with canvas and JavaScript
Search WWH ::

Custom Search