HTML5 Canvas vs. SVG: Choose the Best Tool for the Job

By Robert Gravelle

The canvas itself is an HTML element that you can place anywhere in your page, just as with most other elements. The drawing part is accomplished using either a 2D or 3D (WebGL) drawing context. Right now we'll focus on 2D because it has much more browser support, with 3D being still in its infancy. Here's some code that displays a JPEG image in grayscale:

<script type="text/javascript">  
  window.onload = function(){
      //try and create a canvas element
      var testCanvas  = document.createElement('canvas'); 
       
      //check if object supports getContext() method  
      if (testCanvas.getContext !== undefined) {
        var canvas = document.getElementById("effectsCanvas");
        var context = canvas.getContext("2d");
        
        canvas.style.border = "2px solid blue";
        
        var destX = 0;
        var destY = 0;
        var imageObj = new Image();
     
        imageObj.onload = function(){
            context.drawImage(imageObj, destX, destY);
            var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
        	var pixels  = imgData.data;
        	for (var i = 0, n = pixels.length; i < n; i += 4) {
            	var grayscale = pixels[i  ] * .3 + pixels[i+1] * .59 + pixels[i+2] * .11;
            	pixels[i  ] = grayscale; 	// red
            	pixels[i+1] = grayscale; 	// green
            	pixels[i+2] = grayscale; 	// blue
            	// alpha
        	}
        	context.putImageData(imgData, 0, 0);
        };
        imageObj.src = "Rob_at_Greenfields.jpg";
      }
      else {
        document.writeln('You are plum outta luck, cuz your browser does not support the canvas element.');
      }
  }; 
</script> 
</head>
<body>
<h1>HTML5 Canvas Effects Demo</h1>
<canvas id="effectsCanvas" width="500" height="550" > </canvas>  

SVG

The following example creates an oval with a linear gradient using SVG:

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
  <defs>
    <linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
      <stop offset="0%" style="stop-color:rgb(255,255,0);stop-opacity:1" />
      <stop offset="100%" style="stop-color:rgb(255,0,0);stop-opacity:1" />
    </linearGradient>
  </defs>
  <ellipse cx="200" cy="70" rx="85" ry="55" fill="url(#grad1)" />
</svg>

 

Comparing the Differences

 

SVG Is Vector-based, Canvas Manipulates Pixels

What's the difference, you ask? Remember those old vector video games like asteroids and Tempest. No? OK, I'm getting up there! Anyway, those were based on bright line drawings. One of the reasons for their popularity was that they looked quite different from typical games at the time. With regards to SVG and Canvas, the differences are a lot less dramatic visually, as you can load bitmaps in SVG, and you can draw lines using the canvas API. However, creating the image may be easier using one technology over the other, depending on whether your graphic is mainly line-based or more image-like.

 

SVG Relies on Files, Canvas Uses Pure Scripting

SVG images are defined in XML. As a result, every SVG element is appended to the Document Object Model (DOM) and can be manipulated using a combination of JavaScript and CSS. Moreover, you can attach an event handlers to a SVG element or update its properties based on another document event. Canvas, on the other hand, is a simple graphics API. It draws pixels (extremely well I might add) and nothing more. Hence, there's no way to alter existing drawings or react to events. If you want to update the Canvas image, you have to redraw it.

 

Other Considerations

SVGs are considered to be more accessible because they support text. In the event that the browser does not support SVG, text content will still be displayed. The Canvas is dependent on JavaScript, so there can be an issue if the user has disabled JavaScript or uses an assistive device such as a reader that cannot interpret the JavaScript output. However, that can be remedied by including the <NOSCRIPT> tag. If you want to present the best user experience for those with JavaScript turned off, SVG would be your best choice.

For front-end designers, there's no question that SVG would be easier to configure, due to XML's high readability. This is the same reason that Frameworks like Spring have been so popular these last few years; pretty much anyone can use them. Canvas images are created programmatically and require some programming expertise that is more suited to a developer.

 

Conclusion

I've tried to provide some options here that you can hopefully apply to your own skillset and predispositions. There is no black and white answer to be found, so you'll have to weigh your options before committing to any one technology. Consider that SVG will result in slower rendering as document complexity increases due to SVG's integration into the DOM. Hence, SVG would probably not be best for dynamic applications like games. Downsides of the Canvas include poor text rendering capability, lack of animation, as well as mediocre accessibility support. The best advice I can give you is to choose the one that not only best fits the task at hand, but your own comfort level as well.


If you enjoyed this article, please contribute to Rob's less lucrative music career by purchasing one of Rob's cover or original songs from iTunes.com for only 0.99 cents each.

Rob Gravelle resides in Ottawa, Canada, and is the founder of GravelleConsulting.com. Rob has built systems for Intelligence-related organizations such as Canada Border Services, CSIS as well as for numerous commercial businesses. Email Rob to receive a free estimate on your software project. Should you hire Rob and his firm, you'll receive 15% off for mentioning that you heard about it here!

In his spare time, Rob has become an accomplished guitar player, and has released several CDs. His former band, Ivory Knight, was rated as one Canada's top hard rock and metal groups by Brave Words magazine (issue #92).

Rob uses and recommends MochaHost, which provides Web Hosting at $3.10 per month, 2 LifeTime Free Domains, and 6 Months Free!



Make a Comment

Loading Comments...

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
  •  
  •  
  •