在除IE10之外的所有浏览器中工作

在除IE10之外的所有浏览器中工作

本文介绍了Canvas.toDataURL()在除IE10之外的所有浏览器中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working on a project that uses a canvas to automatically crop an image, then return its data URL. It uses images from an external server, which has the appropriate CORS headers to allow the images to be converted to data URIs after they are cropped even though they are cross-origin.

代码在除了IE 10之外的所有浏览器中工作得很好(没有安全错误!),当调用canvas.toDataURL()时,它会抛出SCRIPT5022:SecurityError。

The code works perfectly (and without security errors!) in all browsers except IE 10, in which it throws 'SCRIPT5022: SecurityError' when canvas.toDataURL() is called.

这是一个错误在IE或东西,我需要做不同的在我的代码,使其工作在Idiot Exploder?谢谢。 -Scott

Is this a bug in IE or something I need to do differently in my code to make it work in Idiot Exploder? Thanks. -Scott

EDIT
这里是我用来创建和绘制画布的代码(大部分) p>

EDITHere is (most of) the code I'm using to create and draw the 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支持图像。 似乎反过来。

I don't believe IE10 has CORS support for images. This MDN article seems to back that up.

如文章所述:

所以,它看起来像你必须代理来自同一个来源/域在尝试这样做之前,至少对于IE10和Opera。

So, it looks like you'll have to proxy the image from the same origin/domain as the one hosting the code in question before attempting to do this, at least for IE10 and Opera.

为了处理没有CORS支持图像的浏览器,需要代理服务器端的镜像。您可以通过将图像源发送到本地服务器上的已知端点,并将图像的源网址作为查询参数传递,从而很容易地做到这一点。

To deal with browsers that do not have CORS support for images, you'll need to proxy the image server-side. You can do this pretty easily by sending the source of the image to a known endpoint on your local server, and passing in the source url of the image as a query parameter.

例如:

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

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

现在,服务器端,您将处理此GET请求, code> source 参数,从源中获取图像,并在响应中返回。

Now, server-side, you'll handle this GET request, rip off the value of the source parameter from the URI, grab the image from the source, and return it in your response.

这篇关于Canvas.toDataURL()在除IE10之外的所有浏览器中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 20:54