Spaces:
No application file
No application file
File size: 16,541 Bytes
91c8a81 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 | 'use client'
import React, { useEffect, useLayoutEffect, useRef, useState } from "react";
import rough from "roughjs/bundled/rough.esm";
import DrawingBoard from './DrawingBoard';
import {
createElement,
drawElement,
} from './element-utils';
import { createMouseHandlers } from './handleMouse';
const captureRegionToPNG = (canvas, region, elements, scale, panOffset, scaleOffset) => {
const tempCanvas = document.createElement('canvas');
const ctx = tempCanvas.getContext('2d');
const width = (region.bounds.x2 - region.bounds.x1);
const height = (region.bounds.y2 - region.bounds.y1);
tempCanvas.width = width * scale;
tempCanvas.height = height * scale;
// Fill white background
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, tempCanvas.width, tempCanvas.height);
ctx.save();
ctx.scale(scale, scale);
ctx.translate(-region.bounds.x1, -region.bounds.y1);
const mainCanvas = canvas.getContext('2d');
const roughCanvas = rough.canvas(tempCanvas);
ctx.translate(panOffset.x, panOffset.y);
elements.forEach(element => {
if (isElementInRegion(element, region.bounds)) {
drawElement(roughCanvas, ctx, element);
}
});
ctx.restore();
return tempCanvas.toDataURL('image/png');
};
// Update the downloadRegionImage function:
const downloadRegionImage = (dataUrl, regionId) => {
const link = document.createElement('a');
link.href = dataUrl;
link.download = `region-${regionId}.png`; // Changed extension to .png
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
const isElementInRegion = (element, bounds) => {
if (element.type === 'pencil') {
return element.points.some(point =>
point.x >= bounds.x1 && point.x <= bounds.x2 &&
point.y >= bounds.y1 && point.y <= bounds.y2
);
} else {
const elementBounds = {
minX: Math.min(element.x1, element.x2),
maxX: Math.max(element.x1, element.x2),
minY: Math.min(element.y1, element.y2),
maxY: Math.max(element.y1, element.y2)
};
return !(elementBounds.maxX < bounds.x1 ||
elementBounds.minX > bounds.x2 ||
elementBounds.maxY < bounds.y1 ||
elementBounds.minY > bounds.y2);
}
};
const downloadAllRegions = (canvas, regions, elements, scale, panOffset, scaleOffset) => {
regions.forEach(region => {
const dataUrl = captureRegionToPNG(canvas, region, elements, scale, panOffset, scaleOffset);
downloadRegionImage(dataUrl, region.id);
});
};
const isPixelNonTransparent = (pixel) => {
return pixel.a > 0;
};
const isWithinBounds = (x, y, width, height) => {
return x >= 0 && x < width && y >= 0 && y < height;
};
const getPixel = (imageData, x, y) => {
const index = (y * imageData.width + x) * 4;
return imageData.data[index + 3] > 0; // Only check alpha channel for performance
};
// Use Set for faster lookups and Int32Array for coordinates
const floodFill = (imageData, startX, startY, visited) => {
const width = imageData.width;
const height = imageData.height;
const queue = new Int32Array(width * height * 2); // Pre-allocate queue
let queueStart = 0;
let queueEnd = 2;
queue[0] = startX;
queue[1] = startY;
const region = {
points: [],
minX: startX,
maxX: startX,
minY: startY,
maxY: startY
};
// Optimize bounds checking
const isWithinBounds = (x, y) => x >= 0 && x < width && y >= 0 && y < height;
// Pre-calculate neighbor offsets
const neighborOffsets = [
[1, 0], [-1, 0],
[0, 1], [0, -1],
[1, 1], [-1, -1],
[1, -1], [-1, 1]
];
while (queueStart < queueEnd) {
const x = queue[queueStart];
const y = queue[queueStart + 1];
queueStart += 2;
const key = `${x},${y}`;
if (visited.has(key)) continue;
if (!getPixel(imageData, x, y)) continue;
visited.add(key);
region.points.push({ x, y });
// Use Math.min/max for bounds tracking
region.minX = Math.min(region.minX, x);
region.maxX = Math.max(region.maxX, x);
region.minY = Math.min(region.minY, y);
region.maxY = Math.max(region.maxY, y);
// Check neighbors using pre-calculated offsets
for (const [dx, dy] of neighborOffsets) {
const nx = x + dx;
const ny = y + dy;
if (isWithinBounds(nx, ny) && !visited.has(`${nx},${ny}`)) {
queue[queueEnd] = nx;
queue[queueEnd + 1] = ny;
queueEnd += 2;
}
}
}
return region;
};
// Optimize distance calculation
const calculateRegionDistance = (region1, region2) => {
// Quick overlap check
const xOverlap = !(region1.maxX < region2.minX || region1.minX > region2.maxX);
const yOverlap = !(region1.maxY < region2.minY || region1.minY > region2.maxY);
if (xOverlap && yOverlap) return 0;
// Calculate distance only when necessary
const dx = !xOverlap ? Math.min(
Math.abs(region1.maxX - region2.minX),
Math.abs(region1.minX - region2.maxX)
) : 0;
const dy = !yOverlap ? Math.min(
Math.abs(region1.maxY - region2.minY),
Math.abs(region1.minY - region2.maxY)
) : 0;
return Math.sqrt(dx * dx + dy * dy);
};
// Optimize region merging using Set
const mergeRegions = (region1, region2) => ({
points: [...region1.points, ...region2.points],
minX: Math.min(region1.minX, region2.minX),
maxX: Math.max(region1.maxX, region2.maxX),
minY: Math.min(region1.minY, region2.minY),
maxY: Math.max(region1.maxY, region2.maxY)
});
const detectRegions = (canvas, elements, panOffset, scale, scaleOffset, minRegionSize = 100, groupingDistance = 80) => {
// Calculate bounds only once
const bounds = elements.reduce((acc, element) => {
if (element.type === 'pencil') {
element.points.forEach(point => {
acc.minX = Math.min(acc.minX, point.x);
acc.minY = Math.min(acc.minY, point.y);
acc.maxX = Math.max(acc.maxX, point.x);
acc.maxY = Math.max(acc.maxY, point.y);
});
} else {
const { x1, y1, x2, y2 } = element;
acc.minX = Math.min(acc.minX, x1, x2);
acc.minY = Math.min(acc.minY, y1, y2);
acc.maxX = Math.max(acc.maxX, x1, x2);
acc.maxY = Math.max(acc.maxY, y1, y2);
}
return acc;
}, { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity });
// Add padding
const padding = 100;
bounds.minX -= padding;
bounds.minY -= padding;
bounds.maxX += padding;
bounds.maxY += padding;
// Create optimized temporary canvas
const tempCanvas = document.createElement("canvas");
const width = Math.max(bounds.maxX - bounds.minX, canvas.width);
const height = Math.max(bounds.maxY - bounds.minY, canvas.height);
tempCanvas.width = width * scale;
tempCanvas.height = height * scale;
// Use OffscreenCanvas when available for better performance
const ctx = tempCanvas.getContext("2d", { alpha: true });
const roughCanvas = rough.canvas(tempCanvas);
// Draw elements with transformation
ctx.save();
ctx.translate(-bounds.minX * scale, -bounds.minY * scale);
ctx.scale(scale, scale);
elements.forEach(element => drawElement(roughCanvas, ctx, element));
ctx.restore();
// Process image data
const imageData = ctx.getImageData(0, 0, tempCanvas.width, tempCanvas.height);
const visited = new Set();
const initialRegions = [];
// Optimize pixel scanning with stride
const stride = 4; // Check every 4th pixel initially
for (let y = 0; y < tempCanvas.height; y += stride) {
for (let x = 0; x < tempCanvas.width; x += stride) {
const key = `${x},${y}`;
if (visited.has(key)) continue;
if (!getPixel(imageData, x, y)) continue;
const region = floodFill(imageData, x, y, visited);
if (region.points.length >= minRegionSize) {
// Transform coordinates back
const transformedRegion = {
...region,
minX: region.minX / scale + bounds.minX,
maxX: region.maxX / scale + bounds.minX,
minY: region.minY / scale + bounds.minY,
maxY: region.maxY / scale + bounds.minY,
points: region.points.map(point => ({
x: point.x / scale + bounds.minX,
y: point.y / scale + bounds.minY
}))
};
initialRegions.push(transformedRegion);
}
}
}
// Optimize region merging
const mergedRegions = [];
const used = new Set();
for (let i = 0; i < initialRegions.length; i++) {
if (used.has(i)) continue;
let currentRegion = initialRegions[i];
used.add(i);
let merged;
do {
merged = false;
for (let j = 0; j < initialRegions.length; j++) {
if (used.has(j)) continue;
const distance = calculateRegionDistance(currentRegion, initialRegions[j]);
if (distance <= groupingDistance) {
currentRegion = mergeRegions(currentRegion, initialRegions[j]);
used.add(j);
merged = true;
}
}
} while (merged);
mergedRegions.push(currentRegion);
}
// Return final regions
return mergedRegions.map((region, index) => ({
id: index + 1,
bounds: {
x1: region.minX,
y1: region.minY,
x2: region.maxX,
y2: region.maxY
},
elements: []
}));
};
const useHistory = initialState => {
const [index, setIndex] = useState(0);
const [history, setHistory] = useState([initialState]);
const setState = (action, overwrite = false) => {
const newState = typeof action === "function" ? action(history[index]) : action;
if (overwrite) {
const historyCopy = [...history];
historyCopy[index] = newState;
setHistory(historyCopy);
} else {
const updatedState = [...history].slice(0, index + 1);
setHistory([...updatedState, newState]);
setIndex(prevState => prevState + 1);
}
};
const undo = () => index > 0 && setIndex(prevState => prevState - 1);
const redo = () => index < history.length - 1 && setIndex(prevState => prevState + 1);
return [history[index], setState, undo, redo];
};
const usePressedKeys = () => {
const [pressedKeys, setPressedKeys] = useState(new Set());
useEffect(() => {
const handleKeyDown = event => {
setPressedKeys(prevKeys => new Set(prevKeys).add(event.key));
};
const handleKeyUp = event => {
setPressedKeys(prevKeys => {
const updatedKeys = new Set(prevKeys);
updatedKeys.delete(event.key);
return updatedKeys;
});
};
window.addEventListener("keydown", handleKeyDown);
window.addEventListener("keyup", handleKeyUp);
return () => {
window.removeEventListener("keydown", handleKeyDown);
window.removeEventListener("keyup", handleKeyUp);
};
}, []);
return pressedKeys;
};
const drawBoundingBoxes = (context, regions, scale) => {
context.save();
regions.forEach(region => {
const { bounds, id } = region;
// Set styling for bounding box
context.strokeStyle = "#FF5733"; // Custom color for better visibility
context.lineWidth = 1 / scale;
context.setLineDash([5 / scale, 5 / scale]); // Dotted lines for bounding box
// Draw bounding box
context.strokeRect(
bounds.x1,
bounds.y1,
bounds.x2 - bounds.x1,
bounds.y2 - bounds.y1
);
// Display region ID inside bounding box
context.setLineDash([]); // Reset line dash for text
context.font = `${16 / scale}px sans-serif`;
context.fillStyle = "#FF5733";
context.fillText(
`#${id}`,
bounds.x1 + 5 / scale,
bounds.y1 + 20 / scale
);
});
context.restore();
};
const App = () => {
const [elements, setElements, undo, redo] = useHistory([]);
const [action, setAction] = useState("none");
const [tool, setTool] = useState("rectangle");
const [selectedElement, setSelectedElement] = useState(null);
const [panOffset, setPanOffset] = useState({ x: 0, y: 0 });
const [startPanMousePosition, setStartPanMousePosition] = useState({ x: 0, y: 0 });
const [scale, setScale] = useState(1);
const [scaleOffset, setScaleOffset] = useState({ x: 0, y: 0 });
const [captureArea, setCaptureArea] = useState(null);
const [drawingRegions, setDrawingRegions] = useState([]);
const textAreaRef = useRef();
const pressedKeys = usePressedKeys();
const [pencilSize, setPencilSize] = useState(3);
const [isDrawing, setIsDrawing] = useState(false);
const handleDetectRegions = () => {
const canvas = document.getElementById("canvas");
if (!canvas) return;
const newRegions = detectRegions(canvas, elements, panOffset, scale, scaleOffset);
setDrawingRegions(newRegions);
// Notify user
if (newRegions.length > 0) {
console.log(`Phát hiện ${newRegions.length} vùng vẽ!`);
alert(`Đã phát hiện ${newRegions.length} vùng vẽ!`);
} else {
alert("Không phát hiện được vùng vẽ nào!");
}
};
useLayoutEffect(() => {
const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");
const roughCanvas = rough.canvas(canvas);
// Clear canvas for redrawing
context.clearRect(0, 0, canvas.width, canvas.height);
// Calculate scaled dimensions
const scaledWidth = canvas.width * scale;
const scaledHeight = canvas.height * scale;
const scaleOffsetX = (scaledWidth - canvas.width) / 2;
const scaleOffsetY = (scaledHeight - canvas.height) / 2;
setScaleOffset({ x: scaleOffsetX, y: scaleOffsetY });
context.save();
context.translate(panOffset.x * scale - scaleOffsetX, panOffset.y * scale - scaleOffsetY);
context.scale(scale, scale);
// Draw elements
elements.forEach(element => {
if (action === "writing" && selectedElement?.id === element.id) return;
drawElement(roughCanvas, context, element);
});
// Call drawBoundingBoxes to render detected regions
drawBoundingBoxes(context, drawingRegions, scale);
context.restore();
}, [elements, action, selectedElement, panOffset, scale, drawingRegions]);
useEffect(() => {
const undoRedoFunction = event => {
if ((event.metaKey || event.ctrlKey) && event.key === "z") {
if (event.shiftKey) {
redo();
} else {
undo();
}
}
};
document.addEventListener("keydown", undoRedoFunction);
return () => {
document.removeEventListener("keydown", undoRedoFunction);
};
}, [undo, redo]);
useEffect(() => {
const panOrZoomFunction = event => {
if (pressedKeys.has("Meta") || pressedKeys.has("Control")) {
onZoom(event.deltaY * -0.01);
} else {
setPanOffset(prevState => ({
x: prevState.x - event.deltaX,
y: prevState.y - event.deltaY,
}));
}
};
document.addEventListener("wheel", panOrZoomFunction);
return () => {
document.removeEventListener("wheel", panOrZoomFunction);
};
}, [pressedKeys]);
const onZoom = delta => {
setScale(prevState => Math.min(Math.max(prevState + delta, 0.1), 2));
};
const handleDownloadRegions = () => {
const canvas = document.getElementById("canvas");
if (!canvas || drawingRegions.length === 0) {
alert("Không có vùng vẽ nào để tải xuống!");
return;
}
downloadAllRegions(canvas, drawingRegions, elements, scale, panOffset, scaleOffset);
alert(`Đã tải xuống ${drawingRegions.length} vùng vẽ!`);
};
const {
handleMouseDown,
handleMouseMove,
handleMouseUp,
handleBlur
} = createMouseHandlers({
action,
setAction,
tool,
setTool,
elements,
setElements,
selectedElement,
setSelectedElement,
panOffset,
setPanOffset,
scale,
scaleOffset,
startPanMousePosition,
setStartPanMousePosition,
pressedKeys,
pencilSize,
setCaptureArea,
isDrawing,
setIsDrawing
});
return (
<DrawingBoard
tool={tool}
setTool={setTool}
elements={elements}
pencilSize={pencilSize}
setPencilSize={setPencilSize}
scale={scale}
setScale={setScale}
onZoom={onZoom}
undo={undo}
redo={redo}
action={action}
selectedElement={selectedElement}
panOffset={panOffset}
scaleOffset={scaleOffset}
handleMouseDown={handleMouseDown}
handleMouseMove={handleMouseMove}
handleMouseUp={handleMouseUp}
handleBlur={handleBlur}
handleDetectRegions={handleDetectRegions}
handleDownloadRegions={handleDownloadRegions}
/>
);
};
export default App; |