This article mainly introduces the relevant information on how to solve the problem of toDataURL() error caused by the introduction of cross-domain images in Canvas. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look.
Recommended Manual: HTML5 latest version reference manual
This article introduces the results of the introduction of cross-domain images in Canvas The solution to the error reported by toDataURL() is shared with everyone. The details are as follows:
[Scenario]
The user opens the webpage and requests Tencent COS (picture images on the server). Draw using canvas.
Then, the user can reselect the image, crop it, and upload it.
[Problem]
When the picture is loaded for the first time, there is no problem with cropping and drawing after selecting a new picture. But the upload failed, and the error was reported as follows:
and run again. I found that the image was not displayed when it was loaded for the first time. . .Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported. When quoting, set the crossOrigin field:
var c=document.getElementById("cover_show"); var img=new Image(); img.src="http://vsqx-cover-xxxxxx.coscd.myqcloud.com/"+this.vsqx_uid+".jpg"; //增加这一行: img.setAttribute("crossOrigin",'anonymous'); img.onload = function(){ var cxt=c.getContext("2d"); cxt.drawImage(img,0,0,300,150,0,0,200,126); }Copy after login
The console error is as follows:
[Final solution]
Log in to Tencent Cloud COS , find this bucket, and set "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.
Recommended related articles:
1.Introduction to the role of the html5 canvas tag and the historical origin of the canvas tag
2.Three-minute HTML5 canvas (Canvas) animation tutorial
Related Video tutorial: 1.
Dugu Jiujian (1)_HTML5 video tutorial
The above is the entire content of this article, I hope it will be helpful to everyone's learning!
The above is the detailed content of How to solve the problem of toDataURL() error when introducing cross-domain images in Canvas. For more information, please follow other related articles on the PHP Chinese website!