Line ${index + 1}: Start (${line.startX}, ${line.startY}), End (${line.endX}, ${line.endY}), Length: ${lengthInMeters.toFixed(2)} m
`;
})
.join('');
}
- // Calculate the length of a line
- function calculateLineLength(x1, y1, x2, y2) {
+ // Calculate the length of a line in meters
+ function calculateLineLengthInMeters(x1, y1, x2, y2) {
const dx = x2 - x1;
const dy = y2 - y1;
- return Math.sqrt(dx * dx + dy * dy);
+ const lengthInPixels = Math.sqrt(dx * dx + dy * dy);
+ return lengthInPixels * pixelToMeter;
}
- // Mouse event for drawing lines and points
+ // Mouse events
canvas.addEventListener('mousedown', (e) => {
- const clickX = snapToGrid(e.offsetX);
- const clickY = snapToGrid(e.offsetY);
-
- // Determine starting point for the line or point
- let startX, startY;
-
- if (!lastEndPoint) {
- // For the first line or point, set the start point anywhere
- startX = clickX;
- startY = clickY;
- firstStartPoint = { x: startX, y: startY }; // Save the start point of the first line
- } else if (clickX === lastEndPoint.x && clickY === lastEndPoint.y) {
- // For subsequent lines, start at the last endpoint
- startX = lastEndPoint.x;
- startY = lastEndPoint.y;
- } else {
- // Invalid starting point for a line
- return;
- }
-
- // Determine the endpoint
const endX = snapToGrid(e.offsetX);
const endY = snapToGrid(e.offsetY);
- // Check if the end point is valid:
- // - Must not be the same as the start point
- // - Must be a valid grid point or the start point of the first line
- const isValidEndPoint =
- (endX !== startX || endY !== startY) &&
- ((endX === firstStartPoint?.x && endY === firstStartPoint?.y) || true);
-
- if (!isValidEndPoint) {
- return;
- }
-
- // If it's a point, draw a point
- if (startX === endX && startY === endY) {
- drawPoint(startX, startY);
- } else {
- // Otherwise, draw the line
+ if (startX !== null && startY !== null) {
+ // Draw the final line
drawLine(startX, startY, endX, endY);
+
+ // Capture the line details
+ capturedLines.push({ startX, startY, endX, endY });
+ updateLineLog();
}
- // Update the last endpoint
- lastEndPoint = { x: endX, y: endY };
-
- // Capture the line or point details
- capturedLines.push({ startX, startY, endX, endY });
- updateLineLog();
+ // Update the start position for the next line
+ startX = endX;
+ startY = endY;
});
- // Function to draw a line
+ // Drawing functions
function drawLine(x1, y1, x2, y2) {
ctx.beginPath();
- ctx.strokeStyle = "#000000"; // Black lines
- ctx.lineWidth = 2;
+ ctx.strokeStyle = "#000000"; // Black color for lines
+ ctx.lineWidth = 2; // Thicker lines
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
}
- // Function to draw a point
- function drawPoint(x, y) {
- ctx.beginPath();
- ctx.fillStyle = "#000000"; // Black point
- ctx.arc(x, y, 3, 0, 2 * Math.PI); // Draw a small circle for the point
- ctx.fill();
- }
-
- // Initialize the canvas
- drawGrid();
+ // Initialize canvas
+ drawGrid(); // Draw the grid when the page loads
\ No newline at end of file