問題描述
當用戶點擊分享按鈕時,生成一張海報,可以保存圖片分享到朋友圈,用戶的圖片是存儲在阿里雲的OSS,當海報完成后,執行.canvas.toDataURL("image/png")時,出現index.html:28 Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported的錯誤提示,這句話的翻譯是uncaught domexception:未能對“htmlcanvaselement”執行“todataurl”:無法導出受污染的畫布。因為圖片跨域了,對畫布造成了污染。
解決方法
搜索相關問題,大多是為img設置crossOrigin屬性,實現圖片允許跨域,即:img.setAttribute("crossOrigin",'Anonymous'),我為圖片添加這個屬性后,圖片無法顯示了,報了一個錯誤: Access to image at 'https://claystar.oss-cn-shenzhen.aliyuncs.com/pic/9dd6d55c5c7334d9448c4628e6ff69f6.jpg' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
通過和同事溝通討論得知,只需要為圖片添加一個時間戳即可。最后解決方式:
img.src='http://www.xxxx.png' + '?time=' + new Date()