HTML5 Canvas Listen or Don’t Listen to Events with Konva

To listen or don’t listen to events with Konva, we can set the listening
property of the config object to true or false when a shape is instantiated,
or we can set the listening property with the setListening() method.
Once we’ve set the listening property for one or more nodes, we’ll also need
to redraw the hit graph for each affected layer with the drawHit() method.

Instructions: Mouseover the oval to observe that the event handler is not executed.
Click on “Listen” to start listening for events and observe that the event handler is now executed.

Konva Listen_for_Events Demoview raw
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/[email protected]/konva.min.js"></script>
<meta charset="utf-8" />
<title>Konva Listen or Don’t Listen to Events Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #f0f0f0;
}

#buttons {
position: absolute;
top: 5px;
left: 10px;
}
</style>
</head>

<body>
<div id="container"></div>
<div id="buttons">
<button id="listen">Listen</button>
<button id="dontListen">Dont' Listen</button>
</div>
<script>
function writeMessage(message) {
text.text(message);
}

var stage = new Konva.Stage({
container: 'container',
width: window.innerWidth,
height: window.innerHeight,
});

var layer = new Konva.Layer();

var text = new Konva.Text({
x: 70,
y: 10,
fontFamily: 'Calibri',
fontSize: 24,
text: '',
fill: 'black',
});

var oval = new Konva.Circle({
x: stage.width() / 2,
y: stage.height() / 2,
radius: 50,
scaleX: 2,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
strokeScaleEnabled: false,
listening: false,
});

oval.on('mouseover', function () {
writeMessage('Mouseover oval');
});
oval.on('mouseout', function () {
writeMessage('');
});

layer.add(oval);
layer.add(text);
stage.add(layer);

document.getElementById('listen').addEventListener(
'click',
function () {
oval.listening(true);
layer.drawHit();
},
false
);

document.getElementById('dontListen').addEventListener(
'click',
function () {
oval.listening(false);
layer.drawHit();
},
false
);
</script>
</body>
</html>
Enjoying Konva? Please consider to support the project.