views:

4699

answers:

3

Is it possible to query a HTML Canvas object to get the color at a specific location?

+11  A: 

There's a section about pixel manipulation in the W3C documentation.

Here's an example on how to invert an image:

// Get the CanvasPixelArray from the given coordinates and dimensions.
var imgd = context.getImageData(x, y, width, height);
var pix = imgd.data;

// Loop over each pixel and invert the color.
for (var i = 0, n = pix.length; i < n; i += 4) {
    pix[i  ] = 255 - pix[i  ]; // red
    pix[i+1] = 255 - pix[i+1]; // green
    pix[i+2] = 255 - pix[i+2]; // blue
    // i+3 is alpha (the fourth element)
}

// Draw the ImageData at the given (x,y) coordinates.
context.putImageData(imgd, x, y);
Georg
+1  A: 

Yup, check out getImageData(). Here's an example of breaking captcha with JavaScript using canvas:

http://ejohn.org/blog/ocr-and-neural-nets-in-javascript/

Adam Backstrom
+2  A: 

Have you tried the getImageData method ?

data = canvas.getImageData(x, y, 1, 1).data;
color = new Color([data[0], data[1], data[2]]);
Theo.T