HTML5 Canvas 简单拖拽边界教程
要限制使用 Konva 拖拽和放置的形状的运动,我们可以使用 dragmove 事件并在其中重写拖拽和放置位置。
这个事件可以用于以各种方式约束拖拽和放置的运动,例如限制水平方向、垂直方向、对角线或径向的运动,甚至可以限制节点保持在一个框、圆或任何其他路径内。
shape.on('dragmove', () => {
// 锁定形状在 x 轴上的位置
// 保持 y 位置不变
shape.x(0);
});
提示:你可以使用 shape.absolutePosition() 方法获取/设置节点的绝对位置,而不是相对的 x 和 y。
说明: 拖拽水平文本并观察它只能水平移动。拖拽垂直文本并观察它只能垂直移动。**
- 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 horizontalText = new Konva.Text({
x: 50,
y: 50,
text: '水平拖拽我',
fontSize: 16,
draggable: true,
fill: 'black',
});
horizontalText.on('dragmove', function () {
// 仅水平拖拽
this.y(50);
});
const verticalText = new Konva.Text({
x: 200,
y: 50,
text: '垂直拖拽我',
fontSize: 16,
draggable: true,
fill: 'black',
});
verticalText.on('dragmove', function () {
// 仅垂直拖拽
this.x(200);
});
layer.add(horizontalText);
layer.add(verticalText);
import { Stage, Layer, Text } from 'react-konva';
import { useState } from 'react';
const App = () => {
const [horizontalPosition, setHorizontalPosition] = useState({ x: 50, y: 50 });
const [verticalPosition, setVerticalPosition] = useState({ x: 200, y: 50 });
const handleHorizontalDragMove = (e) => {
setHorizontalPosition({ x: e.target.x(), y: 50 });
};
const handleVerticalDragMove = (e) => {
setVerticalPosition({ x: 200, y: e.target.y() });
};
return (
<Stage width={window.innerWidth} height={window.innerHeight}>
<Layer>
<Text
x={horizontalPosition.x}
y={horizontalPosition.y}
text="Drag me horizontally"
fontSize={16}
draggable
fill="black"
onDragMove={handleHorizontalDragMove}
/>
<Text
x={verticalPosition.x}
y={verticalPosition.y}
text="Drag me vertically"
fontSize={16}
draggable
fill="black"
onDragMove={handleVerticalDragMove}
/>
</Layer>
</Stage>
);
};
export default App;
<template>
<v-stage :config="stageSize">
<v-layer>
<v-text
:config="horizontalTextConfig"
@dragmove="handleHorizontalDragMove"
/>
<v-text
:config="verticalTextConfig"
@dragmove="handleVerticalDragMove"
/>
</v-layer>
</v-stage>
</template>
<script setup>
const stageSize = {
width: window.innerWidth,
height: window.innerHeight
};
const horizontalTextConfig = {
x: 50,
y: 50,
text: '水平拖拽我',
fontSize: 16,
draggable: true,
fill: 'black'
};
const verticalTextConfig = {
x: 200,
y: 50,
text: '垂直拖拽我',
fontSize: 16,
draggable: true,
fill: 'black'
};
const handleHorizontalDragMove = (e) => {
e.target.y(50);
};
const handleVerticalDragMove = (e) => {
e.target.x(200);
};
</script>