Requirements:

The system needs the function of saving pictures, download the screenshot of the atlas in the form of pictures. Considering that online pictures can not get picture resources, we have to change it to Base64 first, but the result is normal in the local browser (Chrome 90). An error occurs in Chrome 58

The relevant code

let base64 = '';
const img = new Image();
img.src = url;
img.setAttribute("crossOrigin",'Anonymous')
let that = this;
img.onload = function() {
  console.log('img', img)
  const canvas = document.createElement("canvas");
  canvas.width = img.width;
  canvas.height = img.height;
  const ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0, img.width, img.height);
  const dataURL = canvas.toDataURL("image/png");
};
Copy the code

Error message

Analysis of the

  1. Chrome 90 generates base64 correctly, but Chrome 58 generates base64 correctly, which is a non-cross-domain problem. And the pictures are stored on the Gofast server
  2. It is already set on the IMG elementcrossoriginattribute

Surf the Internet

Cross-domain images can be cropped normally (images not converted to Base64) and should meet three conditions:

  1. Set in the IMG elementcrossoriginattribute
  2. Images are allowed to cross domains, setting response headersAccess-Control-Allow-Origin
  3. To request image resources in JS mode, avoid caching. Set the URL with a timestamp, or set cache-control to no-cache in the HTTP header

The main reason is that

  1. If a cross-domain resource is used to draw the canvas and the resource is not requested using CORS, the canvas will be considered polluted. The canvas can be displayed normally, but cannot be usedtoDataURL()ortoBlob()To export data, seeAllowing cross-origin use of images and canvas. So by setting it on the IMG tagcrossorigin, enable CORS, and the property value isanonymous, authentication information is not sent during CORS requests, seeHTML attribute: crossorigin.
  2. When CORS is enabled to request cross-domain resources, resources must be allowed to cross domains in order to return normally. The simplest way to set the response headerAccess-Control-Allow-Origin
  3. The image has already been loaded by the IMG tag, and the browser will cache it by default. The next time you request it in JS mode, you will return the cached image directly. If the image in the cache is not through the CORS request or does not exist in the response headerAccess-Control-Allow-Origin, will result in an error.

Modify the

img.src = url + '? time=' + new Date().valueOf();Copy the code