Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: fix mouse zoom issues #195

Closed
Closed
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 19 additions & 6 deletions frontend/src/canvas/CanvasContainer.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,24 @@ const CanvasContainer = (props) => {
};
}, [isDragging, canvasX, canvasY]);

// Zoom in/out ( into the cursor position )
let targetScale = canvasScale;
let targetX = canvasX;
let targetY = canvasY;

const animateZoom = () => {
if (Math.abs(canvasScale - targetScale) > 0.01) {
setCanvasScale(canvasScale + (targetScale - canvasScale) * 0.1);
setCanvasX(canvasX + (targetX - canvasX) * 0.1);
setCanvasY(canvasY + (targetY - canvasY) * 0.1);
requestAnimationFrame(animateZoom);
}
};

const zoom = (e) => {
// Get the cursor position within the canvas ( note the canvas can go outsid e the viewport )
const rect = props.canvasRef.current.getBoundingClientRect();
let cursorX = e.clientX - rect.left;
let cursorY = e.clientY - rect.top;

if (cursorX < 0) {
cursorX = 0;
} else if (cursorX > rect.width) {
Expand All @@ -81,7 +93,6 @@ const CanvasContainer = (props) => {
cursorY = rect.height;
}

// Calculate new left and top position to keep cursor over the same rect pos ition
let newScale = canvasScale * (1 + e.deltaY * -0.01);
if (newScale < minScale) {
newScale = minScale;
Expand All @@ -97,9 +108,11 @@ const CanvasContainer = (props) => {
const newPosX = canvasX - (newCursorX - cursorX);
const newPosY = canvasY - (newCursorY - cursorY);

setCanvasScale(newScale);
setCanvasX(newPosX);
setCanvasY(newPosY);
targetScale = newScale;
targetX = newPosX;
targetY = newPosY;

requestAnimationFrame(animateZoom);
};

useEffect(() => {
Expand Down