Html 在 HTML5 画布上绘制 SVG 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3768565/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 04:35:30  来源:igfitidea点击:

Drawing an SVG file on a HTML5 canvas

htmlcanvassvg

提问by Randy Voet

Is there a default way of drawing an SVG file onto a HTML5 canvas? Google Chrome supports loading the SVG as an image (and simply using drawImage), but the developer console does warn that resource interpreted as image but transferred with MIME type image/svg+xml.

是否有将 SVG 文件绘制到 HTML5 画布上的默认方法?谷歌浏览器支持将 SVG 加载为图像(并简单地使用drawImage),但开发人员控制台确实警告resource interpreted as image but transferred with MIME type image/svg+xml.

I know that a possibility would be to convert the SVG to canvas commands (like in this question), but I'm hoping that's not needed. I don't care about older browsers (so if FireFox 4 and IE 9 will support something, that's good enough).

我知道一种可能性是将 SVG 转换为画布命令(就像在这个问题中一样),但我希望这不是必需的。我不关心旧的浏览器(所以如果 FireFox 4 和 IE 9 支持某些东西,那就足够了)。

采纳答案by Simon Sarris

EDIT Dec 16th, 2019

编辑 2019 年 12 月 16 日

Path2D is supported by all major browsers now

现在所有主流浏览器都支持 Path2D

EDIT November 5th, 2014

编辑 2014 年 11 月 5 日

You can now use ctx.drawImageto draw HTMLImageElements that have a .svg source in some but not all browsers. Chrome, IE11, and Safari work, Firefox works with some bugs (but nightly has fixed them).

您现在可以使用在某些但不是所有浏览器中ctx.drawImage绘制具有 .svg 源的 HTMLImageElements 。Chrome、IE11 和 Safari 可以正常工作,Firefox 可以处理一些错误(但 nightly 已修复它们)。

var img = new Image();
img.onload = function() {
    ctx.drawImage(img, 0, 0);
}
img.src = "http://upload.wikimedia.org/wikipedia/commons/d/d2/Svg_example_square.svg";

Live example here. You should see a green square in the canvas. The second green square on the page is the same <svg>element inserted into the DOM for reference.

现场示例在这里。您应该会在画布中看到一个绿色方块。页面上的第二个绿色方块是<svg>插入到 DOM 中以供参考的相同元素。

You can also use the new Path2D objects to draw SVG (string) paths. In other words, you can write:

您还可以使用新的 Path2D 对象来绘制 SVG(字符串)路径。换句话说,你可以写:

var path = new Path2D('M 100,100 h 50 v 50 h 50');
ctx.stroke(path);

Live example of that here.

这里的活生生的例子。



Old posterity answer:

老子回答:

There's nothing native that allows you to natively use SVG paths in canvas. You must convert yourself or use a library to do it for you.

没有任何本机允许您在画布中本机使用 SVG 路径。您必须自己转换或使用库来为您转换。

I'd suggest looking in to canvg:

我建议查看canvg:

http://code.google.com/p/canvg/

http://code.google.com/p/canvg/

http://canvg.googlecode.com/svn/trunk/examples/index.htm

http://canvg.googlecode.com/svn/trunk/examples/index.htm

回答by Henrique Campos

Sorry, i don't have enough reputation to comment on the @Matyas answer, but if the svg's image is also in base64, it will be drawed to the output.

抱歉,我没有足够的声誉来评论@Matyas 的答案,但是如果 svg 的图像也在 base64 中,它将被绘制到输出中。

Demo:

演示:

var svg = document.querySelector('svg');
var img = document.querySelector('img');
var canvas = document.querySelector('canvas');

// get svg data
var xml = new XMLSerializer().serializeToString(svg);

// make it base64
var svg64 = btoa(xml);
var b64Start = 'data:image/svg+xml;base64,';

// prepend a "header"
var image64 = b64Start + svg64;

// set it as the source of the img element
img.onload = function() {
    // draw the image onto the canvas
    canvas.getContext('2d').drawImage(img, 0, 0);
}
img.src = image64;
svg, img, canvas {
  display: block;
}
SVG

<svg height="40">
  <rect width="40" height="40" style="fill:rgb(255,0,255);" />
  <image xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAEX0lEQVQ4jUWUyW6cVRCFv7r3/kO3u912nNgZgESAAgGBCJgFgxhW7FkgxAbxMLwBEmIRITbsQAgxCEUiSIBAYIY4g1EmYjuDp457+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r0hyU6P+cRSlhXjbEI2zvnt7y79oqQ3qeg4g6vKjCIXehtDmi6m0UnxVnCRkPUHVNt9qkLJxgXOCYNOg34v48raPaamU2o89/KKsQ9sTSpc0JK7NwdcX8s43Ek5cnSOLC/Z2R6Rj0ra0w2W1/t0xyWn51uk2Ri1QtSO6OU5d7OSi72cQeWxKG7p/Dp//JXTy6C1Pcbc6DMpPRtjTxChEznWhwVZUCKrjCrPoPDczHLmnLBdBgZlRRWUEBR3ZKrme5TlrTGlV440Y1IrXM9qQGi6mkG5V6uza7tUIeCDElTZ1L26elX+fcH/ACJBPYTJ4X8tAAAAAElFTkSuQmCC" height="20px" width="20px" x="10" y="10"></image>
</svg>
<hr/><br/>

IMAGE
<img/>
<hr/><br/>
   
CANVAS
<canvas></canvas>
<hr/><br/>

回答by Matyas

You can easily draw simple svgs onto a canvas by:

您可以通过以下方式轻松地将简单的svgs绘制到画布上:

  1. Assigning the source of the svg to an image in base64 format
  2. Drawing the image onto a canvas
  1. 将 svg 的源分配给 base64 格式的图像
  2. 将图像绘制到画布上

Note:The only drawback of the method is that it cannot draw images embedded in the svg. (see demo)

注意:该方法的唯一缺点是无法绘制嵌入在svg. (见演示)

Demonstration:

示范:

(Note that the embedded image is only visible in the svg)

(请注意,嵌入的图像仅在 中可见svg

var svg = document.querySelector('svg');
var img = document.querySelector('img');
var canvas = document.querySelector('canvas');

// get svg data
var xml = new XMLSerializer().serializeToString(svg);

// make it base64
var svg64 = btoa(xml);
var b64Start = 'data:image/svg+xml;base64,';

// prepend a "header"
var image64 = b64Start + svg64;

// set it as the source of the img element
img.src = image64;

// draw the image onto the canvas
canvas.getContext('2d').drawImage(img, 0, 0);
svg, img, canvas {
  display: block;
}
SVG

<svg height="40">
  <rect width="40" height="40" style="fill:rgb(255,0,255);" />
  <image xlink:href="https://en.gravatar.com/userimage/16084558/1a38852cf33713b48da096c8dc72c338.png?size=20" height="20px" width="20px" x="10" y="10"></image>
</svg>
<hr/><br/>

IMAGE
<img/>
<hr/><br/>
   
CANVAS
<canvas></canvas>
<hr/><br/>

回答by Nati Krisi

Mozilla has a simple way for drawing SVG on canvas called "Drawing DOM objects into a canvas"

Mozilla 有一种在画布上绘制 SVG 的简单方法,称为“将DOM 对象绘制到画布中

回答by Max West

As Simon says above, using drawImage shouldn't work. But, using the canvglibrary and:

正如西蒙上面所说,使用 drawImage 不应该工作。但是,使用canvg库和:

var c = document.getElementById('canvas');
var ctx = c.getContext('2d');
ctx.drawSvg(SVG_XML_OR_PATH_TO_SVG, dx, dy, dw, dh);

This comes from the link Simon provides above, which has a number of other suggestions and points out that you want to either link to, or download canvg.js and rgbcolor.js. These allow you to manipulate and load an SVG, either via URL or using inline SVG code between svg tags, within JavaScript functions.

这来自上面 Simon 提供的链接,其中有许多其他建议,并指出您想要链接或下载 canvg.js 和 rgbcolor.js。这些允许您在 JavaScript 函数中通过 URL 或在 svg 标签之间使用内联 SVG 代码来操作和加载 SVG。