canvas 和 svg 的区别

159 阅读1分钟

1、canvas 是用 js 绘制的 2d 图形,svg 是用 xml 语言绘制的 2d 图形。

canvas 示例:

html:

<canvas id="canvas"></canvas>

js:

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

ctx.fillStyle = 'green';
ctx.fillRect(10, 10, 150, 100);

svg 示例:

<svg version="1.1"
     baseProfile="full"
     width="300" height="200"
     xmlns="http://www.w3.org/2000/svg">

  <rect width="100%" height="100%" fill="red" />

  <circle cx="150" cy="100" r="80" fill="green" />

  <text x="150" y="125" font-size="60" text-anchor="middle" fill="white">SVG</text>

</svg>

2、canvas 绘制的是位图,显示效果和屏幕分辨率有关,分辨率越高,显示效果越好,svg 绘制的是矢量图,显示效果与分辨率无关,若将图像放大,位图显示则会变得模糊,但是矢量图就不会受到影响。

canvas 绘制图形放大后的效果:

image.png

svg 绘制图形放大后的效果:

image.png

3、canvas不支持事件机制,而 svg 使用的是 xml 语言,因此支持分层和事件。

4、canvas 是 html5 新增的标签,svg 由来已久,在 html5 出现之前就存在。

总的来说,svg 结点过多时渲染比较慢,canvas 性能较好,但是写起来比较复杂。