How to read a color of a pixel at [x,y] from a texture (in cocos2d-js)?

  • \$\begingroup\$ What do you want to read? Its color? Its alpha? Its mood? Are you retrieving it offscreen, world coordinates, or screen coordinates? A lot more information is needed here. \$\endgroup\$ Sep 24, 2014 at 8:39
  • \$\begingroup\$ Read its color. Question is updated. Pixel's mood is great. \$\endgroup\$
    – topright
    Sep 24, 2014 at 8:54

1 Answer 1


I'm not finding any way to do this within the cocos2d framework, so if someone can do that it would probably be a better answer.

However, cc.Texture2D does have a getHtmlElementObj() function. Now, this function can return either an image element or a canvas element. If it returns an image, you need to make a canvas from it as shown in this answer:

var canvas = $('<canvas/>')[0];
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);

Once you have a canvas element, you should be able to get a pixel's color as described in this answer:

var data = canvas.getContext('2d').getImageData(x, y, 1, 1).data;
var color = new Color([data[0], data[1], data[2]]);

And just for good measure, here is how to test if getHtmlElementObj() returns an image:

function isImage(i) {
    return i instanceof HTMLImageElement;

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .