Search code examples
javascripthtml5-canvaskineticjs

Getting pixel data from Kinetic JS Image


I am using Kinetic JS to display an image, and I would like to implement a magnify function.

So basically I would like to copy the area of the image which the mouse pointer is hovering over, scale it, and display it elsewhere on the screen.

You can grab HTML5 canvas pixel data with the canvas context.getImageData() function, but is there another way to do this in Kinetic JS or should I just try to get the image's underlying context and use the getImageData function?

Thanks


Solution

  • KineticJS just uses regular canvases so getImageData works. Just grab the context that you want.

    $('#canvas').mousemove(function(e) {
       var pos = findPos(this);
       var x = e.pageX - pos.x;
       var y = e.pageY - pos.y;
       var coord = "x=" + x + ", y=" + y;
       var c = this.getContext('2d');
       var p = c.getImageData(x, y, 1, 1).data; 
       var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
       //do something with the color
    });
    

    http://jsfiddle.net/7MMK2/26/

    However things get a bit tricker once you add more layers to the stage. You would have to loop through each canvas and grab the pixel.