B
B
Bogdan2019-05-23 21:09:14
JavaScript
Bogdan, 2019-05-23 21:09:14

Canvas and crossOrigin?

Hello. Please tell me how to do it right so that it would be possible to edit the image in the canvas, otherwise an error pops up?

DOMException: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.

Found, only such a solution, can it be somehow easier to do?
const loadImageCrossOrigin = url => new Promise((resolve, reject) => {
  const img = new Image();
  img.crossOrigin = 'anonymous';
  img.src = url;
  img.onerror = error => reject(error);
  img.onload = () => {
    const canvas = document.createElement('canvas');
    const context = canvas.getContext('2d');

    canvas.width = img.width;
    canvas.height = img.height;
    context.drawImage(img, 0, 0);

    resolve(canvas.toDataURL('image/jpeg'));
  };
});

Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
twobomb, 2019-06-02
@twobomb

The images you are editing and the script must be on the same domain.
For development, install for example Apache and develop a script on it.
PS In my opinion, even if you put the script and images in the same folder on the desktop, not on the server, it will give an error. Not to mention that you develop on some kind of jsfiddle\codepen, and take images from google images...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question