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

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

问题描述

是否有在 HTML5 画布上绘制 SVG 文件的默认方式?谷歌浏览器支持将 SVG 加载为图像(并且只需使用 drawImage),但开发者控制台会警告 资源被解释为图像但使用 MIME 类型 image/svg+xml 传输.

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 转换为画布命令(例如在 这个问题),但我希望这不是必需的.我不关心旧的浏览器(所以如果 FireFox 4 和 IE 9 支持某些东西,那就足够了).

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

推荐答案

Dec 2019

支持 Path2D() 构造函数通过 所有主要浏览器,允许在 2D 画布表面上声明路径对象".

Dec 2019

The Path2D() constructor is supported by all major browsers now, "allowing path objects to be declared on 2D canvas surfaces".

您现在可以使用 ctx.drawImage部分但不是所有浏览器(75% 的覆盖率:Chrome、IE11 和 Safari 工作,Firefox 工作有一些错误,但每晚都修复了它们).

You can now use ctx.drawImage to draw HTMLImageElements that have a .svg source in some but not all browsers (75% coverage: 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";

此处为现场示例.您应该会在画布中看到一个绿色方块.页面上的第二个绿色方块是插入到 DOM 中以供参考的相同 元素.

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.

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

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

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

此处为现场示例.

没有任何本机允许您在画布中本机使用 SVG 路径.您必须自己转换或使用图书馆为您完成.

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.

我建议查看canvg:(查看主页& 演示)

I'd suggest looking in to canvg: (check homepage & demos)

canvg 获取 SVG 文件的 URL,或 SVG 文件的文本,在 JavaScript 中解析它并在 Canvas 上呈现结果.

canvg takes the URL to an SVG file, or the text of the SVG file, parses it in JavaScript and renders the result on Canvas.

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

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