-4

I want to be able to get the color of a pixel at specific x,y co-ordinates on a canvas (A rectangles color, but the pixel will sufice).

Is there anyway of doing this with normal javascript without adding any additional libraries?

I'm developing it with the idea of mobile platforms and would prefer not to use external libraries. Thanks

4

2 回答 2

2

For the answer let's go straight to the source.

You want context.getImageData(x, y, width, height);

This grabs a rectangle out of the canvas and returns all the pixels there in the form of an "ImageData" object. This object in turn has a "data" attribute which is, for all intents and purposes, just a normal Array (it's not, but you can pretend it is if you just want to read from it).

The data array looks like

[r,g,b,a,r,g,b,a,r,g,b,a,...] where r,g,b, and a are the red, green, blue, and alpha channels of the colour of one pixel. The pixels are ordered as if they were being read in an english book (left to right, then top to bottom).

For you purposes, you can just do var pixel = context.getImageData(x,y,1,1).data. Then if you want to know the red part, do pixel[0], green? pixel[1]... and so on.

However remark that in my emprical tests, getImageData is an incredibly expensive operation (especially in Firefox; Chrome handles it faster, but with less bounds-checking). If you expect to do this query many times per-second, it may be worth getting a larger rectangle to cache some results. Of course this won't work if the pixel data is rapidly changing.

于 2013-02-16T16:54:33.410 回答
1

Canvas 的 getImageData() 返回一个 ImageData 对象,该对象复制画布上指定矩形的像素数据。

var color = canvas2d_context.getImageData(pixel_coord_x, pixel_coord_y, 1, 1);

console.log('pixel red value:   ' + color.data[0]);
console.log('pixel green value: ' + color.data[1]);
console.log('pixel blue value:  ' + color.data[1]);
console.log('pixel alpha value: ' + color.data[1]);

...主要来自http://www.w3schools.com/tags/canvas_getimagedata.asp

于 2013-02-16T16:49:10.633 回答