Search code examples
javascripthtml5-canvas

Javascript Get pixel data of image


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


Solution

  • 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>