HTML5 Canvas访问控制允许源错误 [英] HTML5 Canvas access-control-allow-origin error

查看:187
本文介绍了HTML5 Canvas访问控制允许源错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试从canvas元素获取数据时,我收到以下JavaScript错误:

I'm getting the following javascript error when I try to get data from a canvas element:


错误:canvas.toDataURL ) 不支持。 [异常...操作不安全。代码:18nsresult:0x80530012(SecurityError)...

Error: canvas.toDataURL() not supported. [Exception... "The operation is insecure." code: "18" nsresult: "0x80530012 (SecurityError)"...

画布是从域,但我使用代理将这两行添加到图像响应头:

The canvas is drawn from an image served from a different domain, but I'm using a proxy to add these 2 lines to the image response header:


access-control-allow-origin: *

access-control-allow-origin: *

access-control-allow-credentials:true

access-control-allow-credentials: true

我缺少了?

感谢,

Ted

Thanks,
Ted

推荐答案

要创建正确的CORS请求,您必须设置图片的跨原始属性更改为匿名。 此示例来自Mozilla开发人员网络。

To make a proper CORS request, you must set the image's cross origin property to "Anonymous". This example is from the Mozilla Developer Network.

var img = new Image,
    canvas = document.createElement("canvas"),
    ctx = canvas.getContext("2d"),
    src = "http://example.com/image"; // insert image url here

img.crossOrigin = "Anonymous";

img.onload = function() {
    canvas.width = img.width;
    canvas.height = img.height;
    ctx.drawImage( img, 0, 0 );
    localStorage.setItem( "savedImageData", canvas.toDataURL("image/png") );
}
img.src = src;
// make sure the load event fires for cached images too
if ( img.complete || img.complete === undefined ) {
    img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
    img.src = src;
}

浏览器支持排除任何已知版本的IE和未发布的Safari版本。 Firefox和Chrome有多年的支持。

The browser support excludes any known version of IE, and unreleased versions of Safari. Firefox and Chrome have years of support.

这篇关于HTML5 Canvas访问控制允许源错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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