Search code examples
javascripthtmlcorshotlinking

Html <img src=...> works but JS Image loading cause CORS error


I want to create picture editor in js+jquery. At the first step i ask user to give image url. But I come across problem when i try load image data inside JS (to generate base64 image uri). I get error in console: … has beeb blocked by CORS policy: Access-Control-Allow-Origin …. But I wonder why? If in html file i create for instance (image hotlink):

<img  src="https://static.pexels.com/photos/87293/pexels-photo-87293.jpeg" />

The browser load image without any CORS problems ! Here is my JS code which for the same image throw CORS problem:

 function downloadFile(url) {
    console.log({url});    
    var img = new Image();
    img.onload = function() {
        console.log('ok'); 
        // never execute because cors error
        // … make base64 uri with image data needed for further processing
    };

    img.crossOrigin = "Anonymous";
    img.src = url;
}

So the question is - how to force JS to load image (as html-tag load it) and convert it to base64 url avoiding CORS problem?

https://static.pexels.com/photos/87293/pexels-photo-87293.jpeg


Solution

  • I try to found solution my self (JS ES6) but find only-partially. We are able to load img from no-CORS support src into canvas but browser switch cavnas into 'taint mode' which not allow us to call toDataURL (and any other access to content).

    function loadImgAsBase64(url, callback) {
      let canvas = document.createElement('CANVAS');
      let img = document.createElement('img');
      //img.setAttribute('crossorigin', 'anonymous');
      img.src = url;
    
      img.onload = () => {
        canvas.height = img.height;
        canvas.width = img.width;
        let context = canvas.getContext('2d');
        context.drawImage(img, 0, 0);
        let dataURL = canvas.toDataURL('image/png');
        canvas = null;
        callback(dataURL);
      };
    }
    
    
    let url = 'http://lorempixel.com/500/150/sports/9/';
    
    this.loadImgAsBase64(url, (dataURL) => {
       msg.innerText = dataURL.slice(0,50)+'...';
    });
    IMAGE DATA: loading...<br>
    <div id="msg"></div>

    So only way to overcome this obstacle is to create proxy server (e.g. in PHP) which will have CORS 'on' and it will download images for given url and send back to our app in JS. I found some free server https://cors-anywhere.herokuapp.com which we can use to in development to tests. Below there is full functional code which return dataUri from given image url:

    function loadImgAsBase64(url, callback) {
      let canvas = document.createElement('CANVAS');
      let img = document.createElement('img');
      img.setAttribute('crossorigin', 'anonymous');
      img.src = 'https://cors-anywhere.herokuapp.com/' + url;
    
      img.onload = () => {
        canvas.height = img.height;
        canvas.width = img.width;
        let context = canvas.getContext('2d');
        context.drawImage(img, 0, 0);
        let dataURL = canvas.toDataURL('image/png');
        canvas = null;
        callback(dataURL);
      };
    }
    
    
    let url = 'http://lorempixel.com/500/150/sports/9/';
    
    this.loadImgAsBase64(url, (dataURL) => {
       msg.innerText = dataURL.slice(0,50)+'...';
       // show pic
       document.body.innerHTML += `<img src="${dataURL}">`
    });
    IMAGE DATA Loading...<br>
    <div id="msg"></div>

    Thats all :) (I tested it on chrome, firefox and safari)