SVG和HTML5 Canvas中的图表 [英] Diagrams in SVG versus HTML5 Canvas

查看:168
本文介绍了SVG和HTML5 Canvas中的图表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要开始一个项目,其中我需要绘制由与行相连的圆角矩形组成的图形,当我单击一些元素时,JavaScript动作。这需要在所有现代浏览器中工作。



SVG和HTML5 Canvas似乎都能做到这一点,所以我不知道什么是最好的。



此外,我不想重新发明轮子,所以如果有图书馆做这样的事情我想知道;我看看Raphaël和一些其他JavaScript绘图库,但他们不提供我需要的所有功能。

解决方案

使用SVG,因为—作为一个模式绘图API,您可以直接将事件监听器附加到特定元素,更改特定元素的属性,并让页面神奇地更新。此外,作为基于向量的格式,它是与分辨率无关的。



通过比较,HTML5 Canvas是一个非保留模式(aka immediate-mode )绘图API;你绘制的每个像素与画布上的所有其他像素混合,没有原始形状的概念。此外,作为基于光栅的格式,您需要执行一些额外的工作,以使绘图命令针对不同的显示大小进行调整。



您必须在需要时使用Canvas:


  1. 直接设置像素(例如模糊,闪光效果)

  2. 直接获取像素(例如,读取用户的绘图以另存为PNG,对部分用于检测视频重叠的图片),或

  3. 大量对象数,不会移动太多或跟踪单个事件


  4. 请注意,您不必只选择一个或另一个。你可以在画布上绘制SVG。您可以在SVG中包含位图(图像)。您甚至可以通过< foreignElement> 在SVG中包含HTML5 Canvas。您可以拥有一个包含多个分层画布的HTML页面,以及具有透明背景的SVG元素,并混合每个画布的输出。


    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.

    解决方案

    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.

    这篇关于SVG和HTML5 Canvas中的图表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆