Skip to content Skip to sidebar Skip to footer

Tainted Html Canvas Even With Cors Headers

I'm trying to get the data URL for an image. The image is coming from a cross origin remote server, Wikipedia. I use this JavaScript to try to do it: # get the image const img = do

Solution 1:

When you set src on your image, the browser makes a request for the image. But at that point, you haven't yet set img.crossOrigin. Move the img.crossOrigin line above the img.src line.

That fixes the tainted canvas problem, but you still won't get your URL. The request for the image is asynchronous. You're trying to draw to the canvas with an image that hasn't loaded yet. Move the rest of the code into a load handler on your image and put the img.src line at the end to kick the whole thing off:

const img = document.createElement('img');
img.crossOrigin = 'anonymous';
img.addEventListener('load', () => {
  const canvas = document.createElement('canvas');
  canvas.width = img.width;
  canvas.height = img.height;
  const ctx = canvas.getContext('2d');
  ctx.drawImage(img, 0, 0);
  console.log(canvas.toDataURL('image/jpg'));
});
img.src = 'https://upload.wikimedia.org/wikipedia/commons/thumb/2/26/Strychnine.svg/360px-Strychnine.svg.png';

Post a Comment for "Tainted Html Canvas Even With Cors Headers"