1

I have an array of pixel locations that I need to grab RGB values from and store in a new array. When I console log the array I see all the values but when I console log the first element array[0] I get undefined.

    var topArray = [
            {x: 198, y: 132},
            {x: 219, y: 138},
            {x: 233, y: 157},
            {x: 225, y: 179},
            {x: 201, y: 187},
            {x: 177, y: 176},
            {x: 163, y: 156},
            {x: 178, y: 138},
    ];
        
        
        let avyGridTop = [];
        
        
        
        var img = new Image();
        img.src = '/images/avy20210303.png';
        var canvas = document.getElementById('canvas');
        var ctx = canvas.getContext('2d');
        img.onload = function() {
          ctx.drawImage(img, 0, 0);
          img.style.display = 'none';
          topArray.forEach(pickArray);
        };
        
        function pickArray(event) {
          var x = event.x;
          var y = event.y;
        
          var pixel = ctx.getImageData(x, y, 1, 1);
          var data = pixel.data;
          var r = data[0];
          var g = data[1];
          var b = data[2];
        
          var rgb = {r, g, b};
          avyGridTop.push(rgb);
        
        };
console.log(avyGridTop[0]);
jjhi11
  • 11
  • 2
  • `pickArray()` won't be called until the image loads. – Pointy Mar 04 '21 at 20:01
  • pickArray is what builds avyGridTop though. When I console that it has values that I cannot call by element index. – jjhi11 Mar 04 '21 at 20:18
  • 1
    That is because you are trying to log out an object. You could log the x or y property though by doing something like this: console.log(topArray[0].x) – TinMonkey Mar 04 '21 at 20:23
  • You can certainly console.log an object, but are you trying to do it before the array has been filled with at least the first object? Where are you calling console.log(avyGridTop[0])? – A Haworth Mar 04 '21 at 22:26
  • I am trying to get the rgb values in an array that I can call on to color a map further in to the code. Not sure how to proceed. – jjhi11 Mar 04 '21 at 22:31
  • Unrelated to the question: Do not call getImageData for each of your pixels, call it once, grab the full canvas, and then get the pixel values from that single ImageData: https://jsfiddle.net/5xfhmnus/ – Kaiido Mar 05 '21 at 02:40

0 Answers0