Js Canvas画图加载远程连接报错:
Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
报错Screenshot
尽管没有CORS授权也可以在 canvas 中使用图像, 但这样做就会污染(taints)画布。 只要 canvas 被污染, 就不能再从画布中提取数据, 也就是说不能再调用 toBlob()
, toDataURL()
和 getImageData()
等方法, 否则会抛出安全错误(security error).
这实际上是为了保护用户的个人信息,避免未经许可就从远程web站点加载用户的图像信息,造成隐私泄漏。
代码实例:
var canvas = window.document.createElement('canvas'); var ctx = canvas.getContext('2d'); var image = new Image(); image.src = 'xxxx?7c44414156d579012ee2c9845b276e3e'; image.onload = () => { canvas.width = 500; canvas.height = 500; ctx.drawImage(image, 0, 0, 500, 500); var imgSrc = canvas.toDataURL('image/png', 1); console.log(imgSrc); } /* VM1604:10 Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported. at Image.image.onload (<anonymous>:10:23) */
解决方案:
- 允许远程服务器Access-Control-Allow-Origin开启跨域
- 图片服务放在同一台服务器