HTML5 Canvas 移除 Konva 事件监听器
要使用 Konva 移除事件监听器,我们可以使用形状对象的 off() 方法,该方法需要一个事件类型,例如 click 或 mousedown。
说明:点击圆圈以查看通过 onclick 事件绑定触发的警报。通过点击按钮移除事件监听器,然后再次点击圆圈以观察事件绑定已经被移除。
- Vanilla
- React
- Vue
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');
});
import { Stage, Layer, Circle } from 'react-konva';
import { useState } from 'react';
const App = () => {
const [hasListener, setHasListener] = useState(true);
return (
<>
<button onClick={() => setHasListener(false)}>
移除点击监听器
</button>
<Stage width={window.innerWidth} height={window.innerHeight}>
<Layer>
<Circle
x={window.innerWidth / 2}
y={window.innerHeight / 2}
radius={70}
fill="red"
stroke="black"
strokeWidth={4}
onClick={hasListener ? () => alert('你点击了圆圈') : null}
/>
</Layer>
</Stage>
</>
);
};
export default App;
<template>
<div>
<button @click="removeListener">移除点击监听器</button>
<v-stage :config="stageSize">
<v-layer>
<!--
注意:Vue-Konva 不支持像 @click="condition ? handler : null" 这样的条件事件绑定
相反,我们保持点击处理程序的附加状态,并在处理程序函数内部检查条件
-->
<v-circle
:config="circleConfig"
@click="handleClick"
/>
</v-layer>
</v-stage>
</div>
</template>
<script setup>
import { ref } from 'vue';
const hasListener = ref(true);
const stageSize = {
width: window.innerWidth,
height: window.innerHeight
};
const circleConfig = {
x: window.innerWidth / 2,
y: window.innerHeight / 2,
radius: 70,
fill: 'red',
stroke: 'black',
strokeWidth: 4
};
const handleClick = () => {
if (hasListener.value) {
alert('你点击了圆圈');
}
};
const removeListener = () => {
hasListener.value = false;
};
</script>