Search code examples
javascriptcanvasgetimagedata

use app image data on not respectable websites


I use canvas.getImageData to get the colour of one pixel in a HTML/js canvas. If it isn't an respectable website it is load on, it won't do it, because of cross-origin data. But I can't make the website respectable, because I want to open it as HTML document on my device, to be able, to open it offline. I load images into the canvas, but when you don't have internet, it will load the image saved in localStorage (as dataURL). Thanks for your attention I'm happy about every answer which might help


Solution

  • There are two ways to load cross-origin images. First is using fetch and blob:

    let image_url = await(await fetch(url, mode='cors')).blob();
    let image = new Image;
    image.url = image_url; 
    

    The other option is to set crossOrigin=anynymous on the image element:

    downloadedImg = new Image;
    downloadedImg.crossOrigin = "Anonymous";
    downloadedImg.addEventListener("load", imageReceived, false);
    downloadedImg.src = imageURL;
    

    See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image