This article introduces the solution to the problem of toDataURL() reporting an error when introducing cross-domain images in Canvas. I would like to share it with you. The details are as follows:
【Scene】
When a user opens a web page, he or she requests pictures on Tencent COS (picture server). Draw using canvas.
The user can then reselect the image, crop it, and upload it.
【question】
When the image is loaded for the first time, there is no problem with cropping and drawing after selecting a new image. But the upload failed with the following error:
Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
After understanding, you need to set the crossOrigin field when the image is referenced for the first time:
var c=document.getElementById(cover_show); var img=new Image(); img.src=http://vsqx-cover-xxxxxx.coscd.myqcloud.com/+this.vsqx_uid+.jpg; //Add this line : img.setAttribute(crossOrigin,'anonymous'); img.onload = function(){ var cxt=c.getContext(2d); cxt.drawImage(img,0,0,300,150,0,0,200,126); }
Then run it again. I found that the image was not displayed when it was loaded for the first time. . .
The console error is as follows:
【Final solution】
Log in to Tencent Cloud COS, find this bucket, and set up cross-domain access CORS. (The same applies to other PHP/JAVA servers)
Test again: the image is displayed successfully and the image is uploaded successfully.
The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support VeVb Wulin Network.