Canvas tainted by cross-origin requests

Dear All,

This is probably more of a silly Javascript question. I have a notebook that throws an error, as I can’t simply pass a URL to a canvas element, due to cross-origin requests. I can easily load the images directly using Image, however…

Any ideas?


You need to use a CORS-enabled image. Here’s an example from my Hello, SqueezeNet! notebook:

image = new Promise((resolve, reject) => {
  const image = new Image;
  image.crossOrigin = "anonymous";
  image.src = "";
  image.onload = () => resolve(image);
  image.onerror = reject;

This one also uses a Promise so that the image cell doesn’t resolve until the image is done loading. Depending on your needs, you might not care to wait until the image has loaded, in which case you can say more simply:

image = {
  const image = new Image;
  image.crossOrigin = "anonymous";
  image.src = "";
  return image;

Note that to load a CORS-enabled image, the server will need to return the appropriate CORS headers (Access-Control-Allow-Origin: *). GitHub does that for, so any GitHub-hosted image should be fine.