I'm looking for a way to obtain ID (123 in the code below) of a Konva Label ("Hello World!" in the code below) from Konva's 'dblclick' event.
I could obtain ID (321 in the code below) of a Konva Image (Konva's LOGO "K" in the code below) from both of Konva's 'dblclick' and 'dragmove' events. Also I could obtain the ID (123 in the code below) of the Konva Label ("Hello World!") from 'dragmove' event; however I couldn't obtain the ID (123 in the code below) of the Konva Label ("Hello World!") from Konva's 'dblclick' event.
My code:
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/[email protected]/konva.min.js"></script>
<meta charset="utf-8" />
</head>
<body>
<span id="container"></span>
</body>
<script>
//Konva Stage
var stage = new Konva.Stage({
container: 'container',
width: window.innerWidth,
height: window.innerHeight,
});
//Konva Layer
var layer = new Konva.Layer();
stage.add(layer);
//Konva Image
var imageObj = new Image();
imageObj.src = 'https://raw.githubusercontent.com/konvajs/konvajs.github.io/master/apple-touch-icon-180x180.png';
imageObj.addEventListener('load', function() {
var kImage = new Konva.Image({
x: window.innerWidth*2.5/10,
y: window.innerHeight*1/10,
image: imageObj,
id: 321,
draggable: true,
});
layer.add(kImage);
layer.draw();
});
//Konva Label
WordLabel = new Konva.Label({
x: window.innerWidth*3/10,
y: window.innerHeight*4/10,
opacity: 0.75,
draggable: true,
fill: 'green',
id: 123,
});
//Konva Tag
WordLabel.add(
new Konva.Tag({
fill: 'green',
})
);
//Konva Text
WordLabel.add(
new Konva.Text({
text: 'Hello World!',
fontFamily: 'Calibri',
fontSize: 18,
padding: 5,
fill: 'white',
strokeWidth: 0,
})
);
layer.add(WordLabel);
layer.draw();
//Konva dragstart event
stage.on('dragstart', function(e) {
console.log('ID (dragstart) = ' + parseInt(e.target.id()));
});
//Konva dblclick event
stage.on('dblclick dbltap', function (e) {
console.log('ID (dblclick) = ' +parseInt(e.target.id()));
});
</script>
</html>
If you look at the e.target object you can see that it is the text node rather than the label node that received the click.
Use e.target.findAncestors (see shape API) to get and iterate the shape hierarchy looking for an ancestor shape with the ID attribute you seek.
Working snippet below.