1

For getting color from image at a specific coördinate I have used this answer get-pixel-color-from-canvas-on-mouseover. However on the Powerpoint on page 56 from Microsoft it says that getImageData must used once, because calls from the graphic card is intensive. They gave an example how to do it, but there it is made for analyse the whole picture.

Is there a way to use getImageData just once and then analyse only the data from a specific x and y coördinate at like I say 5 random places?

EDIT: for checking each pixel the example does:

var imageData = ctx.getImageData(0, 0, width, height);
var inputData = imageData.data;

for(var y = 0; y < height; y++) {
    for (car x = 0; x <width; x++) {
       var r = inputData[i+0];
var g = inputData[i+1];
var b = inputData[i+2];

But I want is that it does like below but then with the imageData outside: How can I read the Array with the positions I want? Because the number in the brankets are the color value type (r,g,b)

for (var i=0; i<slider; i++)
{
    var objectx = position.getX();
    var objecty = position.getY();
    var imageData = context.getImageData(objectx, objecty, 1, 1).data; 
    var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
}
Community
  • 1
  • 1

1 Answers1

2

Its pretty easy to do see the following.

Live Demo

var imageData = ctx.getImageData(0, 0, width, height);
var inputData = imageData.data; 

var pData = (~~objectx + (~~objecty * width)) * 4;
var r = inputData[pData],
    g = inputData[pData + 1],
    b = inputData[pData + 2],
    a = inputData[pData + 3];

~~ is just a faster way to do Math.floor. The rest should hopefully be pretty self explanatory. Just change objectx, and objecty to whatever values you need and continue to check the inputData as long as the image hasn't changed theres no need to getImageData again.

Loktar
  • 34,764
  • 7
  • 90
  • 104
  • 1
    Thank you, it works brilliant. And it does not only work, but if you read the code it explains also how the imageData functions. Great! – Martijn Hoogers Mar 11 '13 at 09:35