HTML5 Canvas 特殊舞台事件 Konva
所有事件都是从形状开始的。因此,如果您在画布上的空白处单击,click 事件不会在 Layer 上触发,而是会在 Stage 对象上触发。
说明:单击空白处和形状以查看不同的事件行为。
- 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 text = new Konva.Text({
x: 10,
y: 10,
fontFamily: 'Calibri',
fontSize: 24,
text: '',
fill: 'black',
});
layer.add(text);
const circle = new Konva.Circle({
x: stage.width() / 2,
y: stage.height() / 2,
radius: 70,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
});
function writeMessage(message) {
text.text(message);
}
// 处理舞台点击
stage.on('click', function (e) {
if (e.target === stage) {
writeMessage('在舞台上点击');
return;
}
writeMessage('在 ' + e.target.name() + ' 上点击');
});
// 添加形状
circle.name('circle');
layer.add(circle);
import { Stage, Layer, Circle, Text } from 'react-konva';
import { useState } from 'react';
const App = () => {
const [message, setMessage] = useState('');
const handleStageClick = (e) => {
if (e.target === e.target.getStage()) {
setMessage('在舞台上点击');
return;
}
setMessage('在 ' + e.target.name() + ' 上点击');
};
return (
<Stage
width={window.innerWidth}
height={window.innerHeight}
onClick={handleStageClick}
>
<Layer>
<Text
x={10}
y={10}
fontFamily="Calibri"
fontSize={24}
text={message}
fill="black"
/>
<Circle
x={window.innerWidth / 2}
y={window.innerHeight / 2}
radius={70}
fill="red"
stroke="black"
strokeWidth={4}
name="circle"
/>
</Layer>
</Stage>
);
};
export default App;
<template>
<v-stage :config="stageSize" @click="handleStageClick">
<v-layer>
<v-text :config="textConfig" />
<v-circle :config="circleConfig" />
</v-layer>
</v-stage>
</template>
<script setup>
import { ref, computed } from 'vue';
const message = ref('');
const stageSize = {
width: window.innerWidth,
height: window.innerHeight
};
const textConfig = computed(() => ({
x: 10,
y: 10,
fontFamily: 'Calibri',
fontSize: 24,
text: message.value,
fill: 'black'
}));
const circleConfig = {
x: window.innerWidth / 2,
y: window.innerHeight / 2,
radius: 70,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
name: 'circle'
};
const handleStageClick = (e) => {
if (e.target === e.target.getStage()) {
message.value = '在舞台上点击';
return;
}
message.value = '在 ' + e.target.name() + ' 上点击';
};
</script>