canvas element is used everywhere. From WebGL games to some amazing browser experiments, web developers are jumping on the canvas bandwagon and enjoying the ride.
But are we always using the right tool for the job? In many cases, Scalable Vector Graphics (SVG) offer a better alternative but it’s easy to forget about the technology when it’s hidden beneath the wave of canvas hype. If you’re not considering SVG, perhaps the following reasons will make you think again…
1. SVGs are Scalable
That should be obvious, but it’s a huge benefit — especially now people are using high-resolution iPads and monitors. It’s also a bonus for responsive designs and your logo or chart can scale accordingly.
2. Designer Tools
But anyone can create an SVG. Many of the tools are free and offer custom animation facilities. Have a play with:
3. Language/Framework Support
4. Browser Support
SVG and canvas elements are supported by all the HTML5 browsers. Neither have native support in IE8 and below, but shims such as Raphaël are available.
While that’s not necessarily a case for choosing SVG over canvas, you certainly can’t reject SVGs on the basis of browser support.
5. Accessibility and SEO
SVGs are accessible: text remains text, and something should appear even when your browser doesn’t support every element.
Humans and machines can understand SVG code even if they can’t render it. Search engines such as Google already parse SVGs but canvas elements will always require a fallback.
6. DOM Handling
SVGs have a DOM so it’s easy to attach event handlers and manipulate elements like you would for other HTML block. To move an item you simply change its co-ordinates.
The same is not true for canvas. To determine whether your mouse cursor is over an object, you need to compare the two locations and react accordingly — perhaps re-drawing the whole of the canvas again.
7. It’s More of What You Know…
Canvas manipulation isn’t difficult but it requires a different mindset and you’ll need to learn the API.
…and the Future Looks Bright for SVG
The technology may have been around for more than a decade, but SVG developments continue to advance. Browser vendors are adding support for CSS backgrounds and inline integration as well as implementing mobile engines, animations, transforms and filters.
Canvas is also evolving but it remains a self-contained programmable bit-mapped image element. That will always impose limitations.
SVGs certainly aren’t necessarily the best solution in all situations. If you’re animating hundreds of items — perhaps for a firework or explosion effect — canvas will always be quicker because it’s not constrained by the number of DOM elements the browser can handle. Canvas will generally be the best choice for fast action games.
However, SVGs remain a better alternative for logos or charts with fewer intensive effects. They’re not as trendy as canvas but that’s no reason to avoid them.
Look out for some new SVG tutorials on SitePoint soon…