我想将彩色图像更改为灰度,但是当我尝试使用getImageData时出现安全性错误。
Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.
我知道这个错误已经在所有地方讨论过,但没有一个有明确的解决方案。请帮忙!
<html>
<script>
function grayscale()
{
var myCanvas = document.getElementById("c1");
var myCanvasContext = myCanvas.getContext("2d");
var img = document.getElementById("myImage");
img.crossOrigin = "anonymous";
var imgWidth = img.width;
var imgHeight = img.height;
myCanvas.width = imgWidth;
myCanvas.height = imgHeight;
myCanvasContext.drawImage(img,0,0);
var imageData = myCanvasContext.getImageData(0,0, imgWidth, imgHeight);
for (j=0; j<imageData.height; i++)
{
for (i=0; i<imageData.width; j++)
{
var index=(i*4)*imageData.width+(j*4);
var red=imageData.data[index];
var green=imageData.data[index+1];
var blue=imageData.data[index+2];
var alpha=imageData.data[index+3];
var average=(red+green+blue)/3;
imageData.data[index]=average;
imageData.data[index+1]=average;
imageData.data[index+2]=average;
imageData.data[index+3]=alpha;
}
}
}
</script>
<body>
<img id="myImage" onload="grayscale()" src="doggie.png"></img>
<canvas id = "c1" width = "200px" height = "200px" style="border:1px solid #000000;">
</canvas>
</body>
</html>
答案 0 :(得分:2)
最近我遇到了同样的问题。 您必须在同一个域(作为代码)上拥有图像,或者在图像所在的服务器上设置跨源。
Access-Control-Allow-Origin:*