Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Canvas getImageData Security Error

I want to change a colorful image to gray scale, but I have a security error when I try to use getImageData.

Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data. 

I know this error has been discussed everywhere, but none of them have a clear solution. Please help!

<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>
like image 238
Maya Nastasya Avatar asked Mar 16 '14 11:03

Maya Nastasya


1 Answers

Recently I have the same problem. You must have image on the same domain (as your code) or set cross-origin on server where the image is.

Access-Control-Allow-Origin: *

like image 97
PetrSiller Avatar answered Oct 08 '22 01:10

PetrSiller