HTML and CSS Reference
In-Depth Information
Canvas and SVG: when to use which
Canvas and SVG are both very good drawing APIs, but for different reasons, and with anything, you want
to use the right tool for the job. SVG is a retained-mode API, and the 2D canvas API is an immediate-
mode API.
SVG maintains a tree that represents the current state of all the objects drawn onscreen, which makes it a
retained-mode API. As this tree is available, it makes it a great candidate for interactivity because you can
bind to specifi c objects in the tree and listen for click or touch events and even hit detection for games. It
also has good support in desktop tools such as Adobe Illustrator and Inkscape for importing and export-
ing SVG graphics, rather than having to wrestle XML to create your image. SVG is vector based, so it
handles scaling much better; canvas is a bitmap-based image—it doesn't scale, it just zooms.
If you need some convincing that SVG is the right tool for the job, have a look at Raphaël, the JavaScript
library by Dmitry Baranovskiy ( http://raphaeljs.com ). It uses SVG exclusively and is able to create some
very impressive drawings and animations.
Canvas is very well suited to lots of animations and highly JavaScript-centric applications. It's a lower-level
API when compared to SVG, which means that it's better for when there isn't mouse interaction because
there's no tree maintaining the state of the canvas. It is good for when you have keyboard interaction, like
many of the 8-bit game demos that have emerged in the last year. Since canvas is JavaScript centric, in
your processing loop you can handle keyboard events on the document level. Finally, canvas is pixel ori-
entated, as illustrated in the stick man examples in Figure 5.10, so it's good for pixel pushing.
Each of these technologies has its strengths and weaknesses. As the developer, it's your job to under-
stand the requirements of your application and pick the right one. Good luck!
Using transformers: pixels in disguise
As well as being able to move the pen around the canvas using
methods like moveTo , drawing shapes and lines, you can also
adjust the canvas under the pen using transformations.
Transformation methods include rotate, scale, transform, and
translate (all similar to their CSS counterparts).
In Figure 5.12 , I've drawn a spiral; the aim is to have it rotate in
a circle, giving a quasi-twilight zone effect. Ideally I would keep
the function that draws the spiral the same, not changing any
positions, starting points, or anything else. This would keep the
code much easier to manage. So to ensure that the spiral code
remains simple, I can rotate the canvas under the pen, and then
redraw the exact same spiral, except the result is rotated slightly
in one direction.
 
 
Search WWH ::




Custom Search