1.0.0 • Published 1 year ago

use-cropped-area v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

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.

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

PropertyDescriptionTypeDefault Prop
area*Cropped area of imageArea / null / undefinedrequired
image*Image is used for cropping areaHTMLImageElement / null / undefinedrequired
drawingControl of drawing the canvas elementbooleanoptionaltrue

License

MIT

Contact

LI

EMAIL