跳到主要内容

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

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

// 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');
});