Search code examples
svgchartshtml5-canvasgoogle-visualizationjqplot

SVG vs HTML5 Canvas Based Charts


I have to draw charts on browser using a python backend (which may not matter here). There are numerous libraries like JQPlot, D3, Google Charts for achieving this.

But if you classify them, they are either HTML5 Canvas based or SVG based. Both are important technologies in their own space. But

for charting as a subject, shall I go with SVG based libraries or 
HTML5 Canvas based libraries. What are downside and benefits of 
both approaches. 

I don't have any prior experience with charting and don't want to hit the wall after I start the project.


Solution

  • Projects with a large amount of data may favor canvas. SVG approaches typically create a DOM node per point (unless you make paths), which can lead to:

    1. An explosion in the size of your DOM tree

    2. Performance problems

    Using a path, you can get around this problem, but then you lose interactivity.

    Say you're building a stock chart. If you are talking about a chart with, say... max 5 years and end of trade data samples only, I think the answer is clearly SVG. If you're talking about looking at Walmart's historical data from day one of trading or doing full trade information per minute, you are going to have to really look carefully at SVG. Probably will have to employ fancy memory management and a fetch-on-demand approach as SVG will fall apart, particularly if you go one sample to one SVG node.

    If interactivity is a requirement, SVG easily has the edge, given:

    • It is a retained mode API
    • You can use typical event handlers
    • You can add/remove nodes easily, etc.

    Of course, you see that if you require full interactivity, it may go against mechanisms that allow SVG to scale, like path collapsing, so there is an inherent tension here.

    There is going to be a trade-off in extremes. If size is small, the answer is SVG hands-down. If size is large and no interactivity, the answer is SVG with path drawing only or using Canvas. If size is large and interactivity is required, you have to go canvas or tricky SVG, which is complex in either case.

    Some libraries out there offer both canvas and SVG renders, such as ZingChart and Dojo. Others tend to stick with just one of the two options.