Canvas.toDataURL() 适用于除 IE10 以外的所有浏览器

标签 canvas internet-explorer-10 cors same-origin-policy

我正在开发一个使用 Canvas 自动裁剪图像,然后返回其数据 URL 的项目。它使用来自外部服务器的图像,该服务器具有适当的 CORS header ,以允许图像在裁剪后转换为数据 URI,即使它们是跨域的。

该代码在除 IE 10 之外的所有浏览器中都能完美运行(并且没有安全错误!),其中在调用 canvas.toDataURL() 时会抛出“SCRIPT5022: SecurityError”。

这是 IE 中的错误还是我需要在代码中做一些不同的事情才能使其在 Idiot Exploder 中工作?谢谢。 -斯科特

编辑
这是(大部分)我用来创建和绘制 Canvas 的代码;

var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.src = imageServerURL + '?id=' + imageIdToGet; // imageServerURL points to a different domain but the server has headers allowing requests from my domain
/*
    code here that defines the cropping area, in variables like ulX, lrY, etc.
*/
ctx.beginPath();
ctx.moveTo(ulX, ulY);
ctx.lineTo(urX, urY);
ctx.lineTo(lrX, lrY);
ctx.lineTo(llX, llY);
ctx.closePath();
ctx.clip();
ctx.drawImage(img, 0, 0);
var url = canvas.toDataURL(); // This succeeds in all other browsers but throws a SecurityError in IE

最佳答案

我不相信 IE10 对图像有 CORS 支持。 This MDN article似乎支持这一点。

正如文章所述:

Although you can use images without CORS approval in your canvas, doing so taints the canvas. Once a canvas has been tainted, you can no longer pull data back out of the canvas. For example, you can no longer use the canvas toBlob(), toDataURL(), or getImageData() methods; doing so will throw a security error.



因此,在尝试执行此操作之前,您似乎必须从与托管相关代码的源/域相同的源/域代理图像,至少对于 IE10 和 Opera 而言。

要处理不支持 CORS 图像的浏览器,您需要代理图像服务器端。您可以通过将图像的源发送到本地服务器上的已知端点,并将图像的源 url 作为查询参数传递来非常容易地做到这一点。

例如:

var sourceImageUrl = "https://www.google.com/images/srpr/logo4w.png",  
    localProxyEndpoint = "/imageproxy",   
    image = new Image();   

image.src = localProxyEndpoint + "?source=" + encodeURIComponent(sourceImageUrl);

现在,在服务器端,你将处理这个 GET 请求,撕掉 source 的值。从 URI 中获取参数,从源中获取图像,并在响应中返回它。

关于Canvas.toDataURL() 适用于除 IE10 以外的所有浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18112047/

相关文章:

javascript - 从左到右移动 Canvas 并不流畅和快速

css - IE 10 附加 CSS

jquery - 按钮上的透明覆盖 div 触发器在 IE 10 中不起作用

cors - Postman( Electron 应用程序)如何避开CORS?

javascript - 如何将一个 Canvas 的内容复制到另一 Canvas

java - 坐标不对应

javascript - 绘图软刷

javascript - 禁用 JS 的 IE10 执行手动输入 `onmousedown`

django - 无法使用位于其他域的 JS 工作文件构造 'Worker'

java - 将 Angular 连接到 Spring 时发生 CORS 错误(localhost 8080 <--> localhost 4200)