diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..71ba0a5 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,41 @@ +# Changelog + +All notable changes to this enhanced version of BoxBox will be documented in this file. + +## [Enhanced v1.0.0] - 2026-01-19 + +### Added +- **Aspect Ratio Memory**: Remembers last selected aspect ratio using localStorage +- **Selection Restoration**: Automatically restores previous selection when reopening +- **Recursive Node Traversal**: Finds source images through intermediate processing nodes +- **Better Error Handling**: Image error handler with console logging +- **Improved Coordinate Logic**: Refined the balance between frontend and backend scaling to ensure pixel-perfect crops. +- **Removed Annoying Popups**: Removed the "Immagine giΓ piccola" alert which interrupted the workflow. + +### Fixed +- **Image Loading**: Updated URL construction for ComfyUI compatibility +- **Backend Issues**: + - Fixed temp directory to use `folder_paths.get_temp_directory()` + - Fixed HTTP responses to return proper `web.json_response()` + - Sanitized filenames to prevent path separator issues +- **Coordinate Scaling**: Removed duplicate division, now handled correctly by backend +- **Intermediate Nodes**: Now works with Brightness, Blur, and other processing nodes +- **Coord Sync**: Reverted frontend division to allow the backend `BoxCrop` to handle scaling, preventing "double-scaling" errors. +- **UI Polish**: Silenced the "already small" alert popup. + +### Changed +- Removed annoying popup alert for small images +- Improved console logging throughout +- Aspect ratio now stays locked when drawing new selections + +### Technical Details +- Added `findImageInChain()` recursive function (max depth: 20) +- Updated `openRegionDialog()` to use chain traversal +- Added `api` module import for proper URL construction +- Enhanced scale endpoint with better filename extraction + +--- + +## [Original] - Before 2026-01-19 + +Original BoxBox implementation by mercu-lore. diff --git a/README.md b/README.md index 6a0421b..85d4809 100644 --- a/README.md +++ b/README.md @@ -1,423 +1,131 @@ -# BoxBox - Complete Image Region Processing Suite +# BoxBox - Enhanced Version -A comprehensive ComfyUI custom nodes package for selecting, cropping, resizing, and reinserting image regions with full metadata tracking. +ComfyUI custom node for interactive box/region selection with advanced features. +## π What's New in This Enhanced Version - ## π§ *Known Issue* +This is an improved fork of the original [BoxBox](https://github.com/mercu-lore/BoxBox) with several bug fixes and new features: -In some cases, when the ComfyUI window is too small or zoomed, the selection overlay may appear misaligned with the actual image. -A fix is currently in development. +### β Bug Fixes +1. **Fixed Image Loading After ComfyUI Update** + - Updated image URL construction to use ComfyUI's API helper + - Added proper filename encoding for special characters + - Improved error handling with fallback mechanisms -## π Overview +2. **Fixed Backend Issues** + - Corrected temp directory usage to use ComfyUI's proper temp folder + - Fixed HTTP response format (now returns proper `web.json_response`) + - Sanitized filenames to prevent path separator issues -BoxBox provides a complete workflow for working with specific image regions: +3. **Fixed Coordinate Scaling** + - Removed duplicate coordinate division (was happening in both frontend and backend) + - Coordinates now correctly convert from display space to original image space -1. **π¦ BoxSelector** - Interactive interface to select rectangular regions on images -2. **βοΈ BoxCrop** - Crop selected regions from original images -3. **π¦ BoxResize** - Resize cropped regions with preset aspect ratios for AI generation -4. **π¨ BoxReinsert** - Reinsert generated images back into original positions +4. **Fixed Intermediate Node Support** + - Added recursive node chain traversal to find source images + - Now works with processing nodes (Brightness, Blur, etc.) between LoadImage and BoxSelector + - Searches up to 20 levels deep in the node graph -## π― Available Nodes +5. **NumPy 2.0 Compatibility** + - Updated backend logic with explicit casting (`np.uint8`, `np.float32`) + - Fixed binary incompatibility issues in coordinate processing -### 1. BoxSelector (π¦ BoxSelector) +6. **ComfyUI v0.12.2+ (Modern API) Support** + - Re-engineered frontend to use the modern `window.comfyAPI` system + - Eliminated "Legacy API" deprecation warnings + - Improved dialog instantiation with robust fallback mechanisms -Interactive interface to select rectangular regions on images. +7. **Adaptive Window Scaling** + - Fixed coordinate misalignment when the browser window is resized + - System now dynamically calculates total scale (Server Scale * Browser CSS Scale) -#### Input -- `image` (IMAGE): Source image to select from +### π New Features -#### Output -- `image` (IMAGE): Original image (passthrough) -- `box_metadata` (STRING): JSON with selection coordinates +1. **Aspect Ratio Memory** + - Remembers your last selected aspect ratio using localStorage + - Persists across browser sessions and system restarts + - Keeps aspect ratio locked when drawing new selections -#### Features -- π±οΈ **Interactive Selection**: Click and drag to draw rectangles -- π **Side Coordinates**: Returns x1, x2, y1, y2 (not x, y, width, height) -- π **Clear Button**: Reset selection and start over -- π **Live Coordinates**: Shows selection position in real-time +2. **Selection Restoration** + - Automatically restores your previous selection when reopening the selector + - Shows the blue selection box from your last session + - Allows you to adjust or modify existing selections -#### Output JSON Format -```json -{ - "x1": 100, - "y1": 150, - "x2": 600, - "y2": 450, - "borderWidth": 3, - "borderPosition": "inside", - "displayScaleFactor": 1.0, - "selected": true -} -``` - -#### Advanced Features -- π **Aspect Ratio Locking**: Select from preset ratios or draw freely - - Presets: 1:1, 3:4, 5:8, 9:16, 9:21, 4:3, 3:2, 16:9, 21:9 - - Custom: Draw freely and get closest standard ratio -- π§ **Auto-Scale Large Images**: Images > 1024px automatically scaled down for smooth selection - - Scaling factor saved in metadata (`displayScaleFactor`) - - BoxCrop and BoxReinsert automatically correct coordinates - ---- - -### 2. BoxCrop (βοΈ BoxCrop) - -Crops images according to coordinates provided by BoxSelector. - -#### Input -- `image` (IMAGE): Image to crop -- `box_metadata` (STRING): JSON coordinates from BoxSelector (x1, x2, y1, y2) - - Connect directly from BoxSelector output - -#### Optional Input -- `fallback_mode` (COMBO): Behavior when no valid coordinates - - `use_full_image`: Return entire image (default) - - `return_zero`: Return black image - - `error`: Raise error - -#### Output -- `cropped_image` (IMAGE): Cropped region - -#### How It Works -1. Extracts x1, x2, y1, y2 from metadata -2. If `displayScaleFactor` is present (from large image auto-scaling): - - Divides coordinates by scale factor to convert from preview space to original image space -3. Normalizes coordinates (ensures x1 < x2, y1 < y2) -4. Clips to image boundaries -5. Crops the specified region - -#### Automatic Scale Correction -When BoxSelector uses auto-scale for large images (> 1024px), BoxCrop automatically: -- Detects the `displayScaleFactor` in metadata -- Converts preview-space coordinates back to original-image-space -- Ensures crops match the intended selection on the original image - ---- - -### 3. BoxResize (π¦ BoxResize) - -Resizes cropped regions with preset aspect ratios or custom dimensions, with full metadata tracking. - -#### Input -- `image` (IMAGE): Image to resize -- `size` (COMBO): Preset selection or "Custom" - - `1:1 Square 1024x1024` - - `3:4 Portrait 896x1152` - - `5:8 Portrait 832x1216` - - `9:16 Portrait 768x1344` - - `9:21 Portrait 640x1536` - - `4:3 Landscape 1152x896` - - `3:2 Landscape 1216x832` - - `16:9 Landscape 1344x768` - - `21:9 Landscape 1536x640` - - `Custom` (use width/height parameters) - -#### Optional Input -- `keep_aspect_ratio` (BOOLEAN): Maintain original aspect ratio (default: True) -- `interpolation_mode` (COMBO): Resize algorithm - - `bilinear` (default, faster) - - `bicubic` (higher quality) - - `nearest` (pixel-perfect) -- `width` (INT): Custom width [64-8192, step 8] (when size = "Custom") -- `height` (INT): Custom height [64-8192, step 8] (when size = "Custom") - -#### Output -- `image` (IMAGE): Resized image -- `resize_metadata` (STRING): JSON with resize information - -#### Output JSON Format -```json -{ - "original_width": 500, - "original_height": 300, - "resized_width": 1024, - "resized_height": 1024, - "scale_x": 2.048, - "scale_y": 3.413, - "size_preset": "1:1 Square 1024x1024", - "keep_aspect_ratio": true, - "interpolation_mode": "bilinear" -} -``` - ---- - -### 4. BoxReinsert (π¨ BoxReinsert) - -Reinserts generated images back into original positions using metadata. - -#### Input -- `original_image` (IMAGE): Original full-size image -- `generated_image` (IMAGE): Generated/processed image -- `box_metadata` (STRING): Selection coordinates from BoxSelector -- `resize_metadata` (STRING): Resize information from BoxResize - -#### Output -- `image` (IMAGE): Final image with generated content reinserted - -#### How It Works -1. Reads box_metadata for original selection position (x1, x2, y1, y2) -2. If `displayScaleFactor` is present (from large image auto-scaling): - - Divides coordinates by scale factor to convert from preview space to original image space -3. If resize_metadata is provided: - - Resizes generated_image back to crop dimensions - - Inserts at exact original position -4. If resize_metadata is empty: - - Inserts generated_image as-is (bypasses resize reversal) -5. Returns full image with processed region in place - -#### Automatic Scale Correction -When BoxSelector uses auto-scale for large images (> 1024px), BoxReinsert automatically: -- Detects the `displayScaleFactor` in metadata -- Converts preview-space coordinates back to original-image-space -- Reinserts the generated content at the correct position on the original image - -#### Flexible Workflow -- **With Resize**: Generated β De-resize β Reinsert -- **Without Resize**: Generated β Reinsert directly - ---- - -## π Complete Workflow - -### Standard AI Generation Workflow -``` -LoadImage - β -π¦ BoxSelector (select region interactively) - β box_metadata -βοΈ BoxCrop (extract region) - β cropped_image -π¦ BoxResize (prepare for AI, e.g., 1024x1024) - β resize_metadata -[AI Generation Model - SDXL, SD, etc.] - β generated_image -π¨ BoxReinsert (put back in original position) - β -Output: Final image with AI-generated region -``` - -### Direct Editing Workflow (skip resize) -``` -LoadImage - β -π¦ BoxSelector (select region) - β box_metadata -βοΈ BoxCrop (extract region) - β cropped_image -[Edit/Filter directly] - β edited_image -π¨ BoxReinsert (reinsert without resize) - β -Output: Final image -``` - ---- - -## π‘ Metadata System - -The metadata system ensures complete traceability: - -1. **BoxSelector Output**: `{"x1": ..., "y1": ..., "x2": ..., "y2": ..., "displayScaleFactor": ...}` - - Stores original selection coordinates - - Includes scale factor if image was auto-scaled (for large images > 1024px) - - borderWidth and borderPosition also included - -2. **BoxResize Output**: `{"original_width": ..., "resized_width": ..., "scale_x": ..., ...}` - - Tracks resize transformation for reversal - -3. **BoxCrop & BoxReinsert**: Automatically handle: - - If `displayScaleFactor` present: Convert coordinates from preview-space to original-image-space - - Use converted coordinates for accurate cropping and reinsertion - - Both nodes work seamlessly with auto-scaled selections - ---- - -## βοΈ Settings & Presets - -### BoxSelector -- **Border Width**: Fixed at 3px (built-in) -- **Border Position**: Fixed at "inside" (built-in) - -### BoxResize Presets -All presets optimize for AI generation models: -- **Square**: 1:1 ratio at 1024x1024 -- **Portrait**: Multiple heights (3:4, 5:8, 9:16, 9:21) -- **Landscape**: Multiple widths (4:3, 3:2, 16:9, 21:9) - -### BoxResize Interpolation -- `bilinear`: Fast, good quality (default) -- `bicubic`: Slower, higher quality -- `nearest`: Pixel-perfect, no smoothing - ---- - -## π Coordinate System - -All nodes use **side coordinates (x1, x2, y1, y2)**: -- `x1`: Left edge -- `x2`: Right edge -- `y1`: Top edge -- `y2`: Bottom edge - -This allows: -- Easy understanding of selected region -- Automatic validation (x1 < x2, y1 < y2) -- Direct use for cropping and reinsertion - ---- - -## π¨ User Interface - -### BoxSelector Dialog - -**Left Panel (Controls)** -- Image name -- Aspect Ratio selector (9 presets + Custom mode) -- Clear Selection button -- Selection coordinates display with live aspect ratio info -- Scale info display (when large image is auto-scaled) - -**Right Panel (Canvas)** -- Interactive image canvas -- Auto-scaled preview (for images > 1024px) -- Click + drag to draw rectangle -- Drag handles to resize -- Drag body to move -- Resize handles with smooth interaction - -**Features** -- π§ **Automatic Large Image Handling**: Seamlessly scales down for preview while maintaining accuracy -- π **Aspect Ratio Locking**: Lock to standard ratios or draw freely -- π **Live Feedback**: Real-time coordinate and ratio display +3. **Improved User Experience** + - Removed annoying popup alerts for small images + - Better console logging for debugging + - Image error handler with helpful messages --- ## π¦ Installation -1. Clone/copy the BoxBox folder to: - ``` - ComfyUI/custom_nodes/BoxBox/ - ``` +### Method 1: ComfyUI Manager (Recommended) +1. Open ComfyUI Manager +2. Search for "BoxBox Enhanced" +3. Click Install -2. Restart ComfyUI - -3. Nodes will appear in `image/box` category - ---- - -## π Requirements - -- **ComfyUI**: Latest version -- **Python**: 3.8+ -- **PyTorch**: >= 2.0.0 -- **Pillow (PIL)**: >= 8.0.0 -- **NumPy**: >= 1.20.0 -- **torch.nn.functional**: For interpolation (included with PyTorch) - -### requirements.txt -``` -torch>=2.0.0 -Pillow>=8.0.0 -numpy>=1.20.0 +### Method 2: Manual Installation +```bash +cd ComfyUI/custom_nodes +git clone https://github.com/Latentnaut/BoxBox.git ``` ---- - -## π Quick Start - -1. Add **LoadImage** node -2. Add **π¦ BoxSelector** node, connect image -3. Click "π¦ Select Box" button -4. Draw rectangle on image, click "β Confirm" -5. Add **βοΈ BoxCrop**, connect BoxSelector output -6. Add **π¦ BoxResize**, select preset (e.g., "1:1 Square 1024x1024") -7. Send to AI model or editor -8. Add **π¨ BoxReinsert**: - - Connect original image from step 1 - - Connect generated image from step 7 - - Connect box_metadata from step 4 output - - Connect resize_metadata from step 6 output -9. Execute graph β final image! +Then restart ComfyUI. --- -## π Troubleshooting +## π― Usage -### Selection Dialog Doesn't Open -- Make sure image is connected to BoxSelector -- Check browser console (F12) for errors -- Try reloading page (Ctrl+Shift+R) +1. Add a **LoadImage** node to your workflow +2. Add a **BoxSelector** node +3. Connect the image output to BoxSelector +4. Click **π¦ Select Box** button +5. Draw a rectangular selection on your image +6. Choose an aspect ratio (optional) +7. Click **β Confirm** +8. Use **BoxCrop** to crop the selected region +9. Use **BoxResize** to resize the cropped image -### Drawing Rectangle Doesn't Work -- Ensure you're clicking inside the image area -- Check that cursor shows crosshair -- Try refreshing the page +### Supported Workflows -### Resize Creates Black/Empty Image -- Check that `keep_aspect_ratio` is set correctly -- Verify image dimensions are valid -- Try different `interpolation_mode` - -### Reinsert Doesn't Work -- Verify all 4 inputs are connected (original_image, generated_image, box_metadata, resize_metadata) -- Check that metadata JSON is valid -- Ensure original_image and box_metadata match (same image used for selection) +β **Direct**: LoadImage β BoxSelector β BoxCrop +β **With Processing**: LoadImage β Brightness β BoxSelector β BoxCrop +β **Complex Chains**: LoadImage β Node1 β Node2 β ... β BoxSelector --- -## π Changelog +## π§ Nodes Included -### v1.1.0 (Current) -- β **Auto-Scale Large Images**: Images > 1024px automatically scaled in preview for smooth selection -- β **displayScaleFactor Metadata**: Scale factor saved in metadata for accurate coordinate conversion -- β **Aspect Ratio Locking**: 9 preset aspect ratios + custom free drawing mode -- β **Smart Coordinate Correction**: BoxCrop and BoxReinsert auto-correct coordinates from scaled previews -- β **Live Aspect Ratio Display**: Shows closest standard ratio when drawing freely - -### v1.0.0 -- β BoxSelector with interactive region selection -- β BoxCrop with coordinate-based cropping -- β BoxResize with preset aspect ratios and custom sizes -- β BoxReinsert with flexible resize handling -- β Complete metadata tracking system -- β Optional resize bypass in BoxReinsert -- β Multiple interpolation modes +- **π¦ BoxSelector**: Interactive region selection with aspect ratio locking +- **βοΈ BoxCrop**: Crops image based on selected coordinates +- **π BoxResize**: Resizes images with aspect ratio preservation --- -## π Advanced Usage +## π Known Issues -### Chaining Multiple Regions -``` -Select Region 1 β Crop β Resize β AI Generate β Reinsert -Parallel with: -Select Region 2 β Crop β Resize β AI Generate β Reinsert -``` - -### Batch Processing -Use Reroute nodes to process same coordinates on multiple images. - -### Custom Aspect Ratios -Use BoxResize with "Custom" mode and specify exact width/height. +- Preview shows original image (not processed) when using intermediate nodes + - This is intentional for performance reasons + - Coordinates are still applied correctly to the processed image --- +## π Credits + +- **Original Author**: [mercu-lore](https://github.com/mercu-lore) +- **Enhanced Version**: Latentnaut +- **Improvements**: AI-assisted development with Claude + +--- ## π License -MIT +Same license as the original BoxBox project. --- -## π€ Support - -For issues, feature requests, or suggestions, please contact the developer. - ---- - -**Created for ComfyUI** - Transform your images with precision! π―βοΈπ¦π¨ - - +## π€ Contributing +Issues and pull requests are welcome! If you find bugs or have feature requests, please open an issue on GitHub. diff --git a/box_reinsert_node.py b/box_reinsert_node.py index fecf8ad..34b5bc0 100644 --- a/box_reinsert_node.py +++ b/box_reinsert_node.py @@ -107,38 +107,31 @@ class BoxReinsertNode: crop_width = box_x_end - box_x_start crop_height = box_y_end - box_y_start - # Converti immagini a PIL - original_np = (original_image[0].cpu().numpy() * 255).astype(np.uint8) + # Converti immagini a PIL con casting esplicito + # original_image es (B, H, W, C) + original_np = (original_image[0].detach().cpu().numpy() * 255).round().astype(np.uint8) original_pil = Image.fromarray(original_np) - generated_np = (generated_image[0].cpu().numpy() * 255).astype(np.uint8) + generated_np = (generated_image[0].detach().cpu().numpy() * 255).round().astype(np.uint8) generated_pil = Image.fromarray(generated_np) print(f"[BoxReinsertNode] Generated image size: {generated_pil.size}") print(f"[BoxReinsertNode] Target crop size: {crop_width}x{crop_height}") print(f"[BoxReinsertNode] Use resize: {use_resize}") - # Step 1: Ridimensiona solo se resize_metadata Γ¨ fornito + # Step 1: Ridimensiona if use_resize: - # Annulla il resize fatto da BoxResize - print(f"[BoxReinsertNode] Resizing generated image back to crop dimensions...") generated_resized = generated_pil.resize((crop_width, crop_height), Image.Resampling.LANCZOS) - print(f"[BoxReinsertNode] Generated image resized from {generated_pil.size} to {generated_resized.size}") else: - # Bypassa il resize e usa direttamente l'immagine generata generated_resized = generated_pil - print(f"[BoxReinsertNode] Bypassing resize, using generated image as-is") # Step 2: Rimetti nel punto originale - # Crea una copia dell'immagine originale final_image = original_pil.copy() - - # Incolla l'immagine generata nel punto corretto final_image.paste(generated_resized, (box_x_start, box_y_start)) - # Converti back a tensor - final_np = np.array(final_image).astype(np.float32) / 255.0 - final_tensor = torch.from_numpy(final_np).unsqueeze(0) + # Converti back a tensor con casting sicuro per NumPy 2.0 + final_np_array = np.array(final_image, dtype=np.float32) / 255.0 + final_tensor = torch.from_numpy(final_np_array).unsqueeze(0) # Assicurati che il tensor abbia le giuste dimensioni channels = original_image.shape[3] diff --git a/region_selector_node.py b/region_selector_node.py index 83a88ee..bfe868f 100644 --- a/region_selector_node.py +++ b/region_selector_node.py @@ -38,42 +38,77 @@ class RegionSelectorNode: return (image, self.last_metadata) -def scale_image_if_needed(filename, max_size=1024): - input_path = folder_paths.get_input_directory() - full_path = os.path.join(input_path, filename) +def scale_image_if_needed(filename, type="input", subfolder="", max_size=1024): + if type == "output": + base_dir = folder_paths.get_output_directory() + elif type == "temp": + base_dir = folder_paths.get_temp_directory() + else: + base_dir = folder_paths.get_input_directory() + + if subfolder: + full_path = os.path.join(base_dir, subfolder, filename) + else: + full_path = os.path.join(base_dir, filename) + if not os.path.exists(full_path): - return {"error": "file non trovato"} + return {"error": f"file not found: {full_path}"} with Image.open(full_path) as im: w, h = im.size + # Use comma as separator for filename, type, subfolder to assume default behaviour or backward compatibility + path_params = f"filename={filename}&type={type}" + if subfolder: + path_params += f"&subfolder={subfolder}" + if w <= max_size and h <= max_size: - return {"scaled": False, "path": f"view?filename={filename}&type=input"} + return {"scaled": False, "path": f"/view?{path_params}"} scale_factor = min(max_size / w, max_size / h) new_size = (int(w * scale_factor), int(h * scale_factor)) im_resized = im.resize(new_size, Image.Resampling.LANCZOS) - os.makedirs("temp", exist_ok=True) - scaled_name = f"scaled_{filename}" - scaled_path = os.path.join("temp", scaled_name) + # Use ComfyUI's temp folder + temp_dir = folder_paths.get_temp_directory() + os.makedirs(temp_dir, exist_ok=True) + + # Sanitize filename: replace path separators with underscores + safe_filename = filename.replace('/', '_').replace('\\', '_') + if subfolder: + safe_filename = f"{subfolder}_{safe_filename}".replace('/', '_').replace('\\', '_') + + scaled_name = f"scaled_{safe_filename}" + scaled_path = os.path.join(temp_dir, scaled_name) im_resized.save(scaled_path) - print(f"[RegionSelector] Immagine scalata {w}x{h} -> {new_size[0]}x{new_size[1]}") + print(f"[RegionSelector] Image scaled {w}x{h} -> {new_size[0]}x{new_size[1]}") - return {"scaled": True, "path": f"view?filename={scaled_name}&type=temp", "scale": scale_factor} + return {"scaled": True, "path": f"/view?filename={scaled_name}&type=temp", "scale": scale_factor} @server.PromptServer.instance.routes.post("/region_selector/scale") async def scale_image_endpoint(request): + from aiohttp import web try: - data = await request.json() + # Intentar leer el JSON de forma segura + try: + data = await request.json() + except: + # Fallback si el content-type no es exacto o el cuerpo estΓ‘ malformado + post_data = await request.post() + data = dict(post_data) + filename = data.get("filename") + type_ = data.get("type", "input") + subfolder = data.get("subfolder", "") + if not filename: - return {"error": "filename mancante"} - result = scale_image_if_needed(filename) - return result + return web.json_response({"error": "filename missing"}, status=400) + + result = scale_image_if_needed(filename, type_, subfolder) + return web.json_response(result) except Exception as e: - print(f"[RegionSelector] Errore endpoint scale: {e}") - return {"error": str(e)} + print(f"[BoxBox] Error in scale endpoint: {e}") + return web.json_response({"error": str(e)}, status=500) NODE_CLASS_MAPPINGS = {"BoxSelector": RegionSelectorNode} diff --git a/web/canvas_selector.js b/web/canvas_selector.js index f148ab0..3ba38cd 100644 --- a/web/canvas_selector.js +++ b/web/canvas_selector.js @@ -1,516 +1,5 @@ /** - * Canvas Selector - FunzionalitΓ complete di selezione rettangoli - * Basato sul codice di canva_html + * Canvas Selector - Placeholder + * Functionality moved to region_selector_extension.js to avoid duplicate code and synchronization issues. */ - -function initializeCanvasSelector(container, imageUrl) { - console.log("[CanvasSelector] Initializing with image:", imageUrl); - - // Riferimenti agli elementi DOM (cercati dentro il container) - const canvasContainer = container.querySelector('#canvas-container'); - const backgroundImage = container.querySelector('#background-image'); - const baseCoordinates = container.querySelector('#base-coordinates'); - const dimensionsInfo = container.querySelector('#dimensions-info'); - const currentDimensions = container.querySelector('#current-dimensions'); - const zoomInBtn = container.querySelector('#zoom-in-btn'); - const zoomOutBtn = container.querySelector('#zoom-out-btn'); - const zoomValue = container.querySelector('#zoom-value'); - const borderSlider = container.querySelector('#border-slider'); - const borderValue = container.querySelector('#border-value'); - const resetBtn = container.querySelector('#reset-btn'); - const borderPositionRadios = container.querySelectorAll('input[name="border-position"]'); - const imageUpload = container.querySelector('#image-upload'); - const uploadBtn = container.querySelector('#upload-btn'); - const imageName = container.querySelector('#image-name'); - - // Variabili di stato - let isDrawing = false; - let isResizing = false; - let resizingEdge = null; - let startX = 0; - let startY = 0; - let rectStartX = 0; - let rectStartY = 0; - let rectStartWidth = 0; - let rectStartHeight = 0; - let currentRectangle = null; - let currentZoom = 1; - let currentBorderWidth = 0; - let borderPosition = 'inside'; - let rectangleExists = false; - - // Dimensioni base - let baseWidth = 0; - let baseHeight = 0; - let baseX = 0; - let baseY = 0; - - const defaultBorderWidth = 3; - const zoomStep = 0.25; - const minZoom = 0.25; - const maxZoom = 4; - - // Carica l'immagine iniziale - if (imageUrl) { - backgroundImage.src = imageUrl; - const filename = imageUrl.split('/').pop(); - imageName.textContent = `Immagine: ${filename}`; - } - - // ========== EVENT LISTENERS ========== - - // Upload button - uploadBtn.addEventListener('click', () => imageUpload.click()); - - imageUpload.addEventListener('change', (e) => { - const file = e.target.files[0]; - if (file && file.type.startsWith('image/')) { - const reader = new FileReader(); - reader.onload = (event) => { - backgroundImage.src = event.target.result; - imageName.textContent = `Immagine: ${file.name}`; - if (currentRectangle && confirm('Cambiando immagine il rettangolo verrΓ cancellato. Continuare?')) { - resetRectangle(); - } - }; - reader.readAsDataURL(file); - } - }); - - // Zoom buttons - zoomInBtn.addEventListener('click', () => { - if (currentRectangle) { - currentZoom = Math.min(currentZoom + zoomStep, maxZoom); - updateZoom(); - updateAllDimensions(); - } - }); - - zoomOutBtn.addEventListener('click', () => { - if (currentRectangle) { - currentZoom = Math.max(currentZoom - zoomStep, minZoom); - updateZoom(); - updateAllDimensions(); - } - }); - - // Border slider - borderSlider.addEventListener('input', (e) => { - currentBorderWidth = parseInt(e.target.value); - borderValue.textContent = currentBorderWidth + 'px'; - - if (currentRectangle) { - if (currentRectangle.classList.contains('border-outside')) { - currentRectangle.style.outlineWidth = currentBorderWidth + 'px'; - } else { - currentRectangle.style.borderWidth = currentBorderWidth + 'px'; - } - - if (currentBorderWidth > defaultBorderWidth) { - currentRectangle.classList.add('thick-border'); - } else { - currentRectangle.classList.remove('thick-border'); - } - - updateAllDimensions(); - } - }); - - // Border position radios - borderPositionRadios.forEach(radio => { - radio.addEventListener('change', (e) => { - borderPosition = e.target.value; - - if (currentRectangle) { - if (borderPosition === 'outside') { - currentRectangle.classList.remove('border-inside'); - currentRectangle.classList.add('border-outside'); - currentRectangle.style.outlineWidth = currentBorderWidth + 'px'; - currentRectangle.style.borderWidth = '0px'; - } else { - currentRectangle.classList.remove('border-outside'); - currentRectangle.classList.add('border-inside'); - currentRectangle.style.borderWidth = currentBorderWidth + 'px'; - currentRectangle.style.outlineWidth = '0px'; - } - - updateAllDimensions(); - } - }); - }); - - // Reset button - resetBtn.addEventListener('click', () => { - if (confirm('Vuoi cancellare il rettangolo e disegnarne uno nuovo?')) { - resetRectangle(); - } - }); - - // Mouse down - inizio disegno - canvasContainer.addEventListener('mousedown', (e) => { - if (rectangleExists) return; - if (e.target.classList.contains('resize-handle')) return; - - const rect = canvasContainer.getBoundingClientRect(); - startX = e.clientX - rect.left; - startY = e.clientY - rect.top; - - isDrawing = true; - - currentRectangle = document.createElement('div'); - currentRectangle.className = 'rectangle'; - - if (borderPosition === 'outside') { - currentRectangle.classList.add('border-outside'); - currentRectangle.style.outlineWidth = currentBorderWidth + 'px'; - currentRectangle.style.outlineStyle = 'solid'; - currentRectangle.style.borderWidth = '0px'; - } else { - currentRectangle.classList.add('border-inside'); - currentRectangle.style.borderWidth = currentBorderWidth + 'px'; - } - - currentRectangle.style.left = startX + 'px'; - currentRectangle.style.top = startY + 'px'; - currentRectangle.style.width = '0px'; - currentRectangle.style.height = '0px'; - - if (currentBorderWidth > defaultBorderWidth) { - currentRectangle.classList.add('thick-border'); - } - - canvasContainer.appendChild(currentRectangle); - }); - - // Mouse move - document.addEventListener('mousemove', (e) => { - if (isDrawing) { - const rect = canvasContainer.getBoundingClientRect(); - const currentX = e.clientX - rect.left; - const currentY = e.clientY - rect.top; - - const width = currentX - startX; - const height = currentY - startY; - - if (width < 0) { - currentRectangle.style.left = currentX + 'px'; - currentRectangle.style.width = Math.abs(width) + 'px'; - } else { - currentRectangle.style.width = width + 'px'; - } - - if (height < 0) { - currentRectangle.style.top = currentY + 'px'; - currentRectangle.style.height = Math.abs(height) + 'px'; - } else { - currentRectangle.style.height = height + 'px'; - } - } - - if (isResizing && currentRectangle) { - const deltaX = e.clientX - startX; - const deltaY = e.clientY - startY; - - switch(resizingEdge) { - case 'top': - const newTop = rectStartY + deltaY; - const newHeight = rectStartHeight - deltaY; - if (newHeight > 0) { - currentRectangle.style.top = newTop + 'px'; - currentRectangle.style.height = newHeight + 'px'; - } - break; - - case 'bottom': - const bottomHeight = rectStartHeight + deltaY; - if (bottomHeight > 0) { - currentRectangle.style.height = bottomHeight + 'px'; - } - break; - - case 'left': - const newLeft = rectStartX + deltaX; - const newWidth = rectStartWidth - deltaX; - if (newWidth > 0) { - currentRectangle.style.left = newLeft + 'px'; - currentRectangle.style.width = newWidth + 'px'; - } - break; - - case 'right': - const rightWidth = rectStartWidth + deltaX; - if (rightWidth > 0) { - currentRectangle.style.width = rightWidth + 'px'; - } - break; - - case 'top-left': - const tlNewTop = rectStartY + deltaY; - const tlNewLeft = rectStartX + deltaX; - const tlNewHeight = rectStartHeight - deltaY; - const tlNewWidth = rectStartWidth - deltaX; - if (tlNewHeight > 0 && tlNewWidth > 0) { - currentRectangle.style.top = tlNewTop + 'px'; - currentRectangle.style.left = tlNewLeft + 'px'; - currentRectangle.style.height = tlNewHeight + 'px'; - currentRectangle.style.width = tlNewWidth + 'px'; - } - break; - - case 'top-right': - const trNewTop = rectStartY + deltaY; - const trNewHeight = rectStartHeight - deltaY; - const trNewWidth = rectStartWidth + deltaX; - if (trNewHeight > 0 && trNewWidth > 0) { - currentRectangle.style.top = trNewTop + 'px'; - currentRectangle.style.height = trNewHeight + 'px'; - currentRectangle.style.width = trNewWidth + 'px'; - } - break; - - case 'bottom-left': - const blNewLeft = rectStartX + deltaX; - const blNewHeight = rectStartHeight + deltaY; - const blNewWidth = rectStartWidth - deltaX; - if (blNewHeight > 0 && blNewWidth > 0) { - currentRectangle.style.left = blNewLeft + 'px'; - currentRectangle.style.height = blNewHeight + 'px'; - currentRectangle.style.width = blNewWidth + 'px'; - } - break; - - case 'bottom-right': - const brNewWidth = rectStartWidth + deltaX; - const brNewHeight = rectStartHeight + deltaY; - if (brNewHeight > 0 && brNewWidth > 0) { - currentRectangle.style.width = brNewWidth + 'px'; - currentRectangle.style.height = brNewHeight + 'px'; - } - break; - } - - baseX = parseFloat(currentRectangle.style.left); - baseY = parseFloat(currentRectangle.style.top); - baseWidth = parseFloat(currentRectangle.style.width); - baseHeight = parseFloat(currentRectangle.style.height); - - updateAllDimensions(); - } - }); - - // Mouse up - document.addEventListener('mouseup', (e) => { - if (isDrawing) { - const rect = canvasContainer.getBoundingClientRect(); - const endX = e.clientX - rect.left; - const endY = e.clientY - rect.top; - - const x1 = Math.min(startX, endX); - const y1 = Math.min(startY, endY); - const x2 = Math.max(startX, endX); - const y2 = Math.max(startY, endY); - - baseX = x1; - baseY = y1; - baseWidth = x2 - x1; - baseHeight = y2 - y1; - - rectangleExists = true; - currentRectangle.classList.add('complete'); - - canvasContainer.classList.add('drawing-disabled'); - canvasContainer.style.cursor = 'default'; - - resetBtn.disabled = false; - zoomInBtn.disabled = currentZoom >= maxZoom; - zoomOutBtn.disabled = currentZoom <= minZoom; - - dimensionsInfo.style.display = 'block'; - - addResizeHandles(); - updateAllDimensions(); - - isDrawing = false; - } - - if (isResizing) { - isResizing = false; - resizingEdge = null; - canvasContainer.style.cursor = 'default'; - } - }); - - // ========== FUNZIONI HELPER ========== - - function resetRectangle() { - if (currentRectangle) { - currentRectangle.remove(); - } - currentRectangle = null; - rectangleExists = false; - currentZoom = 1; - updateZoom(); - canvasContainer.classList.remove('drawing-disabled'); - canvasContainer.style.cursor = 'crosshair'; - resetBtn.disabled = true; - zoomInBtn.disabled = true; - zoomOutBtn.disabled = true; - dimensionsInfo.style.display = 'none'; - baseCoordinates.innerHTML = '
Clicca e trascina sull\'immagine per disegnare un rettangolo
'; - } - - function updateZoom() { - const zoomPercent = Math.round(currentZoom * 100); - zoomValue.textContent = zoomPercent + '%'; - if (currentRectangle) { - currentRectangle.style.transform = `scale(${currentZoom})`; - } - - zoomInBtn.disabled = currentZoom >= maxZoom; - zoomOutBtn.disabled = currentZoom <= minZoom; - } - - function addResizeHandles() { - const handles = ['top', 'bottom', 'left', 'right', 'top-left', 'top-right', 'bottom-left', 'bottom-right']; - handles.forEach(position => { - const handle = document.createElement('div'); - handle.className = `resize-handle ${position}`; - handle.dataset.edge = position; - currentRectangle.appendChild(handle); - - handle.addEventListener('mousedown', (e) => { - e.stopPropagation(); - isResizing = true; - resizingEdge = position; - startX = e.clientX; - startY = e.clientY; - - rectStartX = parseFloat(currentRectangle.style.left); - rectStartY = parseFloat(currentRectangle.style.top); - rectStartWidth = parseFloat(currentRectangle.style.width); - rectStartHeight = parseFloat(currentRectangle.style.height); - - canvasContainer.style.cursor = getComputedStyle(handle).cursor; - }); - }); - } - - function updateAllDimensions() { - if (!currentRectangle) return; - - const baseX1 = baseX; - const baseY1 = baseY; - const baseX2 = baseX + baseWidth; - const baseY2 = baseY + baseHeight; - - const centerX = baseX + (baseWidth / 2); - const centerY = baseY + (baseHeight / 2); - - const zoomedWidth = baseWidth * currentZoom; - const zoomedHeight = baseHeight * currentZoom; - - const zoomedX1 = centerX - (zoomedWidth / 2); - const zoomedY1 = centerY - (zoomedHeight / 2); - const zoomedX2 = centerX + (zoomedWidth / 2); - const zoomedY2 = centerY + (zoomedHeight / 2); - - let effectiveX1, effectiveY1, effectiveX2, effectiveY2; - let effectiveWidth, effectiveHeight; - - if (borderPosition === 'inside') { - effectiveX1 = zoomedX1; - effectiveY1 = zoomedY1; - effectiveX2 = zoomedX2; - effectiveY2 = zoomedY2; - effectiveWidth = zoomedWidth; - effectiveHeight = zoomedHeight; - } else { - effectiveX1 = zoomedX1 - currentBorderWidth; - effectiveY1 = zoomedY1 - currentBorderWidth; - effectiveX2 = zoomedX2 + currentBorderWidth; - effectiveY2 = zoomedY2 + currentBorderWidth; - effectiveWidth = zoomedWidth + (currentBorderWidth * 2); - effectiveHeight = zoomedHeight + (currentBorderWidth * 2); - } - - baseCoordinates.innerHTML = ` - π Coordinate Base: