This article introduces a summary of N postures to unlock cross-domain exported images from canvas. I would like to share them with you. The details are as follows:
Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
I believe everyone has encountered the above error when using canvas to execute toDataUrl to export images. The image server domain name is different from the current one because the security policy does not allow cross-domain export of images.
There are many ways to solve this spanning problem 1. Convert the image to base64When the image becomes base64, there is no need to talk about the domain name, and naturally there is no cross-domain
Note: Convert the image to base64 and increase the image file size. If the image is relatively large, it is not recommended to convert to base64, otherwise it will increase the web page loading time and affect the website speed. This method is generally suitable for small images.
2. Image server settings allow cross-domain That is, the response header returned by requesting the image contains Access-Control-Allow-Origin
with the value set to * (allowing cross-domain requests from all websites) or the current website domain name (only allowing cross-domain requests under fixed domain names), and then the front-end loads the image. Set the image cross-origin attribute img.crossOrigin=anonymous。
The specific code is as follows
var canvas = document.getElementById('myCanvas') var ctx = canvas.getContext('2d') var img = document.createElement('img') img.crossOrigin=anonymous img.src = 'https://p4-q.mafengwo.net/s12/M00/CA/3B/wKgED1w8fL6ADk16AAXyDaz2bdU61.jpeg' img.onload = function() { ctx.drawImage(img,0,0,500,300); console.log(canvas. toDataURL()) }
In this way, cross-domain problems can be easily solved by combining both front and rear
3. Put the image under the current domain nameForgive me for laughing unkindly, this is indeed a solution to the problem.
BUT In actual projects, images are generally stored on CDN, so this method is not realistic.