HTML and CSS Reference
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
the script does all the real work. An instance of the canvas element opens up one or more rendering
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.
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).