Skip to main content

HTML5 Canvas 移除 Konva 事件监听器

要使用 Konva 移除事件监听器,我们可以使用形状对象的 off() 方法,该方法需要一个事件类型,例如 click 或 mousedown。

说明:点击圆圈以查看通过 onclick 事件绑定触发的警报。通过点击按钮移除事件监听器,然后再次点击圆圈以观察事件绑定已经被移除。

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,
});

// 添加点击监听器
circle.on('click', function () {
  alert('你点击了圆圈');
});

layer.add(circle);

// 添加按钮以移除监听器
const button = document.createElement('button');
button.style.position = 'absolute';
button.style.top = '10px';
button.style.left = '10px';
button.innerHTML = '移除点击监听器';
document.body.appendChild(button);
button.addEventListener('click', () => {
  // 移除点击监听器
  circle.off('click');
});