js/imageeditor/shared/crop/CROP.md
The crop tool is a component of the image editor that allows users to select a portion of an image to keep while discarding the rest. It provides an interactive UI with handles that can be dragged to adjust the crop area.
js/imageeditor/shared/crop/crop.ts - Main implementation of the crop tooljs/imageeditor/shared/core/editor.ts - Defines the Tool interface and ImageEditorContextjs/imageeditor/shared/Toolbar.svelte - Defines the tool types and subtool typesCropToolThe CropTool class implements the Tool interface defined in editor.ts. It provides the following functionality:
The crop tool maintains several state variables:
crop_bounds - Stores the x, y, width, and height of the crop areais_dragging - Tracks if a handle is being draggedis_dragging_window - Tracks if the entire crop window is being draggedselected_handle - Reference to the currently selected handleactive_corner_index - Index of the active corner (-1 if none)active_edge_index - Index of the active edge (-1 if none)The crop tool creates several visual elements:
crop_ui_container - Container for all UI elementscrop_mask - Graphics object used to mask the imageThe tool sets up event listeners for:
pointerdown - Start dragging a handle or the windowpointermove - Update crop bounds during draggingpointerup - End dragging operationssetup(context, tool, subtool) - Initializes the tool with the editor contextinit_crop_ui() - Creates the UI elementsset_crop_mask() - Sets up the mask for the imagemake_crop_ui(width, height) - Creates the crop UI containercreate_handle(is_edge) - Creates a handle (corner or edge)create_corner_handles(container, width, height) - Creates the corner handlescreate_edge_handles(container, width, height) - Creates the edge handleshandle_pointer_down(event, handle, corner_index, edge_index) - Handles pointer down eventshandle_pointer_move(event) - Handles pointer move eventshandle_pointer_up() - Handles pointer up eventshandle_window_drag_start(event) - Handles the start of window draggingupdate_crop_bounds(delta) - Updates crop bounds based on pointer movementconstrain_crop_bounds() - Ensures crop bounds stay within image dimensionsupdate_crop_mask() - Updates the mask graphicsupdate_crop_ui() - Updates the crop UI position and dimensionsupdate_handle_positions(width, height) - Updates handle positionsThe crop tool integrates with the editor through the ImageEditorContext interface, which provides:
app - The PIXI.js Application instanceimage_container - The container holding the imagedimensions - A readable store with the image dimensionsposition - A readable store with the image positionscale - A readable store with the image scaleThe crop tool uses a PIXI.js mask with alpha=0 to make the mask invisible while still functioning as a mask. This prevents the white background from appearing in the masked area.
The tool handles scaling by:
The tool enforces several constraints:
When modifying the crop tool, consider: