在HTML5画布上绘制SVG文件 [英] Drawing an SVG file on a HTML5 canvas

查看:118
本文介绍了在HTML5画布上绘制SVG文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有将SVG文件绘制到HTML5画布上的默认方式? Google Chrome支持将SVG作为图像加载(并简单地使用 drawImage ),但开发人员控制台警告说资源解释为图像,但会通过MIME传输输入image / svg + xml



我知道有可能将SVG转换为canvas命令(比如这个问题),但我希望这不是必要的。我不在乎老版本的浏览器(所以如果FireFox 4和IE 9会支持某些东西,这已经足够好了)。 编辑2014年11月5日

现在可以使用 ctx.drawImage 来绘制具有.svg源文件的HTMLImageElements <在某些浏览器中,不是所有浏览器。 Chrome,IE11和Safari的工作,火狐工作与一些错误(但每晚已修复它们)。

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

现场示例。你应该在画布上看到一个绿色方块。页面上的第二个绿色方块与插入DOM中的< svg> 元素相同。



您还可以使用新的Path2D对象绘制SVG(字符串)路径(目前仅适用于Chrome )。换句话说,你可以这样写:

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

在这里的实例






老后代答案:



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



我建议看看canvg:



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



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


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.

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).

解决方案

EDIT November 5th, 2014

You can now use ctx.drawImage to 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).

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.

You can also use the new Path2D objects to draw SVG (string) paths (only works in Chrome right now). In other words, you can write:

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.

I'd suggest looking in to canvg:

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

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

这篇关于在HTML5画布上绘制SVG文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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