0

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:

  1. "Unable to get image data from canvas because the canvas has been tainted by cross-origin data."
  2. "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);
}
Dyan
  • 1
  • 1
  • `var img = document.getElementById("img");` you haven't shown this part of the HTML - is it a cross-origin image? – Jaromanda X Apr 25 '20 at 01:47
  • I've tried your code with a local image and it works as expected. So your issue is that the image is a cross-origin resource as @JaromandaX is saying. – Luís Ramalho Apr 25 '20 at 01:50
  • Note that you don't even need getImageData nor even a canvas here, just use a CSS filter grayscale. – Kaiido Apr 25 '20 at 03:38
  • To convert an image to black and white you can use a `ctx.filter = "grayscale(100%)";` then draw the image on the canvas `ctx.drawImage(img,0,0);` Or draw the image `ctx.drawImage(img,0,0)` set `ctx.globalCompositeOperation = "color"` and draw a white rect over the image `ctx.fillStyle = "#FFF"; ctx.fillRect(0,0,ctx.canvas.width, ctx.canvas.height)"` @Kaiido the dup link does not answer the OPs question. OP wants to convert to grayscale, The OP's inexperience lead to `getImageData` which is unrelated – Blindman67 Apr 25 '20 at 11:52
  • @Blindman67 the question is currently about the getImageData being blocked. That's a dupe. The background story has not influence on this, unless OP edit their question so it asks something different. Also, they don't even need a canvas, as I said in my comment. – Kaiido Apr 25 '20 at 12:22

0 Answers0