The Ultimate Solution for Cross-origin Images in Canvas

Browsers do not allow Canvas to use getImageData or toDataURL on cross-origin images due to security concerns.

Traditional Solutions

1. Server needs to configure Access-Control-Allow-Origin

I’m sure you’ve seen this line of code many times, so I’ll keep it brief.

header("Access-Control-Allow-Origin: your-domain.com");

2. Set the crossOrigin Attribute

var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');

var img = new Image();
img.crossOrigin = 'anonymous';
img.onload = function () {
    context.drawImage(this, 0, 0);
    context.getImageData(0, 0, this.width, this.height);
};
img.src = 'https://avatars3.xxxx.com/u/496048';

At this point, your cross-origin issues are mostly resolved. But what if the backend engineer refuses to set the cross-origin header for objective reasons?

The ultimate solution: use ajax to fetch the image, convert it to base64 with FileReader, and then process the base64 image with canvas.

Getting the base64 of an image

function getBase64(imgUrl) {
  return new Promise(((resolve, reject) => {
    window.URL = window.URL || window.webkitURL;
    const xhr = new XMLHttpRequest();
    xhr.open('get', imgUrl, true);
    xhr.responseType = 'blob';
    xhr.send();
    xhr.onload = function () {
      if (this.status === 200) {
        const blob = this.response;
        const oFileReader = new FileReader();
        oFileReader.onloadend = function (e) {
          const base64 = e.target.result;
          resolve(base64);
        };
        oFileReader.onerror = function (e) {
          reject();
        };
        oFileReader.readAsDataURL(blob);
      }
    };
  }));
}

Canvas Image Processing

const base64 = await getBase64(imgSrc);
const img = new Image();
img.src = base64;

var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
img.onload = () => {
    context.drawImage(this, 0, 0);
    context.getImageData(0, 0, this.width, this.height);
};

That’s it for today.

Article Link:

/en/archive/canvas-cross-origin-image/

# Related Articles