HTML5 Canvas 通过 id 选择形状的教程
要使用 Konva 通过 id 选择形状,我们可以使用 find() 方法和 # 选择器。
find() 方法始终返回一个元素数组,即使我们希望它返回单个元素。
如果只需要一个 元素,可以使用 findOne() 方法。
find() 方法适用于任何节点,包括舞台、图层、组和形状。
说明: 点击“激活矩形”按钮通过 id 选择矩形并执行过渡。您也可以拖动和放置矩形。
- 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);
// 创建一个带有 id 的矩形
const rect = new Konva.Rect({
x: stage.width() / 2 - 25,
y: stage.height() / 2 - 25,
width: 50,
height: 50,
fill: 'red',
id: 'myRect',
draggable: true
});
layer.add(rect);
// 添加按钮
const button = document.createElement('button');
button.textContent = '激活矩形';
document.body.appendChild(button);
button.addEventListener('click', () => {
// 通过 id 查找矩形并对其进行动画处理
const rectangle = layer.findOne('#myRect');
rectangle.to({
duration: 1,
rotation: 360,
fill: 'blue',
easing: Konva.Easings.EaseInOut
});
});
import { Stage, Layer, Rect } from 'react-konva';
import { useRef, useState } from 'react';
const App = () => {
const [position, setPosition] = useState({
x: window.innerWidth / 2 - 25,
y: window.innerHeight / 2 - 25
});
const layerRef = useRef(null);
const handleClick = () => {
// 通过 id 查找矩形并对其进行动画处理
const rectangle = layerRef.current.findOne('#myRect');
rectangle.to({
duration: 1,
rotation: 360,
fill: 'blue',
easing: Konva.Easings.EaseInOut
});
};
const handleDragEnd = (e) => {
setPosition({
x: e.target.x(),
y: e.target.y()
});
};
return (
<div>
<button onClick={handleClick} style={{ marginBottom: '10px' }}>
激活矩形
</button>
<Stage width={window.innerWidth} height={window.innerHeight}>
<Layer ref={layerRef}>
<Rect
x={position.x}
y={position.y}
width={50}
height={50}
fill="red"
id="myRect"
draggable
onDragEnd={handleDragEnd}
/>
</Layer>
</Stage>
</div>
);
};
export default App;
<template>
<div>
<button @click="handleClick" style="margin-bottom: 10px">
激活矩形
</button>
<v-stage :config="stageSize">
<v-layer ref="layerRef">
<v-rect
:config="rectConfig"
@dragend="handleDragEnd"
/>
</v-layer>
</v-stage>
</div>
</template>
<script setup>
import { ref } from 'vue';
import Konva from 'konva';
const stageSize = {
width: window.innerWidth,
height: window.innerHeight
};
const position = ref({
x: window.innerWidth / 2 - 25,
y: window.innerHeight / 2 - 25
});
const rectConfig = ref({
x: position.value.x,
y: position.value.y,
width: 50,
height: 50,
fill: 'red',
id: 'myRect',
draggable: true
});
const layerRef = ref(null);
const handleClick = () => {
// 通过 id 查找矩形并对其进行动画处理
const rectangle = layerRef.value.getNode().findOne('#myRect');
rectangle.to({
duration: 1,
rotation: 360,
fill: 'blue',
easing: Konva.Easings.EaseInOut
});
};
const handleDragEnd = (e) => {
const newPos = e.target.position();
position.value = newPos;
rectConfig.value.x = newPos.x;
rectConfig.value.y = newPos.y;
};
</script>