react-avatar-editor、react-cropper、react-easy-crop、react-image-crop はすべて、Reactアプリケーション内で画像をトリミング(クロップ)する機能を提供するライブラリです。これらのライブラリは、ユーザーが画像をアップロードし、特定の領域を選択して切り取ることを可能にします。主なユースケースには、プロフィール写真の編集、サムネイル生成、画像の焦点領域選択などがあります。各ライブラリは異なるアーキテクチャとAPI設計を採用しており、開発者のニーズやプロジェクト要件に応じて最適な選択肢が変わります。
Reactアプリケーションで画像をトリミングする必要があるとき、どのライブラリを選ぶべきでしょうか? react-avatar-editor、react-cropper、react-easy-crop、react-image-crop はすべて同じ目的を持ちますが、内部実装、機能セット、開発体験に大きな違いがあります。この記事では、実際のコード例を交えながら、それぞれの特徴と使いどころを詳しく比較します。
react-avatar-editorreact-avatar-editor は、canvas要素を直接操作して画像を描画・トリミングします。コンポーネントのpropsを通じて画像ソース、スケール、回転などを指定します。
import AvatarEditor from 'react-avatar-editor';
function Editor() {
const editorRef = useRef(null);
const handleSave = () => {
const canvas = editorRef.current.getImage();
const dataUrl = canvas.toDataURL('image/png');
// dataUrlをサーバーに送信など
};
return (
<div>
<AvatarEditor
ref={editorRef}
image="/path/to/image.jpg"
width={250}
height={250}
border={50}
color={[255, 255, 255, 0.6]} // RGBA
scale={1.2}
rotate={0}
/>
<button onClick={handleSave}>保存</button>
</div>
);
}
react-cropperreact-cropper は、人気のあるCropper.jsライブラリをReactコンポーネントとしてラップしています。ref経由でCropperインスタンスにアクセスし、メソッドを呼び出します。
import Cropper from 'react-cropper';
import 'cropperjs/dist/cropper.css';
function Editor() {
const cropperRef = useRef(null);
const handleCrop = () => {
const imageElement = cropperRef?.current;
const cropper = imageElement?.cropper;
const croppedCanvas = cropper.getCroppedCanvas();
const dataUrl = croppedCanvas.toDataURL('image/jpeg');
};
return (
<div>
<Cropper
src="/path/to/image.jpg"
style={{ height: 400, width: '100%' }}
initialAspectRatio={1}
guides={true}
cropBoxResizable={true}
ref={cropperRef}
/>
<button onClick={handleCrop}>トリミング</button>
</div>
);
}
react-easy-cropreact-easy-crop は、純粋なReactコンポーネントで、canvasではなくCSS transformを使用して画像を操作します。トリミング結果の座標をコールバックで受け取り、別途canvasで最終画像を生成します。
import Cropper from 'react-easy-crop';
function Editor() {
const [crop, setCrop] = useState({ x: 0, y: 0 });
const [zoom, setZoom] = useState(1);
const [croppedAreaPixels, setCroppedAreaPixels] = useState(null);
const onCropComplete = (croppedArea, croppedAreaPixels) => {
setCroppedAreaPixels(croppedAreaPixels);
};
const showCroppedImage = async () => {
const croppedImage = await getCroppedImg(
'/path/to/image.jpg',
croppedAreaPixels
);
// croppedImageはdata URL
};
return (
<div>
<div style={{ position: 'relative', width: '100%', height: 400 }}>
<Cropper
image="/path/to/image.jpg"
crop={crop}
zoom={zoom}
aspect={1}
onCropChange={setCrop}
onZoomChange={setZoom}
onCropComplete={onCropComplete}
/>
</div>
<button onClick={showCroppedImage}>表示</button>
</div>
);
}
react-image-cropreact-image-crop は、最小限の機能に特化したシンプルなライブラリです。propsで画像とクロップ領域を指定し、onChangeで更新を監視します。
import ReactCrop from 'react-image-crop';
import 'react-image-crop/dist/ReactCrop.css';
function Editor() {
const [crop, setCrop] = useState({ aspect: 1 });
const onImageLoaded = (image) => {
// 画像が読み込まれた後の処理
};
const onCropComplete = (crop) => {
// クロップ領域が確定したときの処理
};
return (
<ReactCrop
src="/path/to/image.jpg"
crop={crop}
onImageLoaded={onImageLoaded}
onComplete={onCropComplete}
onChange={newCrop => setCrop(newCrop)}
/>
);
}
react-avatar-editor: 正方形固定(widthとheightを同じ値に設定することで疑似対応可能だが、本質的には正方形専用)。react-cropper: 自由に設定可能。aspectRatio propで数値またはNaN(自由)を指定。react-easy-crop: aspect propで任意の比率を指定可能(例: 16 / 9)。react-image-crop: crop.aspectで比率を指定可能。react-avatar-editor: scale propで拡大縮小、rotate propで回転(90度単位)。react-cropper: 拡大縮小、任意角度の回転、フリップ(水平・垂直反転)をサポート。react-easy-crop: 滑らかなzoomと任意角度のrotationをサポート。react-image-crop: 拡大縮小や回転はサポートされていない。react-avatar-editor: 内部でcanvasを操作するため、getImage()で直接canvas要素を取得可能。高品質なPNG出力が可能。react-cropper: getCroppedCanvas()でcanvasを取得し、そこからdata URLやBlobを生成。react-easy-crop: トリミング座標のみを提供。最終画像の生成には、提供されているユーティリティ関数(getCroppedImg)または自前実装が必要。react-image-crop: getCroppedImgなどのヘルパー関数は提供されず、開発者が自前でcanvas操作を実装する必要がある。react-avatar-editor: canvasベースのため、大規模な画像でも比較的軽量だが、アニメーションやインタラクションは限定的。react-cropper: Cropper.jsに依存するため、bundle sizeが大きくなりがち。ただし、機能が豊富でパフォーマンスも十分。react-easy-crop: 純粋なReact実装で依存が少なく、bundle sizeも小さい。CSS transformによる描画で滑らかな操作が可能。react-image-crop: 最も軽量で、最小限の機能に特化しているため、パフォーマンスへの影響は極小。react-avatar-editor: カスタマイズ性は低く、スタイルや挙動の変更が難しい。正方形のアバター用途以外には不向き。react-cropper: Cropper.jsの豊富なオプションを活用できるため、高度なカスタマイズが可能。ただし、Cropper.jsの学習コストが発生。react-easy-crop: 直感的なAPIと豊富なコールバックで、カスタムUIの実装が容易。zoomやrotationのスライダーを簡単に追加可能。react-image-crop: 基本的な機能しか提供しないため、高度なカスタマイズには多くの自前実装が必要。| ライブラリ | 最適なユースケース | 注意点 |
|---|---|---|
react-avatar-editor | 正方形のプロフィール画像編集 | 長方形非対応、メンテナンス状況要確認 |
react-cropper | 豊富な編集機能が必要な複雑な画像エディタ | bundle sizeが大きめ、Cropper.js依存 |
react-easy-crop | モダンで直感的なUIと軽量さを両立したい場合 | 最終画像生成に別途実装が必要 |
react-image-crop | 最小限の機能で素早く導入したい場合 | 拡大縮小・回転非対応、カスタマイズ性低め |
react-avatar-editor(ただし、メンテナンス状況を確認)react-cropperreact-easy-cropreact-image-cropプロジェクトの要件に合わせて、これらのライブラリの中から最適なものを選んでください。
react-easy-crop は、モダンで直感的なUIと軽量な実装を求める場合に最適です。zoomやrotationをサポートしつつも、パフォーマンスに優れたpure React実装を採用しています。canvasではなくCSS transformに基づいており、最終的な画像出力には別途canvas操作が必要ですが、UXと開発体験のバランスが非常に良い選択肢です。
react-image-crop は、最小限の機能で素早く導入したい場合に適しています。シンプルな矩形選択と基本的なイベントハンドリングを提供し、bundle sizeも小さいです。ただし、zoomやrotationといった高度な機能は含まれておらず、カスタマイズ性も限定的なため、基本的なクロップ機能のみ必要なプロジェクト向けです。
react-avatar-editor は、特に正方形のアバター画像を扱うシンプルなユースケースに最適です。内部でcanvas要素を使用し、出力もcanvasベースであるため、高解像度のPNG出力や回転機能が必要な場合に適しています。ただし、長方形のクロップ領域や高度なカスタマイズには向いておらず、メンテナンスが停滞している可能性があるため、新規プロジェクトでは慎重に検討すべきです。
react-cropper は、強力かつ柔軟な画像編集機能を必要とするプロジェクトに適しています。Cropper.jsをReactでラップしたもので、拡大・縮小、回転、フリップ、複数のガイドライン表示など、豊富な機能を提供します。ただし、依存関係としてCropper.jsを必要とし、bundle sizeが大きくなる可能性があるため、軽量さを重視する場合は注意が必要です。
A React component to crop images/videos with easy interactions
Check out the examples:
If react-easy-crop doesn't cover your needs we recommend taking a look at Pintura
Pintura features cropping, rotating, flipping, filtering, annotating, and lots of additional functionality to cover all your image and video editing needs on both mobile and desktop devices.
yarn add react-easy-crop
or
npm install react-easy-crop --save
The Cropper is styled with
position: absoluteto take the full space of its parent. Thus, you need to wrap it with an element that usesposition: relativeor the Cropper will fill the whole page.
import { useState, useCallback } from 'react'
import Cropper from 'react-easy-crop'
const Demo = () => {
const [crop, setCrop] = useState({ x: 0, y: 0 })
const [zoom, setZoom] = useState(1)
const onCropComplete = (croppedArea, croppedAreaPixels) => {
console.log(croppedArea, croppedAreaPixels)
}
return (
<Cropper
image={yourImage}
crop={crop}
zoom={zoom}
aspect={4 / 3}
onCropChange={setCrop}
onCropComplete={onCropComplete}
onZoomChange={setZoom}
/>
)
}
This component requires some styles to be available in the document. By default, you don't need to do anything, the component will automatically inject the required styles in the document head. If you want to disable this behaviour and manually inject the CSS, you can set the disableAutomaticStylesInjection prop to true and use the file available in the package: react-easy-crop/react-easy-crop.css.
If you are using the Cropper inside a modal, you should ensure that there is no opening animation that is changing the modal dimensions (scaling effect). Fading or sliding animations are fine. See #428, #409, #267 or #400 for more details.
| Prop | Type | Required | Description |
|---|---|---|---|
image | string | The image to be cropped. image or video is required. | |
video | string or Array<{ src: string; type?: string }> | The video to be cropped. image or video is required. | |
crop | { x: number, y: number } | ✓ | Position of the media. { x: 0, y: 0 } will center the media under the cropper. |
zoom | number | Zoom of the media between minZoom and maxZoom. Defaults to 1. | |
rotation | number (in degrees) | Rotation of the media. Defaults to 0. | |
aspect | number | Aspect of the cropper. The value is the ratio between its width and its height. The default value is 4/3 | |
minZoom | number | Minimum zoom of the media. Defaults to 1. | |
maxZoom | number | Maximum zoom of the media. Defaults to 3. | |
zoomWithScroll | boolean | Enable zoom by scrolling. Defaults to true | |
cropShape | 'rect' | 'round' | Shape of the crop area. Defaults to 'rect'. | |
cropSize | { width: number, height: number } | Size of the crop area (in pixels). If you don't provide it, it will be computed automatically using the aspect prop and the media size. You should probably not use this option and should rely on aspect instead. See https://github.com/ValentinH/react-easy-crop/issues/186. | |
showGrid | boolean | Whether to show or not the grid (third-lines). Defaults to true. | |
roundCropAreaPixels | boolean | Whether to round the crop area dimensions to integer pixels. Defaults to false. | |
zoomSpeed | number | Multiplies the value by which the zoom changes. Defaults to 1. | |
objectFit demo | 'contain', 'cover', 'horizontal-cover' or 'vertical-cover' | Specifies how the image is shown in the cropper. contain: the image will be adjusted to be fully visible, horizontal-cover: the image will horizontally fill the cropper, vertical-cover: the image will vertically fill the cropper, cover: we automatically pick between horizontal-cover or vertical-cover to have a fully visible image inside the cropper area. Defaults to "contain". | |
onCropChange | crop => void | ✓ | Called every time the crop is changed. Use it to update your crop state. |
onZoomChange | zoom => void | Called every time the zoom is changed. Use it to update your zoom state. | |
onRotationChange | rotation => void | Called every time the rotation is changed (with mobile or multi-fingers gestures). Use it to update your rotation state. | |
onCropSizeChange | cropSize => void | Called when a change in either the cropSize width or the cropSize height occurs. | |
onCropComplete | Function | Called when the user stops moving the media or stops zooming. It will be passed the corresponding cropped area on the media in percentages and pixels (rounded to the nearest integer) | |
onCropAreaChange | Function | Very similar to onCropComplete but is triggered for every user interaction instead of waiting for the user to stop. | |
transform | string | CSS transform to apply to the image in the editor. Defaults to translate(${crop.x}px, ${crop.y}px) rotate(${rotation}deg) scale(${zoom}) with variables being pulled from props. | |
style | { containerStyle: object, mediaStyle: object, cropAreaStyle: object } | Custom styles to be used with the Cropper. Styles passed via the style prop are merged with the defaults. | |
classes | { containerClassName: string, mediaClassName: string, cropAreaClassName: string } | Custom class names to be used with the Cropper. Classes passed via the classes prop are merged with the defaults. If you have CSS specificity issues, you should probably use the disableAutomaticStylesInjection prop. | |
mediaProps | object | The properties you want to apply to the media tag ( | |
cropperProps | object | The properties you want to apply to the cropper. | |
restrictPosition | boolean | Whether the position of the media should be restricted to the boundaries of the cropper. Useful setting in case of zoom < 1 or if the cropper should preserve all media content while forcing a specific aspect ratio for media throughout the application. Example: https://codesandbox.io/s/1rmqky233q. | |
initialCroppedAreaPercentages | { width: number, height: number, x: number, y: number} | Use this to set the initial crop position/zoom of the cropper (for example, when editing a previously cropped media). The value should be the same as the croppedArea passed to onCropComplete. This is the preferred way of restoring the previously set crop because croppedAreaPixels is rounded, and when used for restoration, may result in a slight drifting crop/zoom | |
initialCroppedAreaPixels | { width: number, height: number, x: number, y: number} | Use this to set the initial crop position/zoom of the cropper (for example, when editing a previously cropped media). The value should be the same as the croppedAreaPixels passed to onCropComplete Example: https://codesandbox.io/s/pmj19vp2yx. | |
onInteractionStart | Function | Called every time a user starts a wheel, touch, mousedown or keydown (for arrow keys only) event. | |
onInteractionEnd | Function | Called every time a user ends a wheel, touch, mousedown or keydown (for arrow keys only) event. | |
onMediaLoaded | Function | Called when media gets loaded. Gets passed an mediaSize object like { width, height, naturalWidth, naturalHeight } | |
onTouchRequest | (e: React.TouchEvent<HTMLDivElement>) => boolean | Can be used to cancel a touch request by returning false. | |
onWheelRequest | (e: WheelEvent) => boolean | Can be used to cancel a zoom with wheel request by returning false. | |
disableAutomaticStylesInjection | boolean | Whether to auto inject styles using a style tag in the document head on component mount. When disabled you need to import the css file into your application manually (style file is available in react-easy-crop/react-easy-crop.css). Example with sass/scss @import "~react-easy-crop/react-easy-crop";. | |
setCropperRef | (ref: React.RefObject<HTMLDivElement>) => void | Called when the component mounts, if present. Used to set the value of the cropper ref object in the parent component. | |
setImageRef | (ref: React.RefObject<HTMLImageElement>) => void | Called when the component mounts, if present. Used to set the value of the image ref object in the parent component. | |
setVideoRef | (ref: React.RefObject<HTMLVideoElement>) => void | Called when the component mounts, if present. Used to set the value of the video ref object in the parent component. | |
setMediaSize | (size: MediaSize) => void | [Advanced Usage] Used to expose the mediaSize value for use with the getInitialCropFromCroppedAreaPixels and getInitialCropFromCroppedAreaPercentages functions. See this CodeSandbox instance for a simple example. | |
setCropSize | (size: Size) => void | [Advanced Usage] Used to expose the cropSize value for use with the getInitialCropFromCroppedAreaPixels and getInitialCropFromCroppedAreaPercentages functions. See this CodeSandbox instance for a simple example. | |
nonce | string | The nonce to add to the style tag when the styles are auto injected. | |
keyboardStep | number | number of pixels the crop area moves with each press of an arrow key when using keyboard navigation. Defaults to 1. |
This callback is the one you should use to save the cropped area of the media. It's passed 2 arguments:
croppedArea: coordinates and dimensions of the cropped area in percentage of the media dimensioncroppedAreaPixels: coordinates and dimensions of the cropped area in pixels.Both arguments have the following shape:
const area = {
x: number, // x/y are the coordinates of the top/left corner of the cropped area
y: number,
width: number, // width of the cropped area
height: number, // height of the cropped area
}
This is the exact same callback as onCropComplete, but is triggered for all user interactions.
It can be used if you are not performing any render action on it.
croppedArea: coordinates and dimensions of the cropped area in percentage of the media dimensioncroppedAreaPixels: coordinates and dimensions of the cropped area in pixels.Both arguments have the following shape:
const area = {
x: number, // x/y are the coordinates of the top/left corner of the cropped area
y: number,
width: number, // width of the cropped area
height: number, // height of the cropped area
}
Called when media gets successfully loaded. This is useful if you want to have a custom zoom/crop strategy based on media size.
Example:
const CONTAINER_HEIGHT = 300
const CroppedImage = ({ image }) => {
const [crop, onCropChange] = React.useState({ x: 0, y: 0 })
const [zoom, onZoomChange] = React.useState(1)
return (
<Cropper
image={image}
crop={crop}
zoom={zoom}
onCropChange={onCropChange}
onZoomChange={onZoomChange}
onMediaLoaded={(mediaSize) => {
// Adapt zoom based on media size to fit max height
onZoomChange(CONTAINER_HEIGHT / mediaSize.naturalHeight)
}}
/>
)
}
[Advanced Usage]
Used to calculate values for crop and zoom based on a desired croppedAreaPercentages
value. See this CodeSandbox instance for a simple example.
[Advanced Usage]
See getInitialCropFromCroppedAreaPercentages.
yarn
yarn start
Now, open http://localhost:3001/index.html and start hacking!
This project is maintained by Valentin Hervieu.
This project was originally part of @ricardo-ch organisation because I (Valentin) was working at Ricardo. After leaving this company, they gracefully accepted to transfer the project to me. ❤️
Thanks goes to these wonderful people (emoji key):
This project follows the all-contributors specification. Contributions of any kind welcome!