在 HTML5 Canvas 上绘制 SVG 并支持字体元素
是否有一个很好的库可以将 SVG 转换为支持字体元素的 HTML 画布?我已经尝试过 canvg,但它不支持字体.
Is there a good library for converting SVG to HTML canvas that supports the font element? I have already tried canvg, but it does not support Font.
支持 HTML5 Canvas 的浏览器本身也很好地支持 SVG.因此,您可以这样做:
Browsers that support HTML5 Canvas also support SVG pretty well themselves. As such, you could do this:
var img = new Image;
img.onload = function(){ myCanvasContext.drawImage(img,0,0); };
img.src = "foo.svg";
这种技术的唯一缺点是,如果 SVG 在您的域之外,画布将被污染;如果这是您的目标,您将无法使用 getImageData()
读取生成的 SVG.
The only downside to this technique is that if the SVG is outside of your domain the canvas will become tainted; you will not be able to use getImageData()
to read the resulting SVG, if that is your goal.
我在我的服务器上放了一个这种技术的例子:http://phrogz.net/tmp/canvas_from_svg.html
我已经对此进行了测试,并验证它在 IE9、Chrome v11b、Safari v5 和 Firefox v4 上可以正常工作(并且看起来相同).
I've put an example of this technique on my server: http://phrogz.net/tmp/canvas_from_svg.html
I've tested this and verified that it works (and looks the same) on IE9, Chrome v11b, Safari v5, and Firefox v4.
注意:
Chrome 和 Firefox 目前在安全性方面重拳出击",并且不允许您在之后阅读画布(例如这些已修复getImageData()
或toDataURL()
)您将任何 SVG 绘制到画布上(无论域如何)
Chrome and Firefox currently 'punt' on security and disallow you from reading the canvas (e.g.these have been fixedgetImageData()
ortoDataURL()
) after you draw any SVG to the canvas (regardless of the domain)
Firefox 目前有一个错误,它拒绝将 SVG 绘制到画布上,除非 SVG 指定了 height
和 width
属性.
Firefox currently has a bug where it refuses to draw SVG to the canvas unless the SVG has height
and width
attributes specified.