Cavans VS SVG
Canvas 和 SVG 都允许您在浏览器中创建图形,但是它们在根本上是不同的。
首先我们来说一下SVG
SVG 是一种使用 XML 描述 2D 图形的语言。
SVG 基于 XML,这意味着 SVG DOM 中的每个元素都是可用的。您可以为某个元素附加 JavaScript 事件处理器。
在 SVG 中,每个被绘制的图形均被视为对象。如果 SVG 对象的属性发生变化,那么浏览器能够自动重现图形。
接下来我们来了解一下Canvas
Canvas 通过 JavaScript 来绘制 2D 图形。
Canvas 是逐像素进行渲染的。
在 canvas 中,一旦图形被绘制完成,它就不会继续得到浏览器的关注。如果其位置发生变化,那么整个场景也需要重新绘制,包括任何或许已被图形覆盖的对象。
最后我们来比较一下 Canvas 与 SVG的不同之处
Canvas
· 依赖分辨率
· 不支持事件处理器
· 弱的文本渲染能力
· 能够以 .png 或 .jpg 格式保存结果图像
· 最适合图像密集型的游戏,其中的许多对象会被频繁重绘
SVG
· 不依赖分辨率
· 支持事件处理器
· 最适合带有大型渲染区域的应用程序(比如谷歌地图)
· 复杂度高会减慢渲染速度(任何过度使用 DOM 的应用都不快)
· 不适合游戏应用
下面是SVG和Canvas的小例子
以实现一个红色的圆形为例
利用svg 画出一个圆形 保存为 circle.svg
文件名必须保存为 .svg格式
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>
</svg>
<?xml version="1.0" standalone="no"?>
然后我们新建一个html文件 svg.html
<html>
<head></head>
<body>
<iframe src="html.svg" width="300" height="100">
</iframe>
</body>
</html>
在浏览器中打开 svg.html 我们会惊喜的发现有一个红色背景的圆形呈现在屏幕上
利用 Canvas 画一个圆形
可以新建一个 canvas.html 直接在代码中写入一下代码
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script type="text/javascript">
var c=document.getElementById("myCanvas");
var cxt=c.getContext("2d");
cxt.fillStyle="#FF0000";
cxt.beginPath();
cxt.arc(70,18,15,0,Math.PI*2,true);
cxt.closePath();
cxt.fill();
</script>
然后用浏览器打开canvas.html就可以发现一个红色背景的圆形了
希望本文对大家理解Canvas 和 SVG 有一定的帮助
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。