Skip to content

use-cropped-area is a react hook for creating canvas image from the cropped area of image.

License

Notifications You must be signed in to change notification settings

typeof-null/use-cropped-area

Repository files navigation

use-cropped-area

NPM version npm-typescript Build License

use-cropped-area is a react hook for creating canvas image from the cropped area of image.

view-example

Live Creativity Demo

Installation

npm install use-cropped-area --save-dev

or

yarn add -D use-cropped-area

Usage

import React, { useRef, useMemo, useState } from 'react'
import useCroppedArea, { Area, AreaKey } from 'use-cropped-area'
import { INITIAL_AREA, CANVAS_STYLES } from './constants'

function Example() {
    const [area, setArea] = useState<Area>(INITIAL_AREA)
    const image = useRef<HTMLImageElement | null>(null)
    const canvasRef = useCroppedArea({ area, image: image.current })
    
    const handleChangeArea = (key: AreaKey, value: number) => 
        setArea((prev) => ({ ...prev, [key]: value }))

    const {width, height} = area
    const canvasStyle = useMemo(() => ({
        ...CANVAS_STYLES,
        width,
        height,
    }), [width, height])
    return (
       <Content> 
           <Side>
                <ImageWithCrop
                    ref={image}
                    area={area}
                    src='/path_to_image'
                    onChange={handleChangeArea}
                />
           </Side>
           <Side>
                <canvas ref={canvasRef} style={canvasStyle} />
           </Side>   
       </Content>    
    )
}

Api

Property Description Type Default Prop
area* Cropped area of image Area / null / undefined required
image* Image is used for cropping area HTMLImageElement / null / undefined required
drawing Control of drawing the canvas element boolean optional true

License

MIT

Contact

LI

EMAIL