Home > front end >  new Image not working with crossOrigin "Anonymous"
new Image not working with crossOrigin "Anonymous"

Time:11-11

So I am trying to load one of these urls to new Image however all of them doesn't seem to load. I have an image.onload function but it doesn't go there. But if I remove the image.crossOrigin, it works. But the problem is if I remove the crossOrigin. I will get a canvas tainted error in my function inside the onl oad.

Here is a sample jsfiddle: enter image description here

CodePudding user response:

For safety reasons the browser does not allow to load images from unknown origin. Here is a good article defining the behaviour.

To be able to load without tainted canvas, you should check your server CORS configuration and see if your current working domain is allowed as an Origin

Localhost have to be enabled also, it's not enabled by default. Eg. configuration option to be set as a header on the server: Access-Control-Allow-Origin: localhost

Note that this way only a single origin can be specified. If the server supports clients from multiple origins, it must return the origin for the specific client making the request. Link

Also note that for most servers there are good libraries to enable and handle theses kinds of CORS options with ease, you should look into it or ask your backend developer to add the necessary domains.

If CORS is set right then you can safely removed the anonymus setting. Anonymus basically tries to call the server resource without any credentials. If this happens then it's up to the server to decide whether it serves the request or not.

  • Related