html5 使用图像数据,在chrome浏览器出现跨域问题?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test Html5</title>
<style type="text/css">
*{margin: 0; padding: 0;}
.content {width: 1200px; margin: 0 auto; padding: 20px 0;}
#canvas { border: 2px solid #333;}
.img {width: 1200px; height: 800px; overflow: hidden;}
</style>
</head>
<body>
<div class="content">
<canvas id="canvas">你的浏览器不支持canvas!!!</canvas>
<div class="img"><img id="image" src="images/004.jpg" alt=""></div>
</div>
</body>
<script type="text/javascript">
window.onload = function(){
var canvas = document.getElementById("canvas"); //获取canvas
canvas.width = 1200;
canvas.height = 600;
var context = canvas.getContext('2d'); //获取2d上下文绘图环境
var image = document.getElementById("image");
context.drawImage(image,0,0,800,500); //x,y,wd,hg
//使用图像数据
var imageData = context.getImageData(0,0,800,800); //x y wd hg
var data = imageData.data;
console.log(data);
for (var i = 0; i < data.length; i+=4) {
red = data[i];
green = data[i+1];
blue = data[i+2];
alpha = data[i+3];
average = Math.floor((red+green+blue)/3);
data[i] = average;
data[i+1] = average;
data[i+2] = average;
}
imageData.data = data;
context.putImageData(imageData,0,0);
}
</script>
</html>
chrome 控制台出现 Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.
IE
和edge
是好的,就是将彩色图片变成黑白图片
相关问题canvas 跨域问题
在
stackoverfow
上有相关提问 canvas CORS看不懂
stackoverflow
解决办法 “To solve the cross domain issue with file://, you can start chrome with the parameter” --allow-file-access-from-filessrc= "images/004.jpg"
这也算跨域? 我对跨域的理解就是必须协议相同,域名一样,端口一样。那么chrome 这个问题该如何解决,以后的解决跨域有没有一些好的方法?
试试
img.crossOrigin = "Anonymous";