canvas读取图片报错 Tainted canvases may not be exported

2021/7/27 4:31:18webjs

完整错误信息:

Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

原因:图片跨域导致的错误,所以说是被污染的画布。

原始代码:

const img = document.querySelector('img');
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
document.body.appendChild(canvas);

console.log(canvas.toDataURL('image/png'));

解决方案:
1,不做最后一步toDataURL到处操作,直接将canvas 绑定到页面显示,让用户手动操作(长按/右键 进行保存图片)。
2,从服务器端去除图片跨域限制。