HTML5 Canvas 事件代理与 Konva
要获取 Konva 中的事件目标,我们可以访问事件对象的 target
属性。这在使用事件代理时特别有用,在这种情况下我们可以将事件处理程序绑定到父节点,并监听其子节点上发生的事件。
说明:点击星星并观察图层事件绑定是否正确识别出被点击的形状。
- 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 star = new Konva.Star({ x: stage.width() / 2, y: stage.height() / 2, numPoints: 5, innerRadius: 40, outerRadius: 70, fill: 'red', stroke: 'black', strokeWidth: 4, }); layer.add(star); // 添加事件代理 layer.on('click', function (evt) { const shape = evt.target; text.text('点击的是 ' + shape.getClassName()); });
import { Stage, Layer, Star, Text } from 'react-konva'; import { useState } from 'react'; const App = () => { const [message, setMessage] = useState(''); const handleLayerClick = (e) => { const shape = e.target; setMessage('点击的是 ' + shape.getClassName()); }; return ( <Stage width={window.innerWidth} height={window.innerHeight}> <Layer onClick={handleLayerClick}> <Text x={10} y={10} fontFamily="Calibri" fontSize={24} text={message} fill="black" /> <Star x={window.innerWidth / 2} y={window.innerHeight / 2} numPoints={5} innerRadius={40} outerRadius={70} fill="red" stroke="black" strokeWidth={4} /> </Layer> </Stage> ); }; export default App;
<template> <v-stage :config="stageSize"> <v-layer @click="handleLayerClick"> <v-text :config="textConfig" /> <v-star :config="starConfig" /> </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 starConfig = { x: window.innerWidth / 2, y: window.innerHeight / 2, numPoints: 5, innerRadius: 40, outerRadius: 70, fill: 'red', stroke: 'black', strokeWidth: 4 }; const handleLayerClick = (e) => { const shape = e.target; message.value = '点击的是 ' + shape.getClassName(); }; </script>