Html SVG 和 HTML5 Canvas 有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4996374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the difference between SVG and HTML5 Canvas?
提问by zeckdude
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.
SVG 和 HTML5 Canvas 有什么区别?他们似乎都对我做同样的事情。基本上,他们都使用坐标点绘制矢量图。
What am I missing? What are the major differences between SVG and HTML5 Canvas? Why should I choose one over the other?
我错过了什么?SVG 和 HTML5 Canvas 之间的主要区别是什么?为什么我应该选择一个而不是另一个?
采纳答案by peter.murray.rust
See Wikipedia: http://en.wikipedia.org/wiki/Canvas_element
参见维基百科: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.
SVG 是早期用于在浏览器中绘制形状的标准。然而,SVG 处于更高的层次,因为每个绘制的形状都被记住为场景图或 DOM 中的一个对象,随后将其渲染为位图。这意味着如果 SVG 对象的属性发生更改,浏览器可以自动重新渲染场景。
在上面的例子中,一旦矩形被绘制,系统就会忘记它被绘制的事实。如果要更改其位置,则需要重新绘制整个场景,包括可能已被矩形覆盖的任何对象。但是在等效的 SVG 情况下,可以简单地更改矩形的位置属性,浏览器将决定如何重新绘制它。也可以按层绘制画布,然后重新创建特定层。
SVG 图像以 XML 表示,可以使用 XML 编辑工具创建和维护复杂的场景。
SVG 场景图使事件处理程序能够与对象相关联,因此矩形可以响应 onClick 事件。要使用画布获得相同的功能,必须手动将鼠标单击的坐标与绘制的矩形的坐标进行匹配,以确定它是否被单击。
从概念上讲,canvas 是一个较低级别的协议,可以在其上构建 SVG。[需要引用] 然而,情况并非(通常)——它们是独立的标准。情况很复杂,因为 Canvas 有场景图库,而 SVG 有一些位图操作功能。
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.
更新:我使用 SVG 是因为它的标记语言能力 - 它可以由 XSLT 处理并且可以在其节点中保存其他标记。同样,我可以在我的标记(化学)中保存 SVG。这允许我通过标记的组合来操作 SVG 属性(例如渲染)。这在 Canvas 中是可能的,但我怀疑它要困难得多。
回答by JohnnySoftware
SVG is like a "draw" program. The drawing is specified as drawing instructions for each shape and any part of any shape can be changed. Drawings are shape-oriented.
SVG 就像一个“绘图”程序。绘图被指定为每个形状的绘图指令,任何形状的任何部分都可以更改。图纸是面向形状的。
Canvas is like a "paint" program. Once the pixels hit the screen, that is your drawing. You cannot change shapes except by overwriting them with other pixels. Paintings are pixel-oriented.
Canvas 就像一个“绘画”程序。一旦像素击中屏幕,这就是您的绘图。您不能更改形状,除非用其他像素覆盖它们。绘画是面向像素的。
Being able to change drawings is very important for some programs; e.g. drafting apps, diagramming tools, etc. So SVG has an advantage here.
能够更改图纸对于某些程序非常重要;例如绘图应用程序、图表工具等。因此 SVG 在这里具有优势。
Being able to control individual pixels is important for some artistic programs.
能够控制单个像素对于某些艺术程序很重要。
Getting great animation performance for user-manipulation via mouse drags is easier with Canvas than SVG.
使用 Canvas 比使用 SVG 更容易通过鼠标拖动获得出色的用户操作动画性能。
A single pixel on the computer screen will often consume 4 bytes of information and a computer screen these days takes several megabytes. So Canvas might be inconvenient if you want to let the user edit an image and then upload it again.
计算机屏幕上的单个像素通常会消耗 4 字节的信息,而如今的计算机屏幕需要几兆字节。因此,如果您想让用户编辑图像然后再次上传,则 Canvas 可能不方便。
By contrast, drawing a handful of shapes that cover the entire screen using SVG takes up few bytes, downloads quickly, and can be uploaded again easily with the same advantages going in that direction as when it comes down on the other direction. So SVG can be faster than Canvas.
相比之下,使用 SVG 绘制一些覆盖整个屏幕的形状会占用很少的字节,下载速度很快,并且可以轻松地再次上传,在该方向上具有与在另一个方向上相同的优势。所以SVG可以比Canvas更快。
Google implemented Google Maps with SVG. That gives the web app its zippy performance and smooth scrolling.
谷歌使用 SVG 实现了谷歌地图。这为 Web 应用程序提供了出色的性能和平滑的滚动。
回答by Fizer Khan
High Level Summary of Canvas vs. SVG
Canvas 与 SVG 的高级总结
Canvas
帆布
- Pixel based (Dynamic .png)
- Single HTML element.(Inspect element in Developer tool. You can see only canvas tag)
- Modified through script only
- Event model/user interaction is granular (x,y)
- Performance is better with smaller surface, a larger number of objects (>10k), or both
- 基于像素(动态 .png)
- 单个 HTML 元素。(在 Developer tool 中检查元素。您只能看到 canvas 标签)
- 仅通过脚本修改
- 事件模型/用户交互是细粒度的 (x,y)
- 较小的表面、较多的对象 (>10k) 或两者兼有时,性能会更好
SVG
SVG
- Shape based
- Multiple graphical elements, which become part of the DOM
- Modified through script and CSS
- Event model/user interaction is abstracted (rect, path)
- Performance is better with smaller number of objects (<10k), a larger surface, or both
- 基于形状
- 多个图形元素,成为 DOM 的一部分
- 通过脚本和CSS修改
- 事件模型/用户交互被抽象(rect,path)
- 使用较少数量的对象 (<10k)、较大的表面或两者兼有时,性能会更好
For detailed difference, read http://msdn.microsoft.com/en-us/library/ie/gg193983(v=vs.85).aspx
有关详细差异,请阅读http://msdn.microsoft.com/en-us/library/ie/gg193983(v=vs.85).aspx
回答by Erik Dahlstr?m
There's a difference in what they are, and what they do for you.
它们是什么,它们为你做什么是有区别的。
- SVG is a document format for scalable vector graphics.
- Canvas is a javascript API for drawing vector graphics to a bitmap of a specific size.
- SVG 是一种用于可缩放矢量图形的文档格式。
- Canvas 是一个 javascript API,用于将矢量图形绘制为特定大小的位图。
To elaborate a bit, on format versus API:
详细说明一下,关于格式与 API:
With svg you can view, save and edit the file in many different tools. With canvas you just draw, and nothing is retained about what you just did apart from the resulting image on the screen. You can animate both, SVG handles the redrawing for you by just looking at the elements and attributes specified, while with canvas you have to redraw each frame yourself using the API. You can scale both, but SVG does it automatically, while with canvas again, you have to re-issue the drawing commands for the given size.
使用 svg,您可以在许多不同的工具中查看、保存和编辑文件。用画布你只是画画,除了屏幕上的结果图像之外,你刚刚所做的一切都没有保留。您可以为两者设置动画,SVG 只需查看指定的元素和属性即可为您处理重绘,而对于 canvas,您必须使用 API 自己重绘每一帧。您可以缩放两者,但 SVG 会自动进行,而再次使用画布时,您必须重新发出给定大小的绘图命令。
回答by Sam007
Two things that hit me the most for SVG and Canvas were,
SVG 和 Canvas 最让我印象深刻的两件事是,
Ability to use Canvas without the DOM, where as SVG depends heavily on DOM and as the complexity increases the performance slows down. Like in game design.
能够在没有 DOM 的情况下使用 Canvas,因为 SVG 严重依赖于 DOM,并且随着复杂性的增加,性能会降低。就像在游戏设计中一样。
Advantage of using SVG would be that resolution remains the same across platforms which lacks in Canvas.
使用 SVG 的优点是分辨率在 Canvas 所缺乏的平台上保持不变。
Lot more detail is provided in this site. http://dev.opera.com/articles/view/svg-or-canvas-choosing-between-the-two/
本网站提供了更多详细信息。http://dev.opera.com/articles/view/svg-or-canvas-choosing-between-the-two/
回答by Aji
It is absolutely depends on your need/requirement.
这绝对取决于您的需要/要求。
If you want to just show an image/chart on a screen then recommended approach is canvas. (Example is PNG, GIF, BMP etc.)
If you want to extend the features of your graphics for example if you mouse over on the chart want to zoom certain area without spoil display quality then you select SVG. (Good example is AutoCAD, Visio, GIS files).
如果您只想在屏幕上显示图像/图表,那么推荐的方法是画布。(例如 PNG、GIF、BMP 等)
如果您想扩展图形的功能,例如,如果您将鼠标悬停在图表上想要在不破坏显示质量的情况下缩放特定区域,那么您可以选择 SVG。(很好的例子是 AutoCAD、Visio、GIS 文件)。
If you want build a dynamic flow diagram creator tool with shape connector it is better to select SVG rather than CANVAS.
如果您想使用形状连接器构建动态流程图创建工具,最好选择 SVG 而不是 CANVAS。
When the size of the screen increases, canvas begins to degrade as more pixels need to be drawn.
When the number of objects increases on the screen, SVG begins to
degrade as we are continually adding them to the DOM.
当屏幕尺寸增加时,画布开始退化,因为需要绘制更多像素。
当屏幕上的对象数量增加时,SVG 开始
退化,因为我们不断将它们添加到 DOM 中。
Also please refer : http://msdn.microsoft.com/en-us/library/gg193983(v=vs.85).aspx
另请参阅:http: //msdn.microsoft.com/en-us/library/gg193983(v=vs.85).aspx
回答by Purushoth
SVG
SVG
Based on use case SVG is used for logos, charts because its vector graphics you draw and forgot about it. When view port change like re-sizing(or zoom) it will adjust itself and no need to redraw.
基于用例,SVG 用于徽标、图表,因为您绘制并忘记了它的矢量图形。当视口改变如重新调整大小(或缩放)时,它会自行调整,无需重新绘制。
Canvas
帆布
Canvas is bitmap (or raster) it done by painting of pixels to the screen. It is used to develop games or graphics experience (https://www.chromeexperiments.com/webgl) in a given area it paints pixel and changes by redraw it another. Since its a raster type we need to redraw entirely as view port changes.
画布是位图(或光栅),它通过将像素绘制到屏幕上来完成。它用于在给定区域中开发游戏或图形体验(https://www.chromeexperiments.com/webgl),它绘制像素并通过重新绘制另一个像素来改变。由于它是一种光栅类型,我们需要在视口变化时完全重绘。
Reference
参考
http://www.sitepoint.com/7-reasons-to-consider-svgs-instead-of-canvas
http://www.sitepoint.com/7-reasons-to-think-svgs-instead-of-canvas
http://en.wikipedia.org/wiki/WebGL
http://en.wikipedia.org/wiki/WebGL
http://vector-conversions.com/vectorizing/raster_vs_vector.html
http://vector-conversions.com/vectorizing/raster_vs_vector.html
回答by ceving
SVG
is a specification of a drawing like a file format. A SVG is a document. You can exchange SVG files like HTML files. And additionally because SVG elements and HTML elements share the same the DOM API, it is possible to use JavaScript to generate a SVG DOM in the same way as it is possible to create a HTML DOM. But you do not need JavaScript to generate SVG file. A simple text editor is enough to write a SVG. But you need at least a calculator to calculate the coordinates of the shapes in the drawing.
SVG
是像文件格式一样的绘图规范。SVG 是一个文档。您可以像 HTML 文件一样交换 SVG 文件。此外,由于 SVG 元素和 HTML 元素共享相同的 DOM API,因此可以使用 JavaScript 以与创建 HTML DOM 相同的方式生成 SVG DOM。但是您不需要 JavaScript 来生成 SVG 文件。一个简单的文本编辑器足以编写一个 SVG。但是你至少需要一个计算器来计算图中形状的坐标。
CANVAS
is just a drawing area. It it necessary to use JavaScript to generate the contents of a canvas. You can not exchange a canvas. It is no document. And the elements of the canvas are not part of the DOM tree. You can not use the DOM API to manipulate the contents of a canvas. Instead you have to use a dedicated canvas API to draw shapes into the canvas.
CANVAS
只是一个绘图区。有必要使用 JavaScript 来生成画布的内容。你不能交换画布。它不是文件。并且画布的元素不是 DOM 树的一部分。您不能使用 DOM API 来操作画布的内容。相反,您必须使用专用的画布 API 将形状绘制到画布中。
The advantage of a SVG
is, that you can exchange the drawing as a document. The advantage of the CANVAS
is, that is has a less verbose JavaScript API to generate the contents.
a 的优点SVG
是,您可以将图纸作为文档进行交换。的优点CANVAS
是,它有一个不太冗长的 JavaScript API 来生成内容。
Here is an example, which shows that you can achieve similar results, but the way how to do it in JavaScript is very different.
这是一个示例,它表明您可以实现类似的结果,但是在 JavaScript 中实现的方式却大不相同。
// Italic S in SVG
(function () {
const ns='http://www.w3.org/2000/svg';
let s = document.querySelector('svg');
let p = document.createElementNS (ns, 'path');
p.setAttribute ('id', 'arc');
p.setAttribute ('d', 'M 0.9 -0.9 a 0.8,0.4 -10 0,0 -0.9,0.9');
s.appendChild (p);
let u = document.createElementNS (ns, 'use');
u.setAttribute ('href', '#arc');
u.setAttribute ('transform', 'rotate(180)');
s.appendChild (u);
})();
// Italic S in CANVAS
(function () {
let c = document.querySelector('canvas');
let w = c.width = c.clientWidth;
let h = c.height = c.clientHeight;
let x = c.getContext('2d');
x.lineWidth = 0.05 * w;
x.moveTo (w/2, h/2);
x.bezierCurveTo (w*0.02, h*0.4,
w*0.4, -h*0.02,
w*0.95, h*0.05);
x.moveTo (w/2, h/2);
x.bezierCurveTo (w*(1-0.02), h*(1-0.4),
w*(1-0.4), h*(1+0.02),
w*(1-0.95), h*(1-0.05));
x.stroke();
})();
svg, canvas {
width: 3em;
height: 3em;
}
svg {
vertical-align: text-top;
stroke: black;
stroke-width: 0.1;
fill: none;
}
canvas {
vertical-align: text-bottom;
}
div {
float: left;
}
<div><svg viewBox="-1 -1 2 2"></svg>VG</div>
<div>CANVA<canvas></canvas></div>
As you can see the result is almost the same, but the JavaScript code is completely different.
如您所见,结果几乎相同,但 JavaScript 代码完全不同。
SVG is created with the DOM API using createElement
, setAttribute
and appendChild
. All graphics are in the attribute strings. SVG has more powerful primitives. The CANVAS for example has nothing equivalent to the SVG arc path. The CANVAS example tries to emulate the SVG arc with a Bezier curve. In SVG you can reuse elements in order to transform them. In the CANVAS you can not reuse elements. Instead you have to write a JavaScript function in order to call it twice. SVG has a viewBox
which allows to use normalized coordinates, which simplifies rotations. In the CANVAS you have to calculate the coordinates yourself based of the clientWidth
and clientHeight
. And you can style all SVG elements with CSS. In the CANVAS you can not style anything with CSS. Because SVG is a DOM, you can assign event handlers to all SVG elements. The elements in the CANVAS have no DOM and no DOM event handlers.
SVG 是使用 DOM API 创建的,使用createElement
,setAttribute
和appendChild
。所有图形都在属性字符串中。SVG 有更强大的原语。例如,CANVAS 没有任何等同于 SVG 弧形路径的东西。CANVAS 示例尝试使用贝塞尔曲线模拟 SVG 弧。在 SVG 中,您可以重用元素来转换它们。在 CANVAS 中你不能重用元素。相反,您必须编写一个 JavaScript 函数才能调用它两次。SVGviewBox
允许使用标准化坐标,从而简化旋转。在 CANVAS 中,您必须根据clientWidth
和自己计算坐标clientHeight
. 您可以使用 CSS 设置所有 SVG 元素的样式。在 CANVAS 中,您不能使用 CSS 设置任何样式。因为 SVG 是一个 DOM,所以您可以为所有 SVG 元素分配事件处理程序。CANVAS 中的元素没有 DOM 和 DOM 事件处理程序。
But on the other hand the CANVAS code is much easier to read. You do not need to care about XML name spaces. And you can directly call the graphics functions, because you do not need to build a DOM.
但另一方面,CANVAS 代码更容易阅读。您不需要关心 XML 名称空间。并且您可以直接调用图形函数,因为您不需要构建 DOM。
The lesson is clear: if you quickly want to draw some graphics, use the CANVAS. If you need to share the graphics, like to style it with CSS or want to use DOM event handlers in your graphics, build an SVG.
教训很清楚:如果您想快速绘制一些图形,请使用 CANVAS。如果您需要共享图形,例如使用 CSS 设置样式或希望在图形中使用 DOM 事件处理程序,请构建一个 SVG。
回答by Vasundhara
SVG
It is Object Model-based.
Is suitable for using large rendering areas.
SVG provides any support for event handlers .
Modification is allowed through script and CSS.
SVG has Better scalability
SVG is Vector based (composed of shapes).
SVG is not suitable for Games graphics.
SVG does not depend on resolution.
SVG is capable for API animation.
SVG is suitable for printing with high quality and any resolution.
SVG
它是基于对象模型的。
适合使用大的渲染区域。
SVG 为事件处理程序提供任何支持。
允许通过脚本和 CSS 进行修改。
SVG 具有更好的可扩展性
SVG 是基于矢量的(由形状组成)。
SVG 不适合游戏图形。SVG 不依赖于分辨率。
SVG 能够实现 API 动画。
SVG 适用于高质量和任何分辨率的打印。
Canvas elements
画布元素
It is pixel based.
它是基于像素的。
Is suitable for using small rendering
适合使用小型渲染
Canvas does not provide any recourse for event handlers.
Canvas 不为事件处理程序提供任何追索权。
Modification is allowed through script only.
仅允许通过脚本进行修改。
Canvas has poor scalability.
Canvas 的可扩展性很差。
Canvas is Raster based (composed of a pixel).
画布基于光栅(由像素组成)。
Canvas is suitable for games graphics.
Canvas 适用于游戏图形。
Canvas is completely dependent on resolution.
画布完全取决于分辨率。
Canvas has no any API for animation.
Canvas 没有任何动画 API。
Canvas is not suitable for printing high quality and high resolution.
画布不适合打印高质量和高分辨率。
回答by Narayana Swamy
adding to the above points:
补充以上几点:
SVG is lightweight for transferring over web when compared to JPEG,GIF etc and also it scale extremely when resized without loosing the Quality.
与 JPEG、GIF 等相比,SVG 在网络上传输是轻量级的,并且在调整大小时可以极大地扩展而不会降低质量。