HTML provides a crossorigin attribute for images that, in combination with an appropriate CORS header, allows images defined by the <img> element that are loaded from foreign origins to be used in a <canvas> as if they had been loaded from the current origin.
The CORS behavior, commonly termed as CORS error, is a mechanism to restrict users from accessing shared resources. This is not an error but a security measure to secure users or the website which you are accessing from a potential security bleach.
The crossorigin attribute is a CORS settings attribute. Its purpose is to allow images from third-party sites that allow cross-origin access to be used with canvas .
I usually use http://imgur.com/ for images (same site as SO uses for their inline images) - no sign up required, just upload or paste in an image link and you're ready to go.
It support CORS requirement so you can link directly and use it with canvas for pixel extraction.
If you need to host different files in addition to image I would suggest DropBox as markE does.
There are restriction however, as with any free service incl. ImgUr and DropBox, so be sure to read the Terms (ToS) of use before using the links (ie. none of them intent to function as a CDN so you might want to check out some commercial CDN providers).
If allowed you can do this in JavaScript - set crossOrigin before setting src:
var img = new Image();
img.crossOrigin = ""; // or "anonymous", will be interpreted the same
...
img.src = "...";
As attribute for HTML tag (order doesn't matter):
<img crossOrigin="" src="" ...>
var img = new Image();
img.crossOrigin = "";
img.onload = test;
img.src = "https://i.imgur.com/fHyEMsl.jpg";
function test() {
var ctx = document.querySelector("canvas").getContext("2d");
ctx.drawImage(this, 0, 0);
// This will fail if no CORS support, otherwise all OK
try {
ctx.getImageData(0, 0, 10, 10);
alert("All OK");
}
catch(err) {
alert("No CORS support...");
}
}
<canvas></canvas>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With