简体   繁体   中英

crossOrigin attribute messing with the external image retrieval on Chrome

I'm using HTML Canvas to compose an image on my page. One of the element of my canvas is an image coming from an external domain (Amazon S3), I retrieve this image using CORS and using the crossOrigin attribute on my image loading.

var image = document.createElement('img');
image.setAttribute('crossOrigin', '');
image.onload = function() {
    CANVASCONTEXT.drawImage(image, 0, 0, 200, 200)
}
image.setAttribute('src', MYEXTERNALURL);

And to get the image data:

MYCANVAS.toDataURL()

Everything works fine on Firefox.

On Chrome I cannot retrieve the image from my external source and got the error:

No 'Access-Control-Allow-Origin' header is present on the requested resource

As if the CORS configuration wasn't set.

If I remove the crossOrigin attribute, I can compose my image but I can't use toDataURL() to get the image data (and this makes sense).

Do you have any pointer, any workaround to this problem?

Thanks

Chrome blocked Cross Origin Querys.

You can fix it with htaccess or host Settings.

Apache/Htaccess:

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

Nginx:

location / {
add_header Access-Control-Allow-Origin *;
}

You can read it in german on my blog .

Wow, I figured out what was the problem.

I was requesting the external ressource twice (first time to check if the image was existing, the second time to make the request into the canvas). On the second call, the image was cached by the browser. So I guess the canvas was failing to draw the image because of the source of this image (browser's cache).

I can't tell if that makes sense or not, but I know I'll rewrite this part of my code!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM