HTML5 Canvas 通过 Konva 触发事件
要通过 Konva 触发事件,我们可以使用 fire() 方法。
这使我们能够以编程方式触发事件,如 click、mouseover、mousemove 等,也可以触发自定义事件,如 foo 和 bar。
注意:虽然可以使用自定义事件,但一般来说,使用内置交互事件(如
click、mouseover、mousemove等)会更好。自定义事件可能会使代码更难维护和调试。
- 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('customEvent', function (evt) {
alert('custom event fired');
});
// 添加按钮以触发自定义事件
const button = document.createElement('button');
button.innerHTML = '触发自定义事件';
button.style.position = 'absolute';
button.style.top = '10px';
button.style.left = '10px';
button.style.zIndex = '1';
document.body.appendChild(button);
button.addEventListener('click', () => {
// 触发自定义事件
circle.fire('customEvent', {
bubbles: true,
});
});
layer.add(circle);
import { Stage, Layer, Circle } from 'react-konva';
import { useRef } from 'react';
const App = () => {
const circleRef = useRef();
const handleCustomEvent = () => {
alert('custom event fired');
};
const fireCustomEvent = () => {
circleRef.current.fire('customevent', {
bubbles: true,
});
};
return (
<>
<button
onClick={fireCustomEvent}
style={{
position: 'absolute',
top: '10px',
left: '10px',
zIndex: 1
}}
>
触发自定义事件
</button>
<Stage width={window.innerWidth} height={window.innerHeight}>
<Layer>
<Circle
ref={circleRef}
x={window.innerWidth / 2}
y={window.innerHeight / 2}
radius={70}
fill="red"
stroke="black"
strokeWidth={4}
onCustomevent={handleCustomEvent}
/>
</Layer>
</Stage>
</>
);
};
export default App;
<template>
<div>
<button
@click="fireCustomEvent"
style="position: absolute; top: 10px; left: 10px; z-index: 1"
>
触发自定义事件
</button>
<v-stage :config="stageSize">
<v-layer>
<v-circle
ref="circleRef"
:config="circleConfig"
@customEvent="handleCustomEvent"
/>
</v-layer>
</v-stage>
</div>
</template>
<script setup>
import { ref } from 'vue';
const circleRef = ref(null);
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 handleCustomEvent = () => {
alert('custom event fired');
};
const fireCustomEvent = () => {
circleRef.value.getNode().fire('customevent', {
bubbles: true,
});
};
</script>