Skip to content

Instantly share code, notes, and snippets.

@jaredatron
Created June 17, 2020 23:27
Show Gist options
  • Save jaredatron/717b1e07cb21f0fbc7348f477c6ae8ad to your computer and use it in GitHub Desktop.
Save jaredatron/717b1e07cb21f0fbc7348f477c6ae8ad to your computer and use it in GitHub Desktop.
Example of using ReactCrop react-image-crop
import React, { useRef, useState } from 'react'
import PropTypes from 'prop-types'
import ReactCrop from 'react-image-crop'
import 'react-image-crop/dist/ReactCrop.css'
export default function CropImage({
className = '',
src,
height,
width,
type = 'image/png',
encoderOptions,
onChange,
}){
const imageRef = useRef()
const [crop, setCrop] = useState({
unit: '%',
width: 100,
aspect: width / height,
})
return <ReactCrop
className={`CropImage ${className}`}
src={src}
onImageLoaded={img => { imageRef.current = img }}
crop={crop}
onChange={(_, percentCrop) => setCrop(percentCrop)}
onComplete={(_, percentCrop) => {
onChange(cropImage({
image: imageRef.current,
height,
width,
type,
encoderOptions,
percentCrop,
}))
}}
/>
}
CropImage.propTypes = {
className: PropTypes.string,
src: PropTypes.string.isRequired,
height: PropTypes.number.isRequired,
width: PropTypes.number.isRequired,
onChange: PropTypes.func.isRequired,
type: PropTypes.string,
encoderOptions: PropTypes.any,
}
function cropImage({image, height, width, type, encoderOptions, percentCrop}){
const sx = image.naturalWidth * (percentCrop.x / 100)
const sy = image.naturalHeight * (percentCrop.y / 100)
const sWidth = image.naturalWidth * (percentCrop.width / 100)
const sHeight = image.naturalHeight * (percentCrop.height / 100)
const canvas = document.createElement('canvas')
canvas.width = width
canvas.height = height
const ctx = canvas.getContext('2d')
ctx.drawImage(image, sx, sy, sWidth, sHeight, 0, 0, width, height)
return canvas.toDataURL(type, encoderOptions)
}
@quantumchuckles
Copy link

TypeError: onChange is not a function

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment