From 834e19d9b87a057a9a4aeb43b63683ac6c4e4671 Mon Sep 17 00:00:00 2001 From: Stephan Egli Date: Fri, 10 Jan 2025 12:14:31 +0100 Subject: [PATCH] Added throttling with 16ms --- src/main.js | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/src/main.js b/src/main.js index 8f8be49..0d4b5fb 100644 --- a/src/main.js +++ b/src/main.js @@ -9,6 +9,18 @@ let offsetY = 0; const canvas = document.getElementById("shapesCanvas") +// Add throttle function at the top +function throttle(func, limit) { + let inThrottle; + return function(...args) { + if (!inThrottle) { + func.apply(this, args); + inThrottle = true; + setTimeout(() => inThrottle = false, limit); + } + } +} + // 1. Init the repo & document handle const handle = initRepo() await handle.whenReady() @@ -56,6 +68,11 @@ canvas.addEventListener("mousedown", (e) => { } }); +// Throttled version of moveShape +const throttledMoveShape = throttle((shapeId, x, y) => { + moveShape(shapeId, x, y); +}, 16); // 50ms throttle time (20 updates per second) + // Mousemove: Shape verschieben, sofern dragging aktiv ist canvas.addEventListener("mousemove", (e) => { if (!isDragging || selectedShapeId === null) return; @@ -66,8 +83,8 @@ canvas.addEventListener("mousemove", (e) => { const newX = mouseX - offsetX; const newY = mouseY - offsetY; - // Achtung: Hier könnte man Throttling/RAF implementieren - moveShape(selectedShapeId, newX, newY); + // Use throttled version instead + throttledMoveShape(selectedShapeId, newX, newY); }); // Mouseup: Dragging beenden