HTML5 SVG vs Canvas for lots of lines?

Question: Is the canvas more suitable than svg in the following case?

Case: I am drawing a diagram (using the d3js library) similar to this (but with much more data):

http://mbostock.github.com/d3/talk/20111116/iris-parallel.html

It is based on svg, and it works great for several thousand lines (up to 5000), adding extra lines (svg path) drastically reduces performance (page scrolling becomes slow)

Keep in mind: I need to add mouse events (which is convenient in svg)

+4
source share
3 answers

Usually svg better for vector images, as in your example. However, canvas has many advantages in modern browsers, such as hardware acceleration, so for drawing lines while zooming, the panning effect. performance is not required to use canvas .

Mouse events can be sick with canvas , since you need to manually track everything, so using 5000+ dots with canvas will not be fun. The component will be as soon as the glasses are drawn, if you draw them only after the page behaves perfectly, regardless of the number of lines, since they are all drawn on a bitmap and are not part of the DOM .

Honestly, the best way to find this is to check that you are currently using the canvas.

+4
source

When performance becomes a problem, switching to canvas can be an option. In this case, you can draw the canvas once. Subsequently, he was largely regarded as an image. Drawing can take some time, but you can scale it pretty quickly later. Note that you can draw SVG rendering on canvas using the context.drawImage method ( example ). That way, you can save the SVG generation code to create the SVG in the background, and then draw it on the canvas.

But keep in mind that it will not scale as beautifully as SVG once it is on canvas. When the user zooms in, they will be blurry or pixelated, depending on how the browser scales the graphics.

There are two ways to click events on the canvas. Or save an array of targeted clicks, and add an onclick event handler to the canvas. When a click occurs, iterate through the array and check which one is closest to the coordinates of the click.

Another option is to use delete areas . They must be defined as polygonal paths.

+2
source

+1 to all of the above. I saw amazing performance when using canvas over SVG and over image compositing using the DOM.

About manipulating a canvas image with mouse events, I think the best approach to the image you describe is to abstract it using the following library:

Keep your code away from the canvas itself and let the library think.

+1
source

All Articles