I aimed to convert the image on the canvas to grayscale, and I used getImageData. But there are 2 errors for var imgData = ctx.getImageData(0,0,c.width,c.height);
.
The console says:
- "Unable to get image data from canvas because the canvas has been tainted by cross-origin data."
- "SecurityError: The operation is insecure."
I'm new to javascript and canvas, can anyone help me? Thanks in advance!
My code below:
Html:
<div>
<p>Image on the Canvas: </p>
<canvas id="imgCanvas">Your browser does not support the HTML5 canvas tag.</canvas>
<button type="button" onclick="makeGray()">Convert to Gray</button>
</div>
Javascript:
function makeGray() {
var c = document.getElementById("imgCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("img");
ctx.drawImage(img,0,0);
var imgData = ctx.getImageData(0,0,c.width,c.height);
var i;
for (i = 0; i < imgData.data.length; i += 4) {
var avg = (imgData.data[i] + imgData.data[i+1] + imgData.data[i+2])/3;
imgData.data[i] = avg;
imgData.data[i+1] = avg;
imgData.data[i+2] = avg;
}
ctx.putImageData(imgData,0,0);
}