Mark
Mark

Reputation: 5078

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

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.

Upvotes: 3

Views: 2913

Answers (1)

Blindman67
Blindman67

Reputation: 54026

To get a pixel

var x = 100;
var y = 100;
var imageData = context.getImageData(0, 0, 200, 200);
var index = (x + y * imageData.width) * 4;
var r = imageData.data[index];
var g = imageData.data[index + 1];
var b = imageData.data[index + 2];
var a = imageData.data[index + 3];

There are 4 bytes per pixel, pixels are arranged in rows. So each row has 4 * the width bytes.

Thus you find the row or y

var rowStart = y * imageData.width * 4;

and to find the pixel at column x multiply by 4 and add to the start row index

var pixelIndex = rowStart + x * 4;

The next 4 bytes are the red, green, blue and alpha values of the pixel at x,y

Upvotes: 4

Related Questions