将文档中的SVG栅格化为画布 [英] Rasterizing an in-document SVG to Canvas

查看:578
本文介绍了将文档中的SVG栅格化为画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了正确回答此问题,我认为我will:


  1. 将文档内SVG文件转换为数据网址

  2. 将其加载到< img>

  3. < img> code>< canvas>

  4. < canvas> 转换为PNG资料URL

  5. 将该数据网址加载到图片中。

这里:

http://phrogz.net/SVG/svg_to_png.xhtml



在Firefox中,当在第3步中将图像绘制到画布时,我得到(NS_ERROR_NOT_AVAILABLE)[nsIDOMCanvasRenderingContext2D.drawImage] / p>

为什么我在Firefox中收到此错误,或者如何解决此问题?



在Chrome中,当我在第4步尝试调用 toDataURL()时,会出现 SECURITY_ERR 异常。 p>

为什么我会在Chrome中收到此错误,或如何解决此问题?



WhatWG规格说明对于从在另一文档或脚本中找到的数据:URL生成的图像的 原始应该与该文档相同。

解决方案

在Firefox中,SVG图片会污染画布,但我们请在 https://bugzilla.mozilla.org/show_bug.cgi?id=672013 当该bug落在你想要做什么应该是可能的。 此限制已在FFv12中移除。



所有浏览器都执行类似的限制,并且都在移除它们;一般通过使你可以在SVG图像中做更多的限制。例如,我们不想回到过去的糟糕的时代,通过创建一个带有链接的SVG图片,然后使用画布来读取链接的颜色,来了解您访问过的网站。



此外,此时firefox要求svg元素具有width和height属性才能呈现到canvas。



由Phrogz编辑:如我在上述评论中所述,我收到了独立确认,Chrome中的安全问题是相同的问题:Chrome(当前)总是在绘制SVG文档时绘制画布。


In order to answer this question properly I thought that I would:

  1. Convert an in-document SVG file to a data URL
  2. Load it into an <img>
  3. Draw that <img> to a <canvas>
  4. Convert that <canvas> to a PNG data URL
  5. Load that data URL into an image.

I have an example of this attempt here:
http://phrogz.net/SVG/svg_to_png.xhtml

In Firefox I get (NS_ERROR_NOT_AVAILABLE) [nsIDOMCanvasRenderingContext2D.drawImage] when attempting to draw the image to the canvas in step 3.

Why do I get this error in Firefox, or how do I work around it?

In Chrome I get a SECURITY_ERR exception when I try to call toDataURL() in step 4.

Why would I get this error in Chrome, or how do I work around it?

The WhatWG specs state that the origin for an image "generated from a data: URL found in another Document or in a script" should be the same as that document. All data in this test is from the same document.

解决方案

In Firefox, SVG images taint the canvas but we're working on removing that restriction in https://bugzilla.mozilla.org/show_bug.cgi?id=672013 when that bug lands what you're trying to do should be possible. This restriction has been removed in FFv12.

All browsers implement similar restrictions and all are working on removing them; generally by making what you can do in SVG images more restricted. For instance we don't want to get back to the bad old days of being able to work out what sites you've visited by creating an SVG image with links in it and then reading off the colour of the links using canvas.

In addition at the moment firefox requires that the svg element have width and height attributes in order to render to canvas. This restriction may be removed in future.

Edit by Phrogz: as noted in my comment above, I received independent confirmation that the security issue in Chrome is the same issue: Chrome (currently) always taints a canvas when an SVG document is drawn to it.

这篇关于将文档中的SVG栅格化为画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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