javascriptjquerykineticjsjquery-events

KineticJS event not fired for child of a grouped layer


I am trying to add a click event to an image (Kinetic.Image) I am adding to a KineticJS stage.

Hierarchy

I have created a Fiddle that demonstrates both hierarchy situations.

// The canvas container for the stage
var container = $("#container").html("");

// Create the stage
var stage = new Kinetic.Stage({
    container: container.attr("id"),
    width: container.width(),
    height: container.height()
}); 

// Load image
var img = new Image();
img.onload = function() {

    // Dimensions of the image
    var w = this.width;
    var h = this.height;

    // The base layer
    var baseLayer = new Kinetic.Layer({
        width: w,
        height: h
    });

    // The group
    var group = new Kinetic.Group();

    // The asset layer
    var assetLayer = new Kinetic.Layer({
        width: w,
        height: h
    });

    // The kinetic image element
    var element = new Kinetic.Image({
        image: this,
        width: w,
        height: h
    });

    // Event when image is clicked
    element.on("click", function() { alert("Image clicked"); });

    // Build hierarchy
    assetLayer.add(element);
    group.add(assetLayer);
    baseLayer.add(group);
    stage.add(baseLayer);

    // Draw the stage
    stage.draw();
}

// Load image from URL
img.src = "http://www.html5canvastutorials.com/demos/assets/lion.png";       

I thought it maybe was related to event bubbling, and tried altering the listening property on the layer, but unfortunately this made no difference. Any advice would be greatly appreciated.


Solution

  • I have a feeling you can't group Kinetic.Layer, only Kinetic.Shape. See the wording at this tutorial: http://www.html5canvastutorials.com/kineticjs/html5-canvas-complex-shapes-using-groups-with-kineticjs/

    I changed 2 lines in your fiddle and I got it to work:

    Replace:

    assetLayer.add(element);
    group.add(assetLayer);
    

    With:

    //assetLayer.add(element);
    group.add(element);
    

    Voila! The alert fires for 'click' on image.