How to Choose Between Canvas and SVG for your Site
By Patrick Dengler, Senior Program Manager, Internet Explorer
Canvas and SVG are two exciting graphics features introduced in Internet Explorer 9 and are hardware accelerated. These technologies can be used to address a range of graphic scenarios on the modern Web. With a lot of excitement around Canvas, there has been a tendency to ignore SVG, which, in many cases, is the better choice. Here I offer some thoughts on when to choose Canvas, SVG, or a combination of the two.
High Level Summary of Canvas and SVG
The following is a high-level summary of Canvas and SVG meant to frame a discussion of when to use one particular vector graphic technology over the other.
A Comparison of Canvas and SVG
SVG is known as a retained mode graphics model persisting in an in-memory model. Analogous to HTML, SVG builds an object model of elements, attributes, and styles. When the element appears in an HTML5 document, it behaves like an inline block and is part of the HTML document tree.
Canvas is a bitmap with an immediate modegraphics application programming interface (API) for drawing on it. Canvas is a “fire and forget” model that renders its graphics directly to its bitmap and then subsequently has no sense of the shapes that were drawn; only the resulting bitmap stays around.
One way to think of these is that Canvas resembles the Windows GDI API, where you programmatically draw graphics to a window, and SVG resembles HTML markup with elements, styles, events, and DOM-based programmability. Canvas is procedural whereas SVG is declarative.
The following sections describe the technical benefits and limitations of both technologies, including a common sense approach to determining when one is appropriate for a given task. The illustration below illustrates where each scenario falls on a spectrum from Canvas to SVG with a clear cross over point in the middle.
High Fidelity Complex Vector Documents
High fidelity complex vector documents have been, and will continue to be, the sweet spot for SVG. Highly detailed for viewing and printing, standalone or those embedded in a Web page. The declarative nature of SVG provides for tooling or client or server side generation of shapes from databases.
From the Real-world Diagrams demo on the Internet Explorer Test Drive:
The first image shows the diagrams, while the second image shows these diagrams zoomed in to 1000%
When you consider the usefulness for observing a large schematic, but the need to drill into the detail, or print the entire document for engineering purposes, the “scalable” in Scalable Vector Graphics becomes abundantly clear. For these reasons, we put high fidelity complex vector documents at the SVG end of our spectrum.
SVG as an Image Format
Another common use for SVG is for static images within a Web page. With present-day high DPI monitors, developers must take into account the quality of graphics. The images below represent potential
If the developer wishes to reuse that image on a larger scale, or if the end user uses a high-DPI screen, the raster image becomes pixilated, or the need for a larger version of the file is necessary to preserve the fidelity.
SVG can thus serve as a nice image replacement format for even the simplest of images on a Web page. A suitable replacement by Canvas is not available.
On the other side of the spectrum, canvas brings speed to scenarios that don’t require retention of what was drawn. When Canvas was first introduced, many fun experiments were developed. I break these into three different scenarios.
Because Canvas is all about drawing and manipulating a pixel-based drawing surface, several experiments and showcases of Canvas include sophisticated algorithms to achieve impressive graphic effects such as ray tracing or filters.
The example below was written by Adam Burmister. The experiment creates an image by tracing the path of light through pixels on an image plane and simulating the effects of its encounters with virtual objects.
The same can be said for other scene-wide pixel manipulation. The following function replaces green pixels in one canvas with pixels from another, identically-sized canvas. A function such as this could be used with to create a video “green screen” effect.
It was a fun experiment, but like the ray-tracing example above, performance on today’s machines falls short. I call these out though for one primary reason: such pixel manipulation is simply not possible with SVG. It is the differentiating factor between the two technologies. One manipulates pixels while the other manipulates a model.
Whether creating realistic images from otherwise simple vector graphics or creating green screen effects with video, these graphic scenarios are, in most cases, simply not ready for prime time deployment on the today’s Web. However, certain scenarios are responsive enough (such as applying filters to remove red eye in photos). These pixel manipulation scenarios fall on the far left on the spectrum as a canvas scenario.
Hybrid and Crossover Scenarios
The most interesting set of use cases didn’t indicate a clear winner. These are illustrated with two primary scenarios: Charting/Graphing/Mapping and Two-dimensional Gaming.
Charts and graphs require vector graphics and either Canvas or SVG will work. However, SVG is the often then better choice due to its intrinsic capabilities.
SVG Charting/Graphing/Mapping Scenarios
A popular subset of charts and graphs on the Web include:
For all of these SVG is the technology of choice because:
To illustrate more precisely, let’s examine the scenario of selecting a state on a map of the United States.
In SVG, the state of Alaska is represented by one <path> element with about 162,500 characters of geometric data in its “d” attribute.
In fact, it requires 2,878 path-drawing directives (moveTo, lineTo, and bezierCurveTo) to draw this complex map of Alaska. Of course, lower resolution versions of this map are possible. Considerably fewer lines of code would be required for Wyoming and Colorado. :-)
SVG mapping-based applications typically include an interactive experience involving hover effects, selection, tabbing between items, and scaling. These operations require only lightweight HTML concepts when using SVG, for example, for processing a mouse event:
or creating a hover highlight effect using CSS:
An example of this type of interactive map can be seen in the Test Drive demo Atlas zur Europawahl 2004 in Deutschland, a visualization of the 2004 European election results in Germany.
In canvas, creating either of these effects requires you code your own hit detection using the event object’s mouse coordinates. You no longer have the context of the shape. While there is the isPointOnPath() API, it only applies to the last path created.
Code can and does exist in the form of graphing libraries to enable specific hit detection on graphs using pixel data to identify hits and hovers and are functional. They also exist for SVG and will have better performance if designed to take advantage of the SVG features.
Canvas Charting/Graphing Scenarios
Canvas has its place for charting and graphing scenarios. To set context for this, we need to examine the performance characteristics of both SVG and Canvas.
Sometimes there are outside influences that require a choice of technology that is, or is mostly, independent of functionality. For SVG and Canvas, there are two primary differentiators.
Developer knowledge, skill set, and existing assets will play a significant role into the choice of technologies. If while creating a game, the developers have deep knowledge of low-level graphic APIs and limited knowledge of Web technologies, the likely technology to choose is Canvas (more on this later). In porting games, there are tools that support moving from third party implementations to Canvas.
If performance is critical, often down to milliseconds, it is necessary to compare the performance characteristics of the two technologies. This does not mean that Canvas, typically considered highly performant, is the obvious choice. However, for applications with large amounts of data that must be drawn at the pixel level, Canvas is by far the better choice.
The weather map below does not require a large surface area, and the number of objects on the screen is considerably high. With Canvas, these can be quickly drawn without the cost of updating a DOM.
Casual gaming was the most complicated scenario to explore. Some initial observations:
In gaming libraries, for example, popular physics engines, the graphics model is independent and graphics becomes an implementation detail. Graphing geometries such as boundaries, velocities, sizes, and positions are delivered to engines that subsequently respond with velocities, collisions, and positions. Graphics are used only to get the computed scene to the screen.
While the game and demonstration logic is different, both are leveraging the same physics engine, which tracks positions, collisions, velocities, and other physical aspects of the gaming components. In the end, one utilizes SVG to draw (or move) the elements of the game and the other redraw them with Canvas.
Most 2D casual games that are built today for HTML5 are using Canvas so we place this scenario toward the Canvas side of the cross over point.
Description: Spectrum from canvas to SVG showing 2D casual gaming near the center of spectrum
The Hybrid Scenario
Casual gaming also falls into the hybrid scenario is because there is an advantage to leveraging the best of both technologies. For easy hit detection and user interaction, a mostly opaque layer of SVG geometries can be used to position elements while the underlying Canvas can more quickly position relevant images and provide real-time animations.
There is a growing number experiences outside the casual gaming segment that are finding it compelling to use a hybrid. When a scenario contains both the need for visually intense dynamic graphics and animations (Canvas) as well as rich user interaction (SVG), both of these technologies can and should be used. This is represented by the Brain Power site from one of our partners showcased on The Beauty of the Web site. This Brain Power site—and others featured on The Beauty of the Web—have found this delicate balance.
For user interaction and displaying portions of the brain, the site leverages the higher-level geometries of SVG:
For real time animations and special effects, canvas is used:
The analysis of existing vector graphic technologies available in the latest modern browsers shows new scenarios can be created using standard Web technologies in an interactive way. Check out these videos for more information on how to develop for Canvas and SVG:
The ongoing evolution of the Web continues to include richer graphics at its heart. We’ve presented one point-of-view about applying these technologies to particular scenarios. In the end, both Canvas and SVG are important components of the HTML5 graphically rich Web.
We’d love to hear how you’re applying these new HTML5 technologies to your Web sites. Include URLs and, please, make sure your page works in IE9 by including the HTML5 doctype, <!DOCTYPE html>, and using feature detection not browser detection to know if SVG or Canvas are supported.