JUMP START HTML5 (2014)
Chapter 21 Canvas & SVG: Canvas or SVG?
As we've seen, both canvas and SVG can do similar things. So how do you decide which to use?
Firstly, let's look at how each one is defined:
· SVG is short for Scalable Vector Graphics and is a language that's used to describe graphics in XML.
Now that really doesn't tell you a great deal about the differences between them and how they can each be used, so let's look at it in a little more depth. In SVG, drawn shapes are remembered as objects and therefore, if the attributes of that object change, the browser can then re-render the shape automatically. However, as canvas elements are drawn pixel-by-pixel, then any changes that are made will require the entire scene to be redrawn.
Bear in mind that SVG is fully scalable, unlike canvas, and so SVG may very well be a better choice if you're designing a responsive site that has graphics that need to scale.
SVG files are XML—which is simply structured text. They can be pre-prepared in a vector graphics package such as Illustrator or Inkscape, or you can dynamically create them on the server using any language: Node.js, PHP, Ruby, Python, C#, Java, BASIC, Cobol etc.
In general, SVG is ideal for:
· static images, especially within responsive and fluid layouts
· images which can be resized to any dimension without losing quality
· projects which benefit from DOM methods to attach events and manipulate objects
· projects which create images server-side
· projects where accessibility and SEO are important
Canvas is ideal for:
· bitmap images, editing photographs or any operation which requires pixel-level manipulation
· images which must be created and animated on-the-fly
· graphically-intense applications, such as games
Sometimes, there will not be an obvious best solution and either technology can be used. Remember neither is mutually exclusive; you can use both canvas and SVG on the same page at the same time, e.g. multiple animated canvas elements over a static SVG background. The only limit is your imagination.
I hope you've enjoyed this book and are ready to get started with some awesome examples of your own.
Thanks for reading, and have fun with canvas and SVG!