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

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

问题描述

有没有一种默认方式将SVG文件绘制到HTML5画布上? Google Chrome支持将SVG作为图片加载(只需使用 drawImage ),但开发人员控制台会警告将资源解释为图片,但使用MIME类型image / svg + xml



我知道一种可能性是将SVG转换为canvas命令(如这个问题),但我希望不需要。我不在乎旧的浏览器(所以如果FireFox 4和IE 9将支持某事,这是足够好的)。

解决方案

EDIT 2014年11月5日



现在可以使用 ctx.drawImage 来绘制HTMLImageElements, strong>在某些但不是所有浏览器。 Chrome,IE11和Safari工作,Firefox使用一些错误(但是每天修复它们)。

  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 。你应该在画布上看到一个绿色的方块。页面上的第二个绿色方块是插入到DOM中以供参考的相同< svg> 元素。



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

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






旧的后代答案:



没有什么本地,允许你在canvas中本地使用SVG路径。您必须转换自己或使用图书馆为您做。



我建议您前往canvg:



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

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天全站免登陆