0

I need to load a png file from my computer and loop through each pixel value. I tried canvas, but it breaks with the cross-domain stuff I dont understand...

var img = new Image(); 
img.src = "map.png";

var canvas = document.getElementById("secondaryCanvas");
var ctx = canvas.getContext("2d");

ctx.drawImage(img, 0, 0, 30, 30);

console.log(ctx.getImageData(0,0,1,1));

...Sometimes it works, sometimes it doesnt?... Im absolutely lost

titoco3000
  • 51
  • 1
  • 6
  • Please create a snippet for us to use to help you. :) – Joel Hager Apr 30 '20 at 00:51
  • Maybe this answer can be of any help https://stackoverflow.com/a/13939150/1471485 – John Apr 30 '20 at 00:52
  • You can also try to add the image directly into your app (e.g. inside a folder, img). Then the image is fetched on the same domain, and you avoid CORS errors. – John Apr 30 '20 at 00:54

2 Answers2

0

You can not read the pixel data if the page is being load directly from the file system. You must load the page from a web server. Install apache and load it from localhost

About the fact that it sometimes "work" it depends on whether the image has been draw in the canvas when you call getImageData.

if the image has not been loaded you can call getImageData because you are not reading the image data but the blank canvas.

if you call the getImageData inside the image onload event the code will always fail

var img = new Image(); 
img.onload = function() {
    console.log(this)
    var canvas = document.getElementById("secondaryCanvas");
    var ctx = canvas.getContext("2d");

    ctx.drawImage(img, 0, 0);

    console.log(ctx.getImageData(100,100,1,1));
}
img.src = "map.png";
sney2002
  • 856
  • 3
  • 6
0

This is a quick (althopugh not clean) example that I made on the bus just because I couldn't believe that nobody answered with this hack

If you want to test it save it as index.html and open it with chrome

TLDR; load file as base64 then use it as src for the image

<script>

    async function toBase64(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = () => resolve(reader.result);
            reader.onerror = error => reject(error);
        });
    }

    async function reset() {
        const input = document.querySelector('input');
        console.log(input.files)

        const base64 = await toBase64(input.files[0]);
        console.log(base64)

        const src = base64;

        var img = new Image();
        img.onload = function () {
            console.log(this)
            var canvas = document.getElementById("secondaryCanvas");
            var ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0);
            console.log(ctx.getImageData(100, 100, 1, 1));
        }
        img.src = src;
    }
</script>
<input type="file" id="input" onchange="reset()" />
<canvas id="secondaryCanvas"></canvas>