0

I have an array of x,y locations of specific pixels that I need to grab RGB values from. I get 0,0,0 results with my code as it is now. Any help?

const 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},
];

avyGridTop = [];

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;

  const rgba = [data[0], data[1], data[2]];
    avyGridTop.push(rgba);

};
jjhi11
  • 11
  • 2
  • What is in the canvas, it would do this if it was empty or not loaded yet. see https://stackoverflow.com/questions/32279288/getimagedata-returning-all-zeros – James Mar 03 '21 at 23:09
  • Doh, exactly it. Added the function to img.onload. Thank you! – jjhi11 Mar 03 '21 at 23:48
  • @jjhi11 If you solved your own problem, you should post it as an answer. – 0xLogN Mar 04 '21 at 03:44
  • Thanks @LoganDevine. I have another question though. My array that I push to avyTopGrid isn't able to be called by the indexes. Like so avyTopGrid[0]. I've tried pushing both as an object and an array. – jjhi11 Mar 04 '21 at 13:36
  • one thing is that avyTopGrid should be *defined* not just *initialized*, eg `let avyTopGrid = []` – 0xLogN Mar 04 '21 at 16:29

1 Answers1

0

I fixed this by moving topArray.forEach(pickArray) to within the img.onload.

This way it fires after the img has loaded.

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';
  console.log("img loaded");
    topArray.forEach(pickArray);
};

function pickArray(event) {
  var x = event.x;
  var y = event.y;

  console.log(ctx);
  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 rgba = {r: data[0], g: data[1], b: data[2]};
console.log(rgba);
    avyGridTop.push(rgba)

};
jjhi11
  • 11
  • 2