Search code examples
htmlcanvassvg

What is the difference between SVG and HTML5 Canvas?


What are the differences between SVG and HTML5 Canvas? They both seem to do the same to me. Basically, they both draw vector artwork using coordinate points.

What am I missing? What are the major differences between SVG and HTML5 Canvas? Why should I choose one over the other?


Solution

  • See Wikipedia: http://en.wikipedia.org/wiki/Canvas_element

    SVG is an earlier standard for drawing shapes in browsers. However, SVG is at a fundamentally higher level because each drawn shape is remembered as an object in a scene graph or DOM, which is subsequently rendered to a bit map. This means that if attributes of an SVG object are changed, the browser can automatically re-render the scene.

    In the example above, once the rectangle is drawn, the fact that it was drawn is forgotten by the system. If its position were to be changed, the entire scene would need to be redrawn, including any objects that might have been covered by the rectangle. But in the equivalent SVG case, one could simply change the position attributes of the rectangle and the browser would determine how to repaint it. It is also possible to paint a canvas in layers and then recreate specific layers.

    SVG images are represented in XML, and complex scenes can be created and maintained with XML editing tools.

    The SVG scene graph enables event handlers to be associated with objects, so a rectangle may respond to an onClick event. To get the same functionality with canvas, one must manually match the coordinates of the mouse click with the coordinates of the drawn rectangle to determine whether it was clicked.

    Conceptually, canvas is a lower level protocol upon which SVG might be built.[citation needed] However, this is not (normally) the case—they are independent standards. The situation is complicated because there are scene graph libraries for Canvas, and SVG has some bit map manipulation functionality.

    UPDATE: I use SVG because of its markup language abilities - it can be processed by XSLT and can hold other markup in its nodes. Similarly I can hold SVG in my markup (chemistry). This allows me to manipulate SVG attributes (e.g. rendering) by combinations of markup. This may be possible in Canvas but I suspect that it's a lot harder.