Diagrams in SVG versus HTML5 Canvas

2019-06-18 12:19发布

I want to start a project where I need to draw diagrams consisting of rounded rectangles connected with lines and a JavaScript action when I click some elements. This needs to work in all modern browsers.

Both SVG and HTML5 Canvas seem to be able to do this so I wonder what would be best.

Also I don't want to reinvent the wheel, so if there are libraries that do such things I would like to know; I took a look at Raphaël and some other JavaScript drawing libraries but they don't give all the functionality I need. In Google's API there is such a tool but it is very limited.

标签: html5 canvas svg
1条回答
闹够了就滚
2楼-- · 2019-06-18 12:41

Use SVG because—as a retained-mode drawing API—you can attach event listeners directly to specific elements, and change properties of specific elements and have the page magically update. Further, as a vector-based format, it is resolution-independent.

HTML5 Canvas, by comparison, is a non-retained-mode (aka immediate-mode) drawing API; every pixel you draw is blended with all other pixels on the canvas, with no concept of the original shape. Further, as a raster-based format, you would need to do some extra work to get the drawing commands to adjust for different display sizes.

In general, you should use Canvas if and only if you need:

  1. Direct setting of pixels (e.g. blurs, sparkly effects), or
  2. Direct getting of pixels (e.g. reading a user's drawing to save as a PNG, sampling portions of the image to detect visual overlaps), or
  3. massive number of 'objects' that won't move much or track individual events (SVG can be slow to redraw with thousands of objects).

Note also that you don't have to choose only one or the other. You can draw SVG onto canvas. You can include bitmaps (images) in SVG. You can even include HTML5 Canvas in SVG via <foreignElement>. You can have a single HTML page with multiple layered canvases and SVG elements with transparent backgrounds, intermingling the output of each.

查看更多
登录 后发表回答