Function Signature
Description
ThecropImage function captures the currently visible portion of a zoomed image and exports it as a base64-encoded data URL. It accounts for the current zoom level, position, and optional rotation, making it useful for implementing “save current view” or “export cropped image” features.
Parameters
The current zoom level of the image. A value of
1 represents the original size, while 2 represents 2x zoom.The HTML image element to crop. This should be the zoomed image element.
The horizontal position offset in pixels. This represents how far the image has been panned horizontally.
The vertical position offset in pixels. This represents how far the image has been panned vertically.
The rotation angle in degrees. Supports
0, 90, 180, or 270 degrees. The value is normalized using modulo 360.Return Value
A promise that resolves to a base64-encoded data URL of the cropped image. The format is
data:image/png;base64,... and can be used directly as an image source or downloaded.How It Works
- Calculate Scale: Computes the scale factor based on the image’s natural dimensions and current display size
- Create Canvas: Creates an HTML canvas element matching the visible area dimensions
- Crop Image: Draws the visible portion of the image onto the canvas
- Apply Rotation: If rotation is specified, applies the transformation on a second canvas
- Export Data: Converts the final canvas to a data URL
Usage Examples
Basic Cropping
Cropping with Rotation
Download Cropped Image
Integration with Zoom State
Use Cases
- Export Current View: Allow users to save the exact portion of an image they’re viewing
- Image Editing Tools: Implement crop functionality in image editors
- Profile Picture Crop: Let users select and crop a portion of an uploaded image
- Screenshot Features: Capture specific areas of zoomable images
- Print Preview: Generate a croppable preview of images before printing
Technical Notes
- The function uses HTML Canvas API for image manipulation
- Rotation is applied after cropping to maintain accuracy
- The scale calculation accounts for both natural and display dimensions
- Supports rotation angles of 90 and 270 degrees with dimension swapping
- Returns PNG format by default via
canvas.toDataURL()