Skip to main content

HTML5 Canvas Remove Event Listener with Konva

To remove an event listener with Konva, we can use the off() method of a shape object which requires an event type such as click or mousedown.

Instructions: Click on the circle to see an alert triggered from the onclick event binding. Remove the event listener by clicking on the button and again click on the circle to observe that the event binding has been removed.

import Konva from 'konva';

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

const layer = new Konva.Layer();
stage.add(layer);

const circle = new Konva.Circle({
  x: stage.width() / 2,
  y: stage.height() / 2,
  radius: 70,
  fill: 'red',
  stroke: 'black',
  strokeWidth: 4,
});

// add click listener
circle.on('click', function () {
  alert('you clicked the circle');
});

layer.add(circle);

// add button to remove listener
const button = document.createElement('button');
button.style.position = 'absolute';
button.style.top = '10px';
button.style.left = '10px';
button.innerHTML = 'Remove click listener';
document.body.appendChild(button);
button.addEventListener('click', () => {
  // remove click listener
  circle.off('click');
});