跨域名访问资源的问题 HTML5 Canvas getImageData img.crossOrigin

分类:Javascript| 发布:佚名| 查看: | 发表时间:2014/5/26

利用 canvas 取得图片的data,如果 img.src是来自其它域名的图片,浏览器便会禁止执行
例如代码:

<canvas id="example" width="300" height="300">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>
<script type="text/javascript">
var example = document.getElementById('example');
var context = example.getContext('2d');
var img = new Image();
img.onload = function(){
context.drawImage(img,0,0);
var myImageData = context.getImageData(210, 210, 1, 1);
console.log(myImageData);
};
img.src = "test.png";
</script>

使用了Html5的Canvas画布标签,在canvas里加入本服务器的图片时能够很好得运行。但是当用了跨域的图片地址后在FireFox里可以运行,而在Chrome则报如下错误(IE下也不可运行):

Image from origin 'http://sdimage.b0.upaiyun.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 'http://localhost:3000' is therefore not allowed access.
 
看下边的代码就知道怎么解决了:
<!DOCTYPE html>
<html>
<head>
<title>Canvas Cross Origin Image Test: Testing for Canvas Cross Domain Image CORS Support</title>
<script type="text/javascript">
function initialize() {

//will fail here if no canvas support
try {
var can = document.getElementById('mycanvas');
var ctx = can.getContext('2d');
var img = new Image();
img.crossOrigin = '';
//domain needs to be different from html page domain to test cross origin security
img.src = 'http://lobbydata.com/Content/images/bg_price2.gif'; // 关于换这个地址出错的说明地址:http://camnpr.com/TuiJianTools/html5/canvas-cross-domain-images.html
} catch (ex) {
document.getElementById("results").innerHTML = "<span style='color:Red;'>Failed: " + ex.Message + "</span>";
}

//will fail here if security error
img.onload = function () {
try {
var start = new Date().getTime();
can.width = img.width;
can.height = img.height;
ctx.drawImage(img, 0, 0, img.width, img.height);
var url = can.toDataURL(); // if read succeeds, canvas isn't dirty.
//get pixels
var imgd = ctx.getImageData(0, 0, img.width, img.width);
var pix = imgd.data;
var len = pix.length;
var argb = []; //pixels as int
for (var i = 0; i < len; i += 4) {
argb.push((pix[i + 3] << 24) + (pix[i] << 16) + (pix[i + 1] << 8) + pix[i + 2]);
}
var end = new Date().getTime();
var time = end - start;
document.getElementById("results").innerHTML = "<span style='color:Green;'>" +
"Success: Your browser supports CORS for cross domain images in Canvas <br>"+
"Read " + argb.length+ " pixels in "+ time+"ms</span>";
} catch (ex) {
document.getElementById("results").innerHTML = "<span style='color:Red;'>Failed: " + ex + "</span>";
}
}
}
</script>
</head>
<body onload="initialize()">
<h2>Canvas Cross Origin Image Test: Testing for Canvas Cross Domain Image CORS Support</h2>
<h2><a href="http://camnpr.com/TuiJianTools/html5/using-cross-domain-images-in-webgl-and.html">What is CORS Image Security?</a></h2>
<h1 id="results" style="color:Orange;">Testing...</h1>
<canvas id="mycanvas"></canvas>
<br />
<a href="/Example/List">More Examples</a>
</body>
</html>

解决办法是: img.crossOrigin = '';

如果不加img.crossOrigin='';,那么会报错:
Failed: SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

关于读者提出的,换图片的URL(比如:http://bubuol.com/skins/bubuol1/images/logo.gif)会报错的问题

原因分析:

image Access-Control-Allow-Origin

image Access-Control-Allow-Origin

解决办法:通过设置头信息(Access-Control-Allow-Origin)

详情查看地址:http://camnpr.com/TuiJianTools/html5/canvas-cross-domain-images.html

365据说看到好文章不转的人,服务器容易宕机
原创文章如转载,请注明:转载自郑州网建-前端开发 http://camnpr.com/
本文链接:http://camnpr.com/javascript/1117.html