关于html2canvas得到的canvas不能使用toDataUrl等方法

135 阅读1分钟

在使用html2canvas等到了一个canvas后,使用canvas.toDataURL(),界面会报一个错

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

原因是图片跨域了

根据网上的解决方法,html2canvas的配置项加上useCORS: true或img标签加上crossOrigin="Anonymous",但都不起效

解决办法:不要让canvas去解决跨域,自己在转canvas之前解决

img的src使用临时地址

const blob = await fetch(url).then((r) => r.blob())

const tempUrl: any = URL.createObjectURL(blob as Blob)