Working with images and pixel data?

I’m trying to get image data into the Babylon engine to create geometry based on the pixel color.
I tryed different solutions, but can’t get the data into my script.

I found this code here and made a few changes:

var imageData;

function getPixels(){
        var img = new Image();
        img.onload = function(){
            var canvas = document.createElement('canvas');
            var context = canvas.getContext('2d');
            canvas.width = img.width;
            canvas.height = img.height;
            context.drawImage(img, 0, 0 ); 
            imageData = context.getImageData(0, 0, img.width, img.height);
        img.src = "/apps/gridMaker/tex/hopper.jpg";


and get this log:

In the onload function the data logs perfectly fine, but in the second, the image is’nt loaded yet. Am I right?

How can I make sure to use the image data down the script to work with it? I tried async functions and await, but I couldn’t figure it out.

Im glas for any advice.
Thanks a lot!

This is because onload is async so at the time of the second log there are no data in so far, you should execute the code that needs your data after onload has been called.

1 Like