It’s important to start by understanding the difference between retained mode and an immediate mode graphics models:
- In a retained mode API, the structure of a graphical scene or object is stored in memory as a graph. The runtime itself is responsible for drawing the scene or elements of the scene as appropriate.
- In an immediate mode API, it is the application that is responsible for drawing the scene and you can’t manipulate an object in the scene once it has been drawn. Each has their benefits, depending on the style of application being created, as we’ll see.
More information on retained and immediate mode models can be found on MSDN.
SVG is a retained-mode graphics model. To build a scene graph in SVG, you write declarative markup to create an in-memory tree structure that lives in the HTML DOM. You can manipulate the scene graph through code or through CSS. SVG markup can be generated from a variety of tools, including Adobe Illustrator and Microsoft Visio.
Canvas is the immediate-mode graphics model. Because it doesn’t store the graph in memory, it takes less memory overhead to use, and can be faster for intensive use. Unlike SVG, it is programmatic in nature – there is only one parent <canvas> element, and code is used to populate it. While you draw primitive objects on a canvas, the only thing that is stored is the generated bitmap surface. In general, canvas is a lower-level API than SVG because of these constraints.
A quick tabular comparison of the two technologies:
|Pixel-based (almost like a “dynamic PNG”)||Shape-based (no concept of a pixel)|
|Single HTML element||Multiple graphical elements which become part of the HTML DOM|
|Modified through script only||Modified through script and CSS|
|Event model / user interaction is simplified (x,y)||Event model / user interaction is abstracted (rect, path)|
|Performance is better with smaller surface and/or larger number of objects||Performance is better with a larger surface and/or smaller number of objects|
Given these characteristics, what is the best technology to use for a specific scenario? SVG is perfect for high-fidelity documents and graphics for viewing and printing, and for interactive charts and maps. On the other hand, canvas is perfect for mathematically-intensive operations and complex scenes. However, there are a lot of cross-over scenarios where there’s no clear winner at this point in time, and as browsers evolve and improve, it seems that the performance characteristics of both technologies are starting to converge. Both technologies are clearly valuable!
[Session CD53 | presented by Patrick Dengler]