html

2019-04-11 19:30发布

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

2条回答
何必那么认真
2楼-- · 2019-04-11 19:42

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).

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:

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);
    };
}

And we can call it by this (es6):

let url='https://static.pexels.com/photos/87293/pexels-photo-87293.jpeg';
this.loadImgAsBase64(url, (dataURL) => { console.log('imgData:',dataURL) });

Thats all :) (I tested it only on chrome)

查看更多
姐就是有狂的资本
3楼-- · 2019-04-11 19:56

The only way to avoid CORS is to make changes to avoid cross-origin sharing, at least let the browser thinks that it is cross-origin.

Or, you have to modify the server to support CORS.

查看更多
登录 后发表回答