HTML5 Canvas 拖放教程
要使用 Konva 实现形状的拖放,我们可以在实例化形状时将 draggable
属性设置为 true,或者使用 draggable()
方法。draggable()
方法自动为桌面和移动应用启用拖放功能。
要使用 Konva 检测拖放事件,我们可以使用 on()
方法将 dragstart
、dragmove
或 dragend
事件绑定到节点上。on()
方法需要一个事件类型和一个在事件发生时执行的函数。
- 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, draggable: true, }); // 添加光标样式 circle.on('mouseover', function () { document.body.style.cursor = 'pointer'; }); circle.on('mouseout', function () { document.body.style.cursor = 'default'; }); layer.add(circle);
import { Stage, Layer, Circle } from 'react-konva'; import { useState } from 'react'; const App = () => { const [position, setPosition] = useState({ x: window.innerWidth / 2, y: window.innerHeight / 2 }); return ( <Stage width={window.innerWidth} height={window.innerHeight}> <Layer> <Circle x={position.x} y={position.y} radius={70} fill="red" stroke="black" strokeWidth={4} draggable onMouseEnter={(e) => { document.body.style.cursor = 'pointer'; }} onMouseLeave={(e) => { document.body.style.cursor = 'default'; }} onDragEnd={(e) => { setPosition({ x: e.target.x(), y: e.target.y() }); }} /> </Layer> </Stage> ); }; export default App;
<template> <v-stage :config="stageSize"> <v-layer> <v-circle :config="circleConfig" @mouseenter="handleMouseEnter" @mouseleave="handleMouseLeave" /> </v-layer> </v-stage> </template> <script setup> 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, draggable: true }; const handleMouseEnter = () => { document.body.style.cursor = 'pointer'; }; const handleMouseLeave = () => { document.body.style.cursor = 'default'; }; </script>