We already covered other techniques in previous posts plug-ins, native approaches). For modern browsers SVG and Canvas are the two clear winners for visualization work. How can we choose between them?
SVG has been around a long time, but only last year it became a viable mainstream technique for doing visualization work in a browser. The sticking points were
SVG is a declarative, DOM based approach. This has significant advantages for programmers who expect drawing and event handling to ‘just work’. It also means that SVG content can be searched and indexed straightforwardly.
The drawing order matches the DOM declaration order, and primitives can be grouped together as compound items.
Text handling is good in general, with some browsers allowing you to style ‘foreign’ elements in SVG using standard CSS. Dotted and dashed lines are straightforward to code, and arrowheads can be styled quickly. All good stuff.
HTML5 Canvas is the new kid on the block.
Canvas uses a simple retained-mode graphics approach: it draws what you want where you tell it to draw.
This simplicity means that developers operate using a ‘scene graph’ approach. The scene holds the objects which are rendered in the viewport(s). There are open source scene graph libraries of varying degrees of sophistication that can help you get started.
Another benefit of the simplicity of the specification is that different browsers tend to behave largely the same way.
Even a year or so ago, Canvas support was patchy at best, particularly in the ‘lesser browsers’. It was quite common for browsers simply to ignore text rendering instructions. But over the course of last year Canvas implementations have matured significantly, and in most browsers hardware acceleration has meant massive performance improvements.
Canvas appeals strongly to game developers who use bitmap techniques. Access to pixels is easy and fast – handy for animated sprites.
SVG can be great for generative graphics, but:
Canvas allows us full control of the drawing with no DOM manipulation necessary. That comes at a price: we have to write hit testing code and do basic geometry. The upside is that we’re fully in control of what we’re rendering and how it is interacted with.