简体   繁体   中英

KineticJS which layer clicked?

I use KineticJS add images to layers. I need to know which layer clicked.

This is jsfiddle: http://jsfiddle.net/yvp79ryf/1/

If i clicked first image just need get alert clicked is first layers otherwise second layer

HTML

<div id="container"></div>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.4.3.min.js"></script>
<script defer="defer">

JavaScript

  var stage = new Kinetic.Stage({
    container: 'container',
    width: 578,
    height: 200
  });


  var layer = new Kinetic.Layer();
  var imageObj = new Image();
  imageObj.onload = function() {
  var yoda = new Kinetic.Image({
      x: 140,
      y: stage.getHeight() / 2 - 59,
      image: imageObj,
      width: 106,
      height: 118
    });

    layer.add(yoda);
    stage.add(layer);

  };
  imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/yoda.jpg';



  var layer2 = new Kinetic.Layer();
  var imageObj2 = new Image();
  imageObj2.onload = function() {
  var filteredYoda = new Kinetic.Image({
      x: 280,
      y: stage.getHeight() / 2 - 59,
      image: imageObj2,
      width: 106,
      height: 118
    });

    layer2.add(filteredYoda);
    stage.add(layer2);
  };
  imageObj2.src = 'http://demo-stable-ofbiz.apache.org/images/products/GZ-1000/small.png';

If you click on an image, you can use .getLayer() to get a reference to the layer that your clicked image is on.

stage.on('click', function(e) {
    console.log('layer:',e.target.getLayer().id());
});

KineticJS does not listen for clicks on the empty part of a layer. Therefore, if you click on an empty part of the stage then you cannot tell which layer was clicked. But since since layer2 is above layer then if you click on the empty part of the stage then you're always clicking on the top layer (layer2).

You need to set id to layers to identify them.

var layer = new Kinetic.Layer({id:1});
var layer2 = new Kinetic.Layer({id:2});

Add click event handler on stage

stage.on('click', function(e) {
    if(e.targetNode.parent.attrs.id == 1){
        alert('first layer');
    }else{
        alert('second layer');
    }
});

You can check layer id through the descendants

e is MouseEvent object.

e.targetNode is Kinetic.Image

e.targetNode.parent is Kinetic.Layer

e.targetNode.parent.attrs.id is id of Kinetic.Layer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM