问题
For the purpose of loading images to a canvas, I use this method =>
const load = (url: string) =>
new Promise((resolve, reject) => {
const image = new Image();
if (!image) reject();
image.crossOrigin = 'Anonymous';
image.src = url;
image.addEventListener('load', () => resolve(image));
image.addEventListener('error', err => reject(err));
});
After investigating a lot, I found out that i am encoutring this bug : https://bugs.chromium.org/p/chromium/issues/detail?id=409090
Indeed, randomly pictures are not shown in the moodboard.
I didn't wrote the code, so I am not sure of the necessity of this line, what would be the difference with or without it ?
image.crossOrigin = 'Anonymous';
UPDATE 1
When I remove the image.crossOrigin = 'Anonymous';
the image loading doesn't have CORS issue anymore but then I get this error when trying to use the canvas.toDataURL('image/png')
on the canvas
Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
回答1:
If your images come from a different domain, and you want to be able to export the canvas content after you did draw these images, then you have no choice than loading them with the crossOrigin
attribute.
If you are really facing the linked bug, according to it, the proper fix is to always send the CORS headers from your server response, whether or not the request is made with the Origin header.
And a fast workaround is to avoid the cache, by appending a random query string in the image's src (img.src = url + '?v=' + Math.random();
).
来源:https://stackoverflow.com/questions/46609800/canvas-crossorigin-anonymous-cors-chrile-mac-osx