react-advanced-cropper

repository·master·Indexed 21 days ago

https://github.com/advanced-cropper/react-advanced-cropper

A highly customizable React library for creating image croppers. It supports various cropper types, mobile and desktop interaction, and deep customization of appearance and behavior. Key features include support for Rectangle and Circle stencils, image restrictions (fitArea, fillArea, stencil, none), and the ability to override core operations via custom algorithms. Version 0.20.2.

Tokens
40.4K
Snippets
117
Records
154
Agent score
73%

What's inside react-advanced-cropper

  1. Understand the three cropper types

    master

    The library categorizes croppers into three distinct behavioral groups. Choosing the right group depends on whether you want the user to manipulate the stencil (the selection area) or the image itself:

    1. Classic Cropper: The primary interaction is resizing and moving the stencil. The image may move or resize as a secondary effect.
    2. Fixed Cropper: The stencil is static. It has a fixed size and cannot be moved or resized (no handlers). The user can only change the image's size and position within the stencil.
    3. Hybrid Cropper: A semi-fixed stencil. The user can change the stencil's size and position, but it behaves as if it is trying to return to a default position and size (often used to maintain specific aspect ratios or constraints).
  2. Configure the settings object for state modifiers

    master

    To use state modifiers in react-advanced-cropper, you must define a settings object containing all required fields. This object allows you to control initial states, restrictions on the visible area, and restrictions on the stencil (coordinates) size, position, and aspect ratio.

    {
    	defaultCoordinates,
    	defaultVisibleArea,
    	areaPositionRestrictions,
    	areaSizeRestrictions,
    	sizeRestrictions,
    	positionRestrictions,
    	aspectRatio,
    }
  3. Enable page scrolling while interacting with the cropper

    master

    By default, the Cropper prevents all default mouse and touch events on its background wrapper to ensure that user interactions (like dragging the image) don't accidentally scroll the page.

    If you want to allow the user to scroll the page even when their cursor is over the cropper, you must replace the default CropperBackgroundWrapper with a custom implementation that does not prevent default events.

  4. How to use default settings with `createDefaultSettings`

    master

    To customize the behavior of state modifiers (like position and size restrictions), you must define a settings object. While you can manually define all fields of the settings object, the recommended approach is to use the createDefaultSettings function.

    createDefaultSettings simplifies the process by providing a set of flexible default functions. You can pass an object to createDefaultSettings to override specific defaults or provide additional constraints like minWidth, minHeight, maxWidth, or maxHeight.

    const state = createState({
    	boundaries: {
    		width: 100,
    		height: 100
    	},
    	imageSize: {
    		width: 50,
    		height: 100,
    	},
    	settings: createDefaultSettings()
    })
  5. Understand the Cropper State concept

    master

    The core concept of react-advanced-cropper is the cropper state. All components and hooks provided by the library are essentially tools to modify this state or display it.

    The state is represented by a CropperState object. Note that the state can be null if it has not been initialized yet.

    The state is composed of five main parts: boundary, imageSize, transforms, visibleArea, and coordinates.

    interface CropperState {
    	boundary: Boundary;
    	imageSize: ImageSize;
    	transforms: Transforms;
    	visibleArea: VisibleArea | null;
    	coordinates: Coordinates | null;
    }
  6. Implement a custom background component for image adjustments

    master

    To apply real-time image adjustments (like brightness or saturation) without resetting the cropper state or sacrificing performance, you should replace the default CropperBackgroundImage with a custom background component.

    Your custom component must:

    1. Use getBackgroundStyle from react-advanced-cropper to calculate the correct transform/scale styles.
    2. Forward a ref to either an HTMLImageElement or an HTMLCanvasElement. Using an HTMLCanvasElement is recommended if you want to draw adjusted images (e.g., using ctx.filter) so that the cropper can retrieve the final processed content.
    3. Accept image, state, and transitions as props provided by the Cropper via the backgroundComponent mechanism.
    import { CropperTransitions, CropperImage, CropperState, getBackgroundStyle } from 'react-advanced-cropper';
    
    // Example of a component structure that satisfies the requirements
    export const MyCustomBackground = forwardRef<HTMLCanvasElement, Props>((
        { className, image, state, transitions, ...props 
    }, ref) => {
        const style = image && state ? getBackgroundStyle(image, state, transitions) : {};
        // ... implementation using a canvas to apply filters ...
        return <canvas ref={ref} style={style} />;
    });
  7. Configure cropper behavior using Settings

    master

    Settings are parameters used by state modifiers and helpers to perform operations on the cropper state. They act as a context or a set of global variables for the cropper's logic.

    CoreSettings

    The CoreSettings interface contains the minimal set of parameters required for most operations:

    • Default coordinates
    • Default visible area
    • Area position restrictions
    • Area size restrictions
    • Size restrictions
    • Position restrictions
    • Aspect ratio

    It is recommended to extend CoreSettings to allow your custom modifiers and helpers to access additional parameters. For example, the transformImage modifier requires extended settings:

    function transformImage(state: CropperState, settings: CoreSettings & ModifiersSettings, ...otherArguments): CropperState

    Tip: If a parameter needs to be shared across different modifiers or if you cannot easily pass it as a direct argument to a specific modifier call, include it in the settings object.

  8. Handle stencil resize and move events

    master

    To make a custom stencil interactive, connect the onMove and onMoveEnd callbacks of DraggableElement or DraggableArea to the cropper's API.

    Resizing with DraggableElement

    DraggableElement provides an onMove callback with a shift object of type MoveDirections ({ left: number; top: number; }). This represents the pixel delta of the movement.

    To resize, call cropper.resizeCoordinates. You can use the compensate: true option to allow the stencil to resize in other directions if it hits the cropper boundary.

    Moving with DraggableArea

    To move the stencil, call cropper.moveCoordinates(directions) where directions is a MoveDirections object.

    To finalize the interaction, call cropper.resizeCoordinatesEnd or cropper.moveCoordinatesEnd in the onMoveEnd callback.

    const onResize = (shift: MoveDirections) => {
    	// Example: resizing from center
    	cropper.resizeCoordinates('center', {
    		left: shift.left,
    		top: shift.left,
    	}, {
    		compensate: true,
    	});
    };
    
    const onMove = (directions: MoveDirections) => {
    	cropper.moveCoordinates(directions);
    };
  9. How state modifiers work

    master

    State modifiers are functions used to change the cropper state, preferably by returning a clone of the state. A standard state modifier follows this signature:

    function stateModifier(state: CropperState, settings: CoreSettings, ...otherArguments): CropperState

    They accept the current state, the settings (which act as context), and optional additional arguments, returning the updated CropperState.