HTML and CSS Reference
In-Depth Information
Unfortunately, the only shape that's quite that easy to draw is a rectangle. More interesting shapes require
some slightly more complex code. We can add an outlined circle like so:
context.strokeStyle = "midnightblue"; // Set the stroke color
context.lineWidth = 8; // Set the stroke width
context.arc(125, 115, 40, 0, Math.PI*2, true); // Create the circle path
context.stroke(); // Add the stroke to that path
And you can see the result in Figure 5-13. Shapes are drawn in the order in which they appear in the
JavaScript, so the circle overlaps the square because it's drawn later in the script.
Figure 5-13. Adding a circle to the canvas
More complex shapes are possible, of course, with gradient fills and effects like drop shadows, and
integrated bitmap images. With the canvas element and a 2D rendering context, you can produce almost
any sort of shape-based illustration you might create with vector drawing software like Adobe Illustrator. It
follows that the more complex the drawing is, the more complex the code will be to generate it. It's
certainly not quite as easy as dragging a pencil across a sketchpad, but there are tools, frameworks, and
code libraries that can help ease the pain.
What's really cool about canvas is that these drawings are generated “on the fly” by JavaScript, and can
thus be manipulated by JavaScript in real time, interacting with data and user input. Because the imagery
is created before your eyes, a canvas graphic can move and react and respond. Even with two measly
dimensions the possibilities are infinite.
Figure 5-14 is a screen capture of a live drawing application called Ghostwriter Art Studio
( ). J ust a few
years ago something like this could only be done with plug-ins like Flash or Silverlight, but this app works
directly in a browser. It's built entirely with HTML, CSS, and JavaScript, and uses the canvas element as,
well, a canvas.
Search WWH ::

Custom Search