Canvas + CrossOrigin Anonymous + CORS + Chrile + Mac OSX

做~自己de王妃 提交于 2020-01-03 05:11:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!