我使用 React-Konva 并尝试制作一个具有可扩展性的有限大小的工作空间(如在 photoshop 中)。因此,当您缩放工作区窗口时,它会开始在屏幕上占用越来越多的空间。但是写完函数后,缩放的流畅感就没有了
这里或多或少是工作代码:
import React, { useRef, useState } from 'react';
import { Stage, Layer, Rect } from 'react-konva';
const App = () => {
const [zoom, setZoom] = useState(1);
const stageRef = useRef(null);
const stageWidth = 500;
const stageHeight = 500;
const handleScale = (event: Konva.KonvaEventObject<WheelEvent>) => {
const stage = stageRef.current
if (!stage) {
throw new Error('stage is undefined')
}
event.evt.preventDefault()
if (!event.evt.ctrlKey && !event.evt.altKey && !event.evt.metaKey) {
return
}
const oldScale = stage.scaleX() || 1
const pointer = stage.getPointerPosition()
if (!pointer) {
throw new Error('pointer is undefined')
}
const minScale = 0.1 // Minimal possible scaling
const maxScale = 10 // Maximum possible scaling
const scaleSpeed = 0.015 // Scaling speed
const newScale = Math.min(
Math.max(oldScale - event.evt.deltaY * scaleSpeed, minScale),
maxScale
)
stage.scale({ x: newScale, y: newScale })
const newPosition = {
x: pointer.x - ((pointer.x - stage.x()) / oldScale) * newScale,
y: pointer.y - ((pointer.y - stage.y()) / oldScale) * newScale
}
stage.position(newPosition)
stage.batchDraw()
setZoom(newScale)
}
return (
<Stage
width={stageWidth * zoom}
height={stageHeight * zoom}
ref={stageRef}
onWheel={handleScale}
>
<Layer>
{/* Ваши фигуры */}
<Rect x={50} y={50} width={100} height={100} fill="red" draggable />
</Layer>
</Stage>
);
};
export default App;
是否有可能实现一个有限大小的工作区域,并能够在屏幕上增加或减少它的大小?如果是这样,怎么办?