The problem background

There is nothing wrong with simply rendering cross-domain images in canvas, but to usegetImageData()toDataURL()When operating, the cross-domain image will report an error, usually with something like ⬇️Or the likehtml2canvasSuch a plug-in can parse DOM to generate base64 images, and it also uses canvas for conversion. If cross-domain images are encountered in DOM, there will also be problems

The solution

The most direct is to take the CROSS-origin Resource Sharing (CORS) standard

  1. The first step:

The image server must be configured with a response header access-Control-allow-Origin: *, or the specified domain name

  1. The second step:

(

,

In the use ofhtml2canvasWhen a plugin is used in the DOM<img>Tags and CSS background images can be used, and the plugin will convert them into Image elements and render them. Note: But you are directly inhtmlAdd is to the picturecrossOriginIf it is invalid, the plugin will ignore it and need to use ituseCORS: trueProperties, and then I’ll add cross-domain properties for you. See its source at ⬇️Also, allowTaint is not a feature to try. It seems to be a judgment switch in the plugin, so far it doesn’t affect it

CrossOrigin =anonymous As opposed to telling the server, you don’t need to bring any non-anonymous information. For example, cookies, so the current browser must be secure.

It’s like going to someone’s house and picking up a dress, as opposed to saying, I just want the dress and nothing else. If you don’t, maybe they put a bug in their clothes or something, it’s not safe, and the browser will stop it. (Excerpt from solving canvas picture getImageData,toDataURL cross-domain problem)

Three, the third step:

If your phone has already accessed the image before adding the above action, the response header will be stored in the cache, so the image may still not be displayed. You can add any string to the image SRC, for example:

<img :src="popBless.icon + '? deleteCache'" >Copy the code

New Date().gettime (

Other options

So far, there should be no problems according to the tests. If there are cross-domain problems, you can check to see if the browser does not support the crossOrigin attribute. You can try the following scheme, the idea is to make a request for another picture format

  1. blobFormat images

Post a native code to give you an idea:

var xhr = new XMLHttpRequest(); xhr.onload = function () { var url = URL.createObjectURL(this.response); // Use the URL as your image address here... RevokeObjectURL (URL); }; xhr.open('GET', url, true); xhr.responseType = 'blob'; xhr.send();Copy the code

2, base64 format can let the background students to help provide a picture link to base64 interface, is also a more common interface service

To the end.

Note: Html2Canvas test version of this article: 1.0.0-RC.5