use-cropped-area is a react
hook for creating canvas image from the cropped area of image.
npm install use-cropped-area --save-dev
or
yarn add -D use-cropped-area
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>
)
}