个性化阅读
专注于IT技术分析

画布已被跨源数据污染,污染的画布可能无法导出

点击下载

本文概述

当你尝试在似乎没有合法权限处理你的代码的画布上处理图像时, 会发生这些错误。

它们是由请求的Access-Control-Allow-Origin标头关联的(并引起)(并由服务器允许)。该图像来自另一个域, 因此在大多数浏览器中都不允许这种行为, 因为这将构成安全漏洞。

什么是脏画布?

HTML规范为图像引入了跨域属性, 该属性与适当的CORS标头结合使用, 可以将由从外部来源加载的img元素定义的图像在画布中使用, 就像从当前来源加载图像一样。

有关如何使用crossorigin属性的详细信息, 请参见CORS设置属性。

尽管你可以在画布中使用未经CORS批准的图像, 但这样做会污染画布。画布污染后, 你将无法再将数据拉出画布。例如, 你将无法再使用画布的toBlob(), toDataURL()或getImageData()方法。这样做会引发安全错误。

画布已被跨源数据污染

分析以下代码:

var canvas = document.getElementById("canvas");

function drawImageFromWebUrl(sourceurl){
      var img = new Image();

      img.addEventListener("load", function () {
          // The image can be drawn from any source
          canvas.getContext("2d").drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height);
          
          // However the execution of any of the following methods will make your script fail
          // if your image doesn't has the right permissions
          canvas.getContext("2d").getImageData();
          canvas.toDataURL();
          canvas.toBlob();
      });

      img.setAttribute("src", sourceurl);
}
// But, this code is being executed from ourcodeworld and the image fcomes from google.
drawImageFromWebUrl("https://www.google.de/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png");

如果遇到此问题, 则你的代码可能具有某些共同的方法, 并且该图像并非来自你的域。

被污染的画布可能无法导出

Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

如果你足够聪明地思考, 就会发现此错误:

嘿, 如果我可以从另一个域获取污点画布的数据, 让我们将其转换为base64字符串, 然后重绘它。 -你, 诺贝尔奖获得者-2016

但是还不够聪明, 以为执行此操作也被阻止了, 因为图像”不属于你”。

可能的解决方案

Java脚本

你可以通过简单地在图像中设置crossorigin属性(使用Javascript或HTML)来防止此错误:

<img src="otherdomain.com" crossorigin="Anonymous" />

<!-- Or with Javascript -->
<script>
  var image = new Image();
  image.crossOrigin = "Anonymous";
  ...
</script>

但是, 这仅在服务器响应上带有以下标头时才有效:

Access-Control-Allow-Origin "*"

否则, 你会得到一个新错误:

Image from origin 'otherdomain.com' has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'yourdomain.com' is therefore not allowed access.

服务器端

由于问题在于图像不是来自你的域, 因此你可以使用服务器语言创建代理(用于在https(安全)内容中显示http(不安全)内容的相同技术)。

工作流程(使用服务器语言, PHP, C#等)应为:

代理外部资源

你可以在此处阅读有关此技术的更多信息, 这可能是你的动力所在。

赞(0)
未经允许不得转载:srcmini » 画布已被跨源数据污染,污染的画布可能无法导出

评论 抢沙发

评论前必须登录!