Skip to main content

使用 Konva 按名称移除 HTML5 Canvas 事件监听器

要使用 Konva 按名称移除事件监听器,我们可以使用 on() 方法对事件类型进行命名空间处理,以便随后可以使用 off() 方法按相同命名空间移除事件监听器。

说明:点击圆形可查看两个不同的 onclick 事件绑定触发的两个警报。使用左侧的按钮移除事件监听器,然后再次点击圆形以观察新的 onclick 绑定。

注意:vue 和 react 不支持事件命名空间,因此我们没有为它们制作演示。我们也不建议在 Vue 和 React 中使用命名空间。

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.event1', function () {
  alert('第一个点击监听器');
});

circle.on('click.event2', function () {
  alert('第二个点击监听器');
});

layer.add(circle);

// 添加按钮以移除监听器
const button1 = document.createElement('button');
button1.innerHTML = '移除第一个监听器';
button1.style.position = 'absolute';
button1.style.top = '0';
button1.style.left = '0';
document.getElementById('container').appendChild(button1);

const button2 = document.createElement('button');
button2.innerHTML = '移除第二个监听器';
button2.style.position = 'absolute';
button2.style.top = '30px';
button2.style.left = '0';
document.getElementById('container').appendChild(button2);