KineticJS event not fired for child of a grouped layer

℡╲_俬逩灬. 提交于 2019-12-24 09:34:34

问题


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

  • When I use a simple hierarchy, as shown below (Test 0) the event can be successfully triggered.
  • However when adding the image in a more complex hierarchy (Test 1) the event is not triggered.

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.


回答1:


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.



来源:https://stackoverflow.com/questions/17453342/kineticjs-event-not-fired-for-child-of-a-grouped-layer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!