Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

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 several ways to solve this leapfrog problem

First, convert the image to base64

When the image becomes base64, there is no domain name, so there is no cross-domain

Note: converting an image to Base64 will increase the size of the image file. If the image is large, it is not recommended to convert base64, otherwise it will increase the loading time of the web page and affect the speed of the website. This method is generally suitable for small images

Second, the image server Settings allow cross-domain

Access-control-allow-origin returns a header with an access-Control-Allow-Origin tangent value of * (allows cross-domain requests from all websites) or the current website domain name (only allows cross-domain requests from fixed domain names). The front end then sets the image’s cross-domain property img.crossOrigin=”anonymous” before loading the image. 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()) }Copy the code

In this way, the cross-domain problem can be easily solved

Third, put the image under the current domain name

Forgive me for smiling unkindly, but this is a problem solver. BUT in real projects images are usually stored on CDN, so this approach is not practical 🌚🌝🌞Copy the code

When the image becomes base64, there is no domain name, so there is no cross-domain

4. When the image service cannot set the cross-domain response header

There is indeed such a situation, such as obtaining the head picture of the third party website, such as wechat head picture, and then the front end dynamically generates new pictures, wechat head picture is not allowed to export cross-domain, how to do?? None of the above works

This situation requires the assistance of the backend. The backend does a layer of forwarding, and the server obtains the profile picture, converts it into Base64 and returns it to the front end, or stores it on the local server that allows cross-domain, produces a new picture link and returns it to the front end. At this time, combining method 1 or method 2, the cross-domain problem is naturally solved

If you use htmlToCanvas to export images, you need to add the useCORS: True configuration item, the principle is the same as method 2, of course, the precondition is that the image domain name allows cross-domain

So far I know the N way is introduced, welcome to add