在 HTML5 Canvas 上绘制 SVG,支持字体元素
有没有一个好的库可以将 SVG 转换为支持 font 元素的 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
支持 HTML5 Canvas 的浏览器本身也很好地支持 SVG。因此,您可以这样做:
此技术的唯一缺点是,如果 SVG 位于您的域之外,则画布将被污染;如果您的目标是,您将无法使用
getImageData()
读取生成的 SVG。我已在我的服务器上放置了此技术的示例:http://phrogz.net/tmp/canvas_from_svg。 html
我已经对此进行了测试并验证了它在 IE9、Chrome v11b、Safari v5 和 Firefox v4 上有效(并且看起来相同)。
[编辑] 请注意:
Chrome 和 Firefox 目前在安全性上“押注”,不允许您阅读画布(例如这些已修复getImageData()
或toDataURL()
) 在将任何 SVG 绘制到画布上(无论域如何)Firefox 目前有一个错误,它拒绝绘制 SVG到画布上,除非 SVG 指定了
height
和width
属性。Browsers that support HTML5 Canvas also support SVG pretty well themselves. As such, you could do this:
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.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.
[Edit] Note that:
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 currently has a bug where it refuses to draw SVG to the canvas unless the SVG has
height
andwidth
attributes specified.如果您将 svg 嵌入到 HTML 中或作为原始源,您可以使用数据 URL 将 svg 转换为 HTML 图像元素,然后可以在画布上绘制:
In case you have the svg embedded into HTML or as a raw source you can use a data URL to convert the svg to a HTML image element which you then can draw on the canvas:
我只是尝试了一个简单的img标签、Phrogs的方法和canvg。我的 SVG 嵌入了 PNG。这只适用于canvg。其他人显示的图像没有嵌入 PNG。那是在带有标准浏览器或 Chrome 的 Android Jellybean 上。
I just tried a simple img tag, Phrogs' method and canvg. My SVG has an embedded PNG. That only worked in canvg. The others showed the image without the embedded PNG. That was on Android Jellybean with either the standard browser or Chrome.