HTML5 Canvas 拖拽舞台
要使用 Konva 拖拽舞台,我们可以在实例化分组时将配置对象的 draggable
属性设置为 true
,或者使用 draggable()
方法。
与其他节点(如形状、组和图层)的拖拽方式不同,我们可以通过拖拽舞台的任何部分来拖动整个舞台。
- Vanilla
- React
- Vue
import Konva from 'konva'; const stage = new Konva.Stage({ container: 'container', width: window.innerWidth, height: window.innerHeight, draggable: true }); 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 }); // 创建文本 const text = new Konva.Text({ x: 10, y: 10, text: '可以随意拖拽舞台', fontSize: 20, fontFamily: 'Calibri', fill: 'black' }); layer.add(circle); layer.add(text);
import { Stage, Layer, Circle, Text } from 'react-konva'; const App = () => { return ( <Stage width={window.innerWidth} height={window.innerHeight} draggable > <Layer> <Circle x={window.innerWidth / 2} y={window.innerHeight / 2} radius={70} fill="red" stroke="black" strokeWidth={4} /> <Text x={10} y={10} text="可以随意拖拽舞台" fontSize={20} fontFamily="Calibri" fill="black" /> </Layer> </Stage> ); }; export default App;
<template> <v-stage :config="stageConfig"> <v-layer> <v-circle :config="circleConfig" /> <v-text :config="textConfig" /> </v-layer> </v-stage> </template> <script setup> const stageConfig = { width: window.innerWidth, height: window.innerHeight, draggable: true }; const circleConfig = { x: window.innerWidth / 2, y: window.innerHeight / 2, radius: 70, fill: 'red', stroke: 'black', strokeWidth: 4 }; const textConfig = { x: 10, y: 10, text: '可以随意拖拽舞台', fontSize: 20, fontFamily: 'Calibri', fill: 'black' }; </script>