Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
时间: 2023-09-22 17:12:36 浏览: 163
Canvas引入跨域的图片导致toDataURL()报错的问题的解决
5星 · 资源好评率100%
"Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported"是一个报错信息,意味着当使用canvas的toDataURL()方法时,画布上存在被污染的图像(即跨域的图像),不能导出。原因是在使用drawImage()方法将跨域的图片绘制到canvas上。解决方法包括以下两个步骤:
1. 在引用图片之前设置跨域资源允许权限。这可以通过在创建image对象之后设置image对象的crossOrigin属性为'anonymous'来实现。示例代码如下:
```
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = '图片地址';
```
请确保在设置crossOrigin属性之后再设置图片的src属性。
2. 确保存放图片的服务器开启了跨域允许权限。否则,可能会出现"No 'Access-Control-Allow-Origin' header is present on the requested resource"的错误提示。你可以联系服务器管理员或者在服务器端配置相应的跨域请求头。
通过以上两个步骤,你应该能够解决"Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported"的问题。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported [已解决]....](https://blog.csdn.net/qq_35516360/article/details/122065183)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *2* [Canvas引入跨域的图片导致toDataURL()报错的问题的解决](https://download.csdn.net/download/weixin_38693419/14830620)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *3* [canvas生成图片toDataURL报错(Uncaught DOMException: Failed to execute ‘toDataURL‘ on ‘HTMLCanvasEl...](https://blog.csdn.net/sumimg/article/details/115375085)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"]
[ .reference_list ]
阅读全文