The Karma Project: Code Less, Teach More

December 17, 2009

Karma Tutorial Part II: Comparing HTML 5 Canvas and SVG

Filed under: News — bryanwb @ 4:40 am

This article is the second in a series of four

  1. Introduction to karma.js
  2. This article,Comparing HTML 5 Canvas and SVG
  3. Digging into Inkscape
  4. JavaScript and SVG

In “Introduction to karma.js” I gave an overview of how the library works. In this article, I want to give an overview of the relative merits of HTML 5 <canvas> and SVG in the context of creating your application. In the next article, I will walk you through the creation of a geography lesson using karma.js. You will need google chrome or Firefox > 3.5 and the following libraries:

  • karma.js
  • jquery-1.3.2.js
  • jquery.svg.js
  • jquery.svgdom.js

You can grab them all here

This tutorial will require a basic understanding of css selectors, jQuery, and the SVG editing application inkscape. karma.js works fine without jQuery but this tutorial makes relies on both jQuery and the jQuery plugin jQuery SVG. If you use chromium, make sure you have web-inspector installed. If you are a Firefoxer, you will need Firebug.

Your Weapons, <audio>, <video>, <canvas>, and <svg>

The success of the Karma Project is contingent upon the good browser support for HTML 5 and SVG. We have seen amazing advances in web technology over the course of the last 12 months, so Karma’s prospects look good! Using SVG for web applications is not well-established, in part because SVG is very complicated specification and in part because until recently SVG has gotten very little love from the Browser vendors.

Twilight SVG: The Standard that Came Back from the Dead

SVG’s stagnation changed in a big way when Google put serious development resources behind it. One of those resources is Brad Neuberg, whom they hired in spring 2009 to evangelize for SVG and other web technologies. There is now a lot of momentum behind SVG.

HTML 5 <canvas> has a nice, simple API and it is fast. Fellow uber-nerds should be excited by the nascent WebGL specification and upcoming GPU acceleration. SVG is quite slow compared to canvas but that shouldn’t be an argument against it. Canvas is faster because it doesn’t have to save its own state. For a number of applications like this tutorial, it would take you much longer to write the same program using straight canvas and would be much harder to maintain. Further, the speed benefits may be negligible in the scope of the larger application. to roughly paraphrase Brad Neuberg, when your graphics need to maintain their state, use SVG. When your graphics don’t need to maintain their own state and are doing performance-sensitive operations, use canvas.

I particularly like the workflows that SVG enables. With SVG, you can first create your images in inkscape, then embed them in your document, then manipulate the image with your code. With canvas, you have to manually write the code to draw the image entirely with javascript code and then frequently redraw large portions of it.

Let’s walk through drawing a circle and then moving it horizontally across the screen using <canvas> and then SVG

<canvas> Example

View the Example

1. Create the element in your html, make sure you set the width and height in your markup. Your image will become incredibly distorted if you try to set the dimensions using css. I can’t remember exactly why.

<canvas id="myCanvas" width="800px" height="600px"></canvas>

2. Tell Karma about it

var k = Karma({ 
                            canvas : [ 
                                       { name : "myCircle", domId: "myCircle" }


			var MAX_X = 600;
			var myX = 30;		

	    var timerId = setInterval(function() {
               if (myX < MAX_X){
		   myX = myX + 20;  
	       } else {
                   //stop the animation
               }, 100);

View the Full Example

Please note that the above example uses the Karma API heavily, which is just wraps around the HTML 5 API to save you boatloads of typing.

SVG example

View the Example

1. Draw the circle using inkscape. I precisely choose whatever color I want with having to actually understand hexadecimal color codes.

Drawing a circle in SVG

Creating a circle in Inkscape

2. Give the circle element the id=”svgCircle” by right-clicking on the circle and choosing Object properties

Setting the Element Id in inkscape

Setting the Element Id in inkscape

3. embed in the html using the object tag

 <object id="myCircle" data="assets/svg/circle.svg" type="image/svg+xml" width="800px" height="600px"> </object>

4. Tell Karma about it

var k = Karma({ 
                            svg : [ 
                                       { name : "myCircle", domId: "myCircle" }

5. Move it! Using the translate transformation

$('#svgCircle', k.svg.myCircle.root).animate({svgTransform:'translate(400,0)'}, 5000);

View the Example

What I like about SVG is that it feels very “webby.” That is, I can manipulate the SVG DOM (Document Object Model) much the same way that I can manipulate the HTML DOM. I can also manipulate the presentation using the same css file I use for my HTML.

I must make an important caveat, SVG’s created in inkscape often do not behave in the browser as you expect them to. I suspect this is because heretofore inkscape has been primarily used to create images for non-browser contexts. That said, I believe that the inkscape team are very interested in making inkscape an integral part of the web development toolset.

I had the pleasure of meeting Josh Andler and Jon Cruz from the Inkscape team at last summer’s Google Summer of Code conference. Both were very enthusiastic about better integrating inkscape with the web workflow.


One of the great benefits of using SVG is that you can use the same css file as you do for your HTML document. To use an external css file in your SVG, you need to link it in just above the first <svg> tag.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?xml-stylesheet href="../../css/lesson.css" type="text/css"?>
<svg ......

When you use the same css file for both your HTML and SVG documents, you need to make sure your element Id’s are unique across all of them. I found it helpful to prefix my svg element Id’s with “svg.” In an application with multiple svg images embedded, I may consider prefixing each SVG element Id with “svg” followed by a short identifier for that particular image, for example “svgAlienQuestion” or “svgShipWing.”

jQuery and SVG

jQuery is a little Javascript library that has taken the webdev world by storm. The jQuery library itself is quite small and almost entirely focuses on DOM manipulation. In this regard it reminds me of the UNIX philosophy “Do one thing and do it well.” jQuery SVG is a plugin that allows you to manipulate SVG documents in much the same way you use jQuery to manipulate the HTML DOM. Pay special attention to the word “document.” Each SVG image embedded in your HTML is a separate document with its own DOM. You need to pass jQuery SVG root element for your target document so that jQuery SVG know which DOM to use.

// In this example you have 3 SVG images embedded in your HTML
// alien, ship, and map. All 3 have been passed to the Karma in the Karma({ svg : [  . . .  block

//To change the text inside the alien SVG
$('#question', k.svg.alien.root).text('Some new Text!');

//To add and event listener to the left wing of the ship
$('#leftWing', k.svg.ship.root).bind('click', function() { ....  

//hide a mountain on the map
$('#mountainEverest','display', 'none');

jQuery SVG makes SVG manipulation very intuitive to those already familiar with jQuery. One drawback to jQuery SVG is that it is not a well-supported tool. Author Keith Wood has done us all a tremendous favor by writing but as yet there isn’t a larger support community around it. I myself patched the .css() method just last weekend to work on Firefox > 3.5 and Chromium. I did not thoroughly test it and I highly doubt that the .css() method will work on Internet Explorer. SVG lovers, if you really want to see SVG adoption take off, I can’t recommend a better place to put your efforts than jQuery SVG.

You can get my patched version of jQuery SVG here and the original at Keith Wood’s site.

The Vampire’s Dilemma
Since SVG is a Vampire Specification, only recently back from the dead, documentation and examples in the HTML context are relatively scarce. Frequently, the most complete documents are the API specifications from the W3C. It is both frustrating and bewildering to work from the W3C specs as you never quite know if X browser has implemented that spec and to what degree of fidelity.

I have also found a lot more browser bugs and inconsistencies using SVG as compared to <canvas>. One glaring bug/feature, depending on how you look at it, is that chromium will not load an SVG document if its display property is set to ‘none’. Firefox will load an SVG with its display set to ‘none’. It took me a number of hours to figure out this inconsistency as it isn’t documented anywhere that I could find. No, I haven’t filed a bug on this yet but I seriously intend to. I swear on my dead pet hamster’s grave.

There is also a well-known glaring gap in the SVG 1.1 API. SVG’s <text> element does not support line wrapping for text. You have break your text manually into <textspan> elements in order to keep it from overflowing bounds of your <text> element. Luckily, there is a clever hack to get around this problem.
Thanks to Mark Finkle for this fix.

         style="font-size:20px">Some Old Text</xhtml:div>

To change out the text in the above block, I simply use a css selector and jQuery’s text() method:

 $('foreignObject #alienQuestion', k.svg.alien.root).text("Some New Text!");

That may look like a lot of boilerplate text but consider the alternative. Using <canvas> you would have have to redraw the entire canvas area in order to change text embedded in your drawing. That is a considerable waste of computational resources.

That’s it for this installment, stay tuned for Part III, where I will walk you through the creation of a geography lesson.

For further reading, I highly recommend the following resources:



  1. Nice writeup!

    Comment by Brad Neuberg — December 17, 2009 @ 5:42 am

  2. Great tutorial, keep up the great work! 🙂

    Comment by KChristophD — December 17, 2009 @ 11:05 am

  3. […] Comparing HTML 5 Canvas and SVG […]

    Pingback by Tutorial III: Digging into Inkscape « Karma Project Learn.Teach.Everything — December 18, 2009 @ 3:34 am

  4. […] This article,Comparing HTML 5 Canvas and SVG […]

    Pingback by Tutorial IV: The Adventure Continues – JavaScript and SVG « Karma Project Learn.Teach.Everything — December 18, 2009 @ 3:36 am

  5. […] This article,Comparing HTML 5 Canvas and SVG […]

    Pingback by Karma version 0.2 Released « Karma Project Learn.Teach.Everything — December 20, 2009 @ 4:23 pm

  6. “With canvas, you have to manually write the code to draw the image entirely with javascript code and then frequently redraw large portions of it.“

    Not entirely true. Opacity ( has the ability to export a javascript function to draw a vector image in a canvas. While SVG support is much more widespread, it is at least possible to use the same kind of workflow for canvas based animation.

    Comment by Paul — December 23, 2009 @ 7:29 am

    • tks Paul,

      What advantage do you gain by drawing a vector image in canvas? Is it faster overrall? Have you used this approach?

      Comment by bryanwb — December 23, 2009 @ 10:40 am

  7. This website has got some very useful info on it! Thank you for helping me!

    Comment by here — June 5, 2012 @ 7:51 pm

  8. This is a wonderful site, could you be interested in going through an interview concerning just how you produced it? If so e-mail me and my friends!

    Comment by link — June 20, 2012 @ 6:36 pm

  9. Wanted to drop a comment and let you know your Rss feed is not functioning today. I tried adding it to my Yahoo reader account but got absolutely nothing.

    Comment by click for rob shanahan — June 23, 2012 @ 1:16 am

  10. This blog site has lots of extremely useful info on it. Thanks for informing me.

    Comment by direct sales jewelry — June 24, 2012 @ 1:26 am

  11. I adore that blog site layout ! How did you make it. It is very nice!

    Comment by wow cd keys on-line — June 24, 2012 @ 6:51 am

  12. How do you make your blog site look this good! Email me if you get the chance and share your wisdom. .

    Comment by medical alert button — June 25, 2012 @ 1:14 am

  13. Heya, I just hopped over to your web page using StumbleUpon. Not somthing I might usually read, but I appreciated your thoughts none the less. Thank you for making something well worth reading.

    Comment by commercial function rooms surrey — June 26, 2012 @ 1:35 pm

  14. I adore that blog site layout ! How did you make it!? Its really cool.

    Comment by — June 26, 2012 @ 7:28 pm

  15. A insightful post there mate . Thank you for that .

    Comment by buy leather wallets — June 26, 2012 @ 8:23 pm

  16. Nice post ! Thanks for, posting on my blog page dude! I shall email you soon! I didnt realise that.

    Comment by close window — June 27, 2012 @ 6:28 am

  17. This site has a lot of very useful information on it. Cheers for helping me!

    Comment by needs — June 28, 2012 @ 1:28 am

  18. I Am Going To have to return again whenever my course load lets up – nevertheless I am getting your Rss feed so i can go through your web blog offline. Thanks.

    Comment by quickbooks consultant — June 28, 2012 @ 11:24 pm

  19. Have you given any kind of thought at all with converting your main blog into Spanish? I know a few of translaters right here which might help you do it for no cost if you wanna contact me personally.

    Comment by buy fridge freezer — June 30, 2012 @ 3:31 am

  20. I appreciate your wp format, where did you get a hold of it?

    Comment by business tax service — June 30, 2012 @ 6:37 pm

  21. I have got 1 recommendation for your site. It looks like at this time there are a few cascading stylesheet troubles when opening a number of webpages in google chrome and safari. It is working okay in internet explorer. Perhaps you can double check that.

    Comment by disney junior games — July 1, 2012 @ 2:12 am

  22. Wanted to drop a comment and let you know your Feed is not working today. I tried including it to my Yahoo reader account and got nothing.

    Comment by succeed in life — July 1, 2012 @ 5:00 am

  23. Whenever I originally left a comment I clicked the Notify me when new comments are added checkbox and currently every time a remark is added I get 4 email messages with the identical comment.

    Comment by investigate motorbike games — July 1, 2012 @ 10:42 am

  24. If you dont mind, where do you host your web page? I am searching for a good quality web host and your web site appears to be extremely fast and up most the time

    Comment by privacy — July 2, 2012 @ 8:17 pm

  25. Nice post ! Thanks for, visiting my blog man! I will email you some time! I did not realise that!

    Comment by traffic attorney — July 3, 2012 @ 4:51 am

  26. Can you message me with a few pointers about how you made your blog site look this awesome, I would be appreciative.

    Comment by dynowatt — July 3, 2012 @ 8:16 am

  27. Have you given any kind of thought at all with translating your website into Spanish? I know a couple of translaters here that will would certainly help you do it for no cost if you want to get in touch with me.

    Comment by bathroom remodeling phoenix, bathroom remodeling az, phoenix kitchen remodeling, kitchen remodeling az, home remodeling phoenix — July 4, 2012 @ 6:59 am

  28. When I open up your Rss feed it appears to be to be a lot of junk, is the problem on my side?

    Comment by like i said — July 5, 2012 @ 1:19 am

  29. Re: The person who created the remark that this was a good website actually needs to have their head reviewed.

    Comment by website — July 5, 2012 @ 9:36 pm

  30. Have you thought about adding some videos to your article? I think it might enhance everyones understanding.

    Comment by personalisation agenda — July 6, 2012 @ 10:51 am

  31. How come you dont have your website viewable in wap format? cant see anything in my iPhone.

    Comment by how to become a millionaire — July 7, 2012 @ 2:13 pm

  32. really beneficial material, in general I picture this is worthy of a bookmark, many thanks

    Comment by wedding dj athens ga — July 7, 2012 @ 7:13 pm

  33. The look for your weblog is a bit off in Epiphany. Even So I like your blog. I may have to use a normal web browser just to enjoy it.

    Comment by web address — July 8, 2012 @ 1:18 am

  34. This website is extremely cool. How was it made ?

    Comment by understandable — July 8, 2012 @ 2:06 am

  35. The structure for your blog is a tad off in Epiphany. Even So I like your website. I might have to install a normal browser just to enjoy it.

    Comment by self development — July 8, 2012 @ 1:58 pm

  36. Im getting a tiny problem. I cant get my reader to pick up your feed, Im using google reader by the way.

    Comment by forex brokers article — July 9, 2012 @ 1:00 am

  37. Wow! This blog is awesome! How do you make it look this good ?

    Comment by visit our site — July 9, 2012 @ 6:52 pm

  38. Could you message me with any hints & tips about how you made this blog site look this cool, Id be thankful!

    Comment by snow plowing franklin — July 10, 2012 @ 3:14 am

  39. I enjoy your wordpress design, where did you get a hold of it?

    Comment by cosmetic dentistry nyc — July 10, 2012 @ 7:37 am

  40. Dude! This blog site is sick. How can I make it look this good ?

    Comment by official site — July 11, 2012 @ 1:53 am

  41. How come you do not have your site viewable in mobile format? cant view anything in my phone.

    Comment by customer feedback questions — July 11, 2012 @ 3:23 am

  42. Even though I genuinely like this publish, I think there was an punctuational error close to the end of the third sentence.

    Comment by open in a new browser window — July 12, 2012 @ 3:48 am

  43. How come you do not have your web site viewable in wap format? Can not see anything in my phone.

    Comment by like us on facebook — July 12, 2012 @ 3:52 am

  44. I tried looking at your web site with my new iphone 4 and the layout does not seem to be right. Might want to check it out on WAP as well as it seems most mobile phone layouts are not really working with your web site.

    Comment by TM — July 12, 2012 @ 7:37 am

  45. It appears to me that this web site doesnt load in a Motorola Droid. Are other folks having the same problem? I like this site and dont want to have to skip it any time Im gone from my computer.

    Comment by purchase secured loans — July 12, 2012 @ 2:06 pm

  46. Have you considered including some social bookmarking links to these sites. At least for youtube.

    Comment by dog pens — July 12, 2012 @ 2:22 pm

  47. Awesome post ! Thank you for, commenting on my blog page mate! Ill message you some time! I did not know that.

    Comment by spinach recipe — July 12, 2012 @ 6:57 pm

  48. Do you have a spam issue on this site; I also am a blogger, and I was questioning your situation; we have created some great methods and we are looking to swap options with other people, be sure to shoot me an e-mail if planning to pursue.

    Comment by save on — July 13, 2012 @ 1:36 am

  49. It looks to me that this site doesnt load up in a Motorola Droid. Are other folks getting the same issue? I like this web site and dont want to have to miss it when Im gone from my computer.

    Comment by consumers — July 13, 2012 @ 7:49 am

  50. If you dont mind, where do you host your web site? I am hunting for a great host and your blog seams to be extremely fast and up just about all the time

    Comment by here's the site — July 13, 2012 @ 2:37 pm

  51. A interesting post there mate ! Thanks for it !

    Comment by flagstaff snoring doctor — July 15, 2012 @ 1:21 am

  52. Im getting a small issue. I cant get my reader to pickup your rss feed, Im using yahoo reader by the way.

    Comment by growing out gray hair — July 16, 2012 @ 1:22 am

  53. Is it fine to put a portion of this in my site if I post a reference to this web-site?

    Comment by sponsor — July 16, 2012 @ 5:33 pm

  54. If you dont mind, where do you host your site? I am shopping for a good host and your weblog appears to be extremely fast and up all the time

    Comment by appstar scam — July 16, 2012 @ 7:32 pm

  55. I think one of your ads caused my web browser to resize, you may well need to set up that on your blacklist.

    Comment by hampshire web design — July 17, 2012 @ 2:11 am

  56. Great Stuff, do you have a facebook profile?

    Comment by home care pacific palisades — July 17, 2012 @ 2:21 am

  57. Have you considered adding a few social bookmarking links to these blogs. At the very least for flickr.

    Comment by close remove frame — July 17, 2012 @ 2:58 am

  58. That may seem odd, but in fact, it is a very effective mode for
    people with some degrees of visual impairment, since when you focus on white letters, you are focussing
    on light itself. There are e – Book companies that will format your manuscript
    files into e – Book files and can even provide a cover image.
    A thought in this substance, produces the thing that
    is imaged by the thought.

    My webpage; free pdf ebook download

    Comment by free pdf ebook download — May 16, 2013 @ 9:40 pm

  59. Thank you for any other informative blog. The place else may just I get that type of information written in such an ideal
    way? I have a project that I am just now running on,
    and I have been on the glance out for such info.

    my web blog :: weight loss tips

    Comment by weight loss tips — July 2, 2013 @ 4:01 pm

  60. My name is Aline and I work as a financial advisor
    in Kirktown Of Deskford. When I am not working I
    will be writing. Excellent blog on a subject I happen to be pretty knowledgeable about.

    Also visit my webpage; accounting

    Comment by accounting — July 14, 2013 @ 1:17 pm

  61. It’s nearly impossible to find educated people for this subject, however, you seem like you know what you’re talking about!

    Comment by beautiful cheap places to live in the us — July 16, 2013 @ 9:12 pm

  62. “Karma Tutorial Part II: Comparing HTML
    5 Canvas and SVG | The Karma Project: Code Less, Teach More” truly makes me personally contemplate a somewhat extra.
    I actually treasured each and every individual element of this blog post.

    Thank you ,Chastity

    Also visit my page; Ernesto

    Comment by Ernesto — January 25, 2014 @ 4:29 pm

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Blog at

%d bloggers like this: