Get color from array returned by canvas.getImageData() method

Viewed 1869

I have a canvas and want to dynamically get the color of a pixel. Im using getImageData() to get an array containing the colors. I only want to call getImageData() once and get all the color data from it once. This is because in my use case I will loop over an array of size 1 million containing of x, y coordinates for the canvas.

However I cannot figure out how to get the color from the image array with the x, y coordinates. Here's my code:

var canvas = document.getElementById("canvas");
var context = canvas.getContext('2d');

context.beginPath();
context.rect(0, 0, 200, 200);
context.fillStyle = 'black';
context.fill();
context.closePath();

context.beginPath();
context.rect(50, 50, 50, 50);
context.fillStyle = 'red';
context.fill();
context.closePath();

var imageData = context.getImageData(0, 0, 200, 200).data;

console.log('imageData is ', imageData);

for(var x = 0; x < 10; x++) {

    var x = Math.floor(Math.random() * 200);
    var y = Math.floor(Math.random() * 200);

    console.log('x, y is ', x, y);

    // how to I get the color here?
    var color = Uint8ClampedArray[x][y];

    console.log('color is ', color);
}

I get an error at the line:

var color = Uint8ClampedArray[x][y];

All other solutions involve calling getImageData() each time on the coordinate with a width and height of 1. But I dont want to do this, preferring to query imageData to get the color....

Fiddle is here.

1 Answers
Related