Added dragging of circle

This commit is contained in:
Stephan Egli 2025-01-09 19:24:42 +01:00
parent 777d27a5d7
commit c61efa7b52
2 changed files with 68 additions and 7 deletions

View File

@ -47,4 +47,4 @@ export function drawAllShapesOnCanvas(canvas, shapesArray) {
ctx.fillStyle = triangle.color || "black";
ctx.fill();
}

View File

@ -2,13 +2,16 @@
import { initRepo, addCircle, addTriangle, moveShape } from "./docManager.js"
import { drawAllShapesOnCanvas } from "./canvasManager.js"
let isDragging = false;
let selectedShapeId = null;
let offsetX = 0;
let offsetY = 0;
const canvas = document.getElementById("shapesCanvas")
// 1. Init the repo & document handle
const handle = initRepo()
// TODO is the whenReady() needed ?
// await handle.whenReady()
await handle.whenReady()
// 2. Subscribe so we can re-render whenever doc changes
// Listen for 'change' events
@ -25,11 +28,69 @@ const addTriangleButton = document.getElementById("addTriangleButton");
addCircleButton.addEventListener("click", () => {
// z. B. zufällige Position/Radius
addCircle(100, 100, 30);
// TODO render();
});
addTriangleButton.addEventListener("click", () => {
// z. B. zufällige Koordinaten
addTriangle( 200, 200, 220, 220, 180, 220);
// TODO render();
});
});
// Mousedown: Prüfen, ob wir auf ein Shape klicken
canvas.addEventListener("mousedown", (e) => {
const { offsetX: mouseX, offsetY: mouseY } = e;
// 1. Shape unter Maus suchen
const clickedShape = getShapeAtCoordinates(mouseX, mouseY);
console.log("Clicked shape:",clickedShape)
if (clickedShape) {
isDragging = true;
selectedShapeId = clickedShape.id;
// Damit das Shape unter dem Mauszeiger bleibt, merken wir uns den "Offset"
offsetX = mouseX - clickedShape.x;
offsetY = mouseY - clickedShape.y;
}
});
// Mousemove: Shape verschieben, sofern dragging aktiv ist
canvas.addEventListener("mousemove", (e) => {
if (!isDragging || selectedShapeId === null) return;
const { offsetX: mouseX, offsetY: mouseY } = e;
// Neue Koordinaten berechnen
const newX = mouseX - offsetX;
const newY = mouseY - offsetY;
// Achtung: Hier könnte man Throttling/RAF implementieren
moveShape(selectedShapeId, newX, newY);
});
// Mouseup: Dragging beenden
canvas.addEventListener("mouseup", () => {
isDragging = false;
selectedShapeId = null;
});
/**
* Gibt das Shape zurück, das die Koordinaten (mx, my) enthält/berührt
* (Vereinfacht: nur für Kreise)
*/
function getShapeAtCoordinates(mx, my) {
const doc = handle.docSync()
console.log("DOC IN GETSHAPEATCOORDIATES:",doc)
// Hier nur ein einfacher Loop durch alle Kreise
for (let shape of doc.shapes) {
if (shape.type === "circle") {
const dist = Math.sqrt((mx - shape.x) ** 2 + (my - shape.y) ** 2);
console.log("calculated distance and radius:",dist,shape.radius)
if (dist <= shape.radius) {
console.log("Found shape:",shape)
return shape;
}
}
// ggf. erweitern für Dreiecke oder andere Formen
}
return null;
}