|

Using HTML5 Canvas vs. SVG

In this post, I will discuss some of the key features of SVG (Scalable Vector Graphics) and HTML5-Canvas based graphics. Let’s start off by explaining the basic differences between these two technologies!

Canvas

Thanks to the current hype for HTML5, Canvas is on everyone’s lips. It gets a lot of credit for being the missing technology for HTML to create all kinds of interactive graphics and content that used to need plugins like the Adobe Flash Player or others. When it comes down to its features, it is really just a grid of pixels that can be drawn on. It comes with a JavaScript API that allows you to draw certain shapes, curves and text onto it. Consequently, the name speaks for itself: It is a canvas. It’s noteworthy to point out, though, that it has no form of hierarchy when it comes to the elements drawn onto the canvas – it simply colors pixels. Therefore, there is no such thing as click events or other fine features for certain elements on the canvas because for the browser it is just one node in the DOM. In other words, it is good for creating pixel-based images.

SVG

SVG, on the other hand, is a completely different deal. SVG stands for Scalable Vector Graphics. As you can probably assume from the name, the first major difference in comparison to Canvas is that all graphics are vector-based instead of pixel-based, which means they can be scaled and skewed without losing quality. More importantly, SVG is XML-based. This means that the graphics are represented as nodes in the DOM, versus as a single node as in Canvas. Therefore you are supplied with all sorts of events such as click and mouseover for every element in the graphic. Since SVG is node-based, that also means that you have the ability to move elements around. Conveniently, SVG has its own animation markup called SMIL, which is also XML-based. With the help of this markup, you can create simple animations without using any JavaScript.

SVG is supported in most modern browsers. Older versions of Internet Explorer support a language called VML. It’s very similar to SVG but is a Microsoft proprietary format. This seems like it would be a problem but thanks to SVG libraries like Raphaël.js, you can create graphics once using JavaScript and the library uses the correct markup to create either SVG or VML based on the browser support.

How to create graphics

What matters to most developers is not necessarily the technology or how it’s implemented in the browser, but rather how hard it is for the developer to use it. As mentioned above, Canvas uses a JavaScript API to manipulate the pixels on it. SVG, on the other hand, can be written just like HTML markup, either hardcoded in the markup-file or with a little help of JavaScript using the DOM API. In many cases the uses of both technologies tend to be interactive in some way, therefore, most of the time it is JavaScript that creates the graphics. In the case of SVG, most people tend to use a framework to help them create those graphics, such as Raphaël.js. This seems to be the most advanced and widely used framework for SVG. For creating graphics and interactions with Canvas, many libraries have been written over the past few years. One of the most talked about frameworks is easel.js, which delivers a very Flash-like API and structure for creating graphics and managing interactions, such as clicks targeted on certain elements on the canvas. Like we talked about earlier, Canvas has no hierarchy when it comes to the elements drawn onto the canvas. This means frameworks, like easel.js, take it upon themselves to keep track of where the user clicks and maps that onto certain objects. Also, the movements of an element on the canvas requires the element to be entirely redrawn. These types of chores are things you don’t want to worry about when creating an application.

Canvas Examples

I think the easiest way to understand something, is by using it.

So let’s start off with a little Canvas example. What you need is a <canvas> element somewhere in the document. That would look something like this:

<canvas id="canvas" width="700" height="500"></canvas>

This provides us with a canvas with the appropriate height and width.

Quick tip: By the way, resetting the width or height, will clear the entire canvas. It will even clear the canvas when you set one of the parameters to the same value it already is.

Next, we need JavaScript to find the canvas and retrieve its Context. The Context is the class that holds the API. That would work something like this:

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

Now we can use the Context to create shapes. Let’s start off by drawing a box with the size 40 by 40 with its top left corner at 10, 10.

context.strokeRect(10, 10, 40, 40);

That was not so hard. But as you can see, once the rectangle is drawn, there is no data saved about it. Now let’s draw a more complex shape. You can start a random path by calling:

context.beginPath();

That does exactly what it says: starts a path. Now you can add commands that define the path such as:

context.moveTo(60, 60);
context.lineTo(100, 120);
context.lineTo(200, 180);

At the end, we want to close the path:

context.closePath();

It’s important to note here that we did not draw anything yet. The path gets pushed into an internal stack of drawing instructions. We can print the entire stack of drawing instructions onto the canvas by calling:

context.stroke();

So our code so far would create this:

Not necessarily a world class piece of art, but we are getting there.

Unfortunately, we don’t have time to go over the entire Canvas API but I think you get the drift. It’s not very hard to get started.

SVG Examples

As I’ve mentioned, SVG works a little bit different than Canvas. It doesn’t require any JavaScript at all because it is a markup language.

In this example, we’re going to use SVG to create the shape of a basic face. Start off by defining the SVG body:

<svg width="140" height="170">
</svg>

Now let’s add a circle with a stroke and no fill as the outline of the face. The tag obviously goes within the SVG.

<circle cx="70" cy="95" r="50" stroke="black" fill="none" />

The markup is very straight forward. You define the X/Y-position with cx  and cy, the radius r and the stoke and the fill color.

Next up are the eyes:

<circle cx="55" cy="80" r="5" stroke="black" fill="#339933" />
<circle cx="85" cy="80" r="5" stroke="black" fill="#339933" />

Finally, all we need is a line for the mouth and our basic face is complete:

<line x1="55" y1="120" x2="85" y2="120" stroke="black" />

With these few lines of code, we create something like this:

Which one to use when

SVG or Canvas – that is the question! How do you decide whether to use SVG or Canvas, and when? What it really comes down to is what technology is the right one for the job. Obviously the answer is not going to be one over the other every time. It really depends on the task you are confronted with.

Here are some things to consider that can help you decide. When I find myself in a situation where I need sprite sheets (and I am not talking about a button roll-over-effects but more about a walking character in an online game), I tend to use Canvas. Sprite sheets themselves are really hard to work out with SVG since it’s not supported naturally. And as we already know, Canvas is a pixel-based format and therefore has no problem displaying certain rectangles from a bigger image.

On the other hand, one of SVG’s biggest strengths is the ability to draw graphs of almost any kind. It does not matter if we talk about curves or pie charts representing Google’s stock last year, SVG is on your side. Since it is vector-based, SVG is really good with lines and curves. This explains why so many examples of SVG are in fact charts or graphs.

So what I do before I start a project: I ask myself if the strength of SVG (lines, curves, etc.) and the mathematical helpers that come with it (ability to display only parts of a curve, determining the length of an outline of a shape, etc.) are of any help. If yes, then I go with SVG! Why wouldn’t I use SVG in this case, even if it’s not as hyped as Canvas?

Conversely, if I find myself developing a classic jump-and-run game with lots of tiny, blinking animations then Canvas might be a better ally.

Performance

The last aspect that can’t be left out is performance. The “Which one is faster?” question that determines so many aspects of projects and features. My answer so far: it depends. I’m sorry for letting you down again! But it really does! It depends on the browsers you are targeting and how the code is written. In other words, I can’t give you an answer on this one, but on the upside: it matters increasingly less. Modern browsers increase their performance on both ends and therefore most tests end up with the same frame rate in both implementations.

So I guess in a way that is a satisfying answer – you do not need to worry about the speed any more than you already do anyway.

As you can see, both SVG and Canvas have their strengths and utility. With these two different technologies at your disposal you’ll be able to tackle a wide-variety of programming tasks. While performance speed is not a decisive factor, the question of when to use SVG over Canvas, and vice versa, can be simply answered based on what you’re trying to do and which one can help you do it better.

Safari Books Online has the content you need

Check out these HTML5 books covering Canvas and SVG, available from Safari Books Online:

HTML5 Games Most Wanted gathers the top HTML5 games developers and reveals the passion they all share for creating and coding great games. You’ll learn programming tips, tricks, and optimization techniques alongside real-world code examples that you can use in your own projects. You won’t just make games—you’ll make great games.
Whether you need an example-driven programmer’s guide or a complete desk reference, JavaScript: The Definitive Guide is the most authoritative book on the language that runs the Web. This sixth edition offers comprehensive coverage of ECMAScript 5 (the new language standard) and also the new APIs introduced in HTML5.
The Definitive Guide to HTML5 provides the breadth of information you’ll need to start creating the next generation of HTML5 websites. It covers all the base knowledge required for standards-compliant, semantic, modern website creation. It also covers the full HTML5 ecosystem and the associated APIs that complement the core HTML5 language.
HTML5 is revolutionizing the way web applications are developed, and HTML5 Canvas puts you right in the middle the action. You’ll learn how to build interactive multimedia applications with HTML5′s Canvas, using this new element to draw, animate, compose images, and more. You’ll also learn the best way to use existing JavaScript libraries, as well as how to incorporate related aspects such as audio and video.
HTML5 will transform web and mobile gaming. As new browsers rapidly adopt it, HTML5 will do everything “legacy” technologies such as Flash and Silverlight have done—and much more. In Learning HTML5 Game Programming, pioneering developer James L. Williams gives you all the knowledge, code, and insights you’ll need to get started fast!

About this author

Mathias Paumgarten, co-author of HTML5 Games Most Wanted, is a web developer who focuses on front-end and interaction development. Starting with a background in Flash development, he now focuses mainly on JavaScript. He found his passion for the web and code-based animation at a very young age and made his way from a small town in Austria all the way to New York City where he currently works for Firstborn Multimedia as a Creative Developer. Part of his work can be found at https://github.com/MathiasPaumgarten and http://www.mathias-paumgarten.com/.

About Safari Books Online

Safari Books Online is an online learning library that provides access to thousands of technical, engineering, business, and digital media books and training videos. Get the latest information on topics like Windows 8, Android Development, iOS Development, Cloud Computing, HTML5, and so much more – sometimes even before the book is published or on bookshelves. Learn something new today with a free subscription to Safari Books Online.
|

One Response to Using HTML5 Canvas vs. SVG

  1. Pingback: SVG Tip: Introduction to Raphaël.js | Safari Books Online's Official Blog