0

The following code throws me a CORS error:

const img = document.createElement('img');
img.src = url;

img.onload = () => {
  if (img.width > img.height) {
    img.height = 224;
  } else {
    img.width = 224;
  }

  document.body.appendChild(img);

  const canvas = document.createElement('canvas');
  const context = canvas.getContext('2d');

  canvas.width = img.width;
  canvas.height = img.height;
  context.drawImage(img, 0, 0 );
  img.crossOrigin = 'Anonymous';
  img.setAttribute('crossOrigin', '');
  const imgData = context.getImageData(0, 0, img.width, img.height);
};

core.js:1673 ERROR DOMException: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data. at HTMLImageElement.img.onload [as __zone_symbol__ON_PROPERTYload]

It fails at the getImageData part but creating the img and appending it to the body works fine.

Is there an error in my code? I don't understand why I can display the image but when I want to get the ImageData I get an error.

Any ideas or explainings?

Jonas
  • 7,089
  • 15
  • 49
  • 110
  • 2
    It's a security feature. Image data from a different domain than that of the main page cannot be accessed via a canvas like that. – Pointy Oct 03 '18 at 21:12
  • Perhaps you need to test this code locally, ie, Python's simpleserver or node's http server. – Battlesquid Oct 03 '18 at 21:25

0 Answers0