跳到主要内容

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

// add click listeners
circle.on('click.event1', function () {
  alert('first click listener');
});

circle.on('click.event2', function () {
  alert('second click listener');
});

layer.add(circle);

// add buttons to remove listeners
const button1 = document.createElement('button');
button1.innerHTML = 'Remove first listener';
button1.style.position = 'absolute';
button1.style.top = '0';
button1.style.left = '0';
button1.onclick = function() {
  circle.off('click.event1');
};
document.getElementById('container').appendChild(button1);

const button2 = document.createElement('button');
button2.innerHTML = 'Remove second listener';
button2.style.position = 'absolute';
button2.style.top = '30px';
button2.style.left = '0';
button2.onclick = function() {
  circle.off('click.event2');
};
document.getElementById('container').appendChild(button2);