0

everybody,

I need to get the color of my image that is in my canvas object.

That's what I am doing right now:

_canvas.getContext('2d').getImageData(event.offsetX, event.offsetY, 1, 1).data;

This is what I want, but I have two images... one does'nt have color just de draw... the other is the same, but with color in each part... I want to show to the user.. the image without color... and when mouse hover... get the "back" color.

I hope you understand what I am trying to do here.

I am adding the image in this way:

loadIMLImage(context, "http://localhost:51413/img/image_color.png");
loadIMLImage(context, "http://localhost:51413/img/image.png");

and this is the method

   function loadIMLImage(context, source) {
       base_image = new Image();
       base_image.src = source;
       base_image.onload = function () {
           context.drawImage(base_image, 100, 100);
       }
       return base_image;
   }

Any help will be appreciated.

Hugo S. Mendes
  • 1,076
  • 11
  • 23

1 Answers1

0

For this scenario you can do the following:

  • Draw the back-buffer image first
  • Extract the pixel buffer for re-use (store globally)
  • Draw the main image
  • When getting the coordinates check with the already extracted buffer

Example assuming you have the images loaded:

var context = _canvas.getContext('2d'),
    buffer;

...image loaded and ready here...

// draw back image
context.drawImage(backImage, 0, 0);

// extract buffer right away
buffer = context.getImageData(0, 0, _canvas.width, _canvas.height).data;

// draw main image on top (clear canvas first if smaller)
context.drawImage(mainImage, 0, 0);

The buffer and canvas is now ready. The buffer you have is a copy and won't be affected by the changes after it has been extracted so we are safe against changes.

Now for each event call with event as argument:

function getPixel(e) {

    var rect = _canvas.getBoundingClientRect(), // get canvas abs. position
        x = e.clientX - rect.left,              // adjust mouse positions
        y = e.clientY - rect.top,
        p = (y * _canvas.width + x) * 4;        // calc offset in buffer

    return {
        r: buffer[p],
        g: buffer[p+1],
        b: buffer[p+2],
        a: buffer[p+3]
    };
}

Not only does this works faster as you don't need to extract part of the buffer over the CPU each time, but you don't need to create a second canvas either which would be the optional way of doing it.

Hope this helps!