HTML5 security error CanImageData

I want to change the color image to gray, 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 that this error was discussed everywhere, but none of them has 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> 
+7
javascript html5 cors html5-canvas canvas
source share
1 answer

I recently have the same problem. You must have an image in the same domain (as your code) or set the cross-start on the server where the image is located.

Access-Control-Allow-Origin: *

+2
source share

All Articles