@crafing/react-image-crop
v0.1.2
Published
React state wrapper for lego-image cropper (no UI — host apps render the canvas)
Maintainers
Readme
@crafing/react-image-crop
Complete React integration guide for beginners.
This package gives you a React hook: useImageCrop.
It connects a <canvas> to an image cropper (pan, zoom, rotate, export) and keeps the transform in React state.
It does not draw buttons, sliders, or a layout. You build the UI. The hook is the controller.
Live demo
Try the free browser cropper (same engine this package wraps):
Table of contents
- What you get
- Install
- Important rules (read first)
- Minimal working app (copy-paste)
- Step-by-step integration
- Load an image (first time)
- Save transform to a database
- Restore a saved edit
- Zoom, rotate, reset, frame size
- Export the cropped image
- Optional: CSS / DOM preview
- Upload from a file input
- Full API reference
- Data format reference
- Common mistakes
1. What you get
Your React app
├── Toolbar (zoom, rotate, save) ← you write
├── <canvas> inside a frame div ← you write
└── useImageCrop() ← this package| Included | Not included |
|----------|--------------|
| useImageCrop hook | Crop UI chrome |
| Transform helpers (fractions ↔ pixels) | File upload widgets |
| Bind to your canvas via canvasRef | CSS themes |
2. Install
npm install @crafing/react-image-cropPeer dependency: React 18+. Depends on lego-image.
3. Important rules (read first)
- You must render a
<canvas>and attachcanvasRefto it. - Do not set React
width/heightprops on<canvas>.
The cropper sets the bitmap size fromframeSize/setFrameSize. - Wrap the canvas in a box with fixed CSS size and
overflow: hiddenmatching the frame. - Call
setLego(...)only afterready === true(canvas is bound). - Save the
transformobject fromonChange, not random pixel values, if you want perfect restore later.
4. Minimal working app (copy-paste)
Replace src/App.jsx with:
import { useEffect, useState } from "react";
import { useImageCrop } from "@crafing/react-image-crop";
const FRAME = { width: 600, height: 600 };
// Public sample image — replace with your URL
const DEMO_URL = "https://picsum.photos/1200/800";
export default function App() {
const [savedTransform, setSavedTransform] = useState(null);
const {
canvasRef,
ready,
loaded,
error,
transform,
setLego,
zoomIn,
zoomOut,
rotateLeft,
rotateRight,
resetImage,
getCanvasDataUrl,
} = useImageCrop({
onChange: (values) => {
// Called whenever the user pans / zooms / rotates
setSavedTransform(values);
},
});
// Load image once the canvas is ready
useEffect(() => {
if (!ready) return;
setLego({
imageUrl: DEMO_URL,
imageType: "image/jpeg",
frameSize: FRAME,
// no transform → default cover fit
}).catch((err) => {
console.error(err);
});
}, [ready, setLego]);
function downloadCrop() {
const dataUrl = getCanvasDataUrl();
if (!dataUrl) {
alert("Nothing to export yet");
return;
}
const a = document.createElement("a");
a.href = dataUrl;
a.download = "crop.png";
a.click();
}
return (
<div style={{ fontFamily: "system-ui", padding: 16, maxWidth: 720 }}>
<h1>Image crop demo</h1>
{error ? (
<p style={{ color: "crimson" }}>Error: {error}</p>
) : null}
<p>
Status: {ready ? "ready" : "waiting for canvas"} ·{" "}
{loaded ? "image loaded" : "no image yet"}
</p>
{/* Frame box — size must match frameSize */}
<div
style={{
width: FRAME.width,
height: FRAME.height,
overflow: "hidden",
border: "1px solid #ccc",
background: "#111",
}}
>
<canvas ref={canvasRef} />
</div>
<div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginTop: 12 }}>
<button type="button" onClick={zoomIn} disabled={!loaded}>
Zoom in
</button>
<button type="button" onClick={zoomOut} disabled={!loaded}>
Zoom out
</button>
<button type="button" onClick={rotateLeft} disabled={!loaded}>
Rotate left
</button>
<button type="button" onClick={rotateRight} disabled={!loaded}>
Rotate right
</button>
<button type="button" onClick={resetImage} disabled={!loaded}>
Reset
</button>
<button type="button" onClick={downloadCrop} disabled={!loaded}>
Download crop
</button>
</div>
<h2>Current transform (save this)</h2>
<pre style={{ background: "#f4f4f5", padding: 12, overflow: "auto" }}>
{JSON.stringify(transform || savedTransform, null, 2)}
</pre>
<p style={{ color: "#666", fontSize: 14 }}>
Tip: hold <kbd>Ctrl</kbd> (or <kbd>Cmd</kbd>) and scroll on the canvas to zoom.
Drag on the canvas to pan.
</p>
</div>
);
}How to try it
- Install from npm:
npm install @crafing/react-image-crop - Paste the code into your React app.
- You should see an image inside a 600×600 box.
- Drag to pan, Ctrl+scroll to zoom, use the buttons.
- Click Download crop to get a flattened image file.
If that works, integration is correct.
5. Step-by-step integration
Step 1 — Import
import { useImageCrop } from "@crafing/react-image-crop";Step 2 — Call the hook
const {
canvasRef,
ready,
setLego,
zoomIn,
// ...
} = useImageCrop({
onChange: (transform) => {
// optional: autosave
},
});Step 3 — Put a canvas in the page
<div style={{ width: 600, height: 600, overflow: "hidden" }}>
<canvas ref={canvasRef} />
</div>Step 4 — When ready is true, load an image
useEffect(() => {
if (!ready) return;
setLego({
imageUrl: "https://example.com/photo.png",
imageType: "image/png",
frameSize: { width: 600, height: 600 },
});
}, [ready, setLego]);Step 5 — Add your buttons
<button type="button" onClick={zoomIn}>Zoom in</button>Done.
6. Load an image (first time)
Omit transform so the cropper applies cover fit (image fills the frame).
await setLego({
imageUrl: "https://cdn.example.com/user-photo.jpg",
imageType: "image/jpeg",
frameSize: { width: 600, height: 600 },
});imageUrl can be:
https://...URL- Blob URL (
URL.createObjectURL(file)) - Data URL (
data:image/png;base64,...)
7. Save transform to a database
onChange gives you fractions relative to the frame. Store them as-is.
const [record, setRecord] = useState({
imageUrl: "",
imageType: "image/jpeg",
frameSize: { width: 600, height: 600 },
transform: null,
});
const { setLego, ready } = useImageCrop({
onChange: (values) => {
const next = {
...record,
transform: {
x: values.x,
y: values.y,
width: values.width,
height: values.height,
rotate: values.rotate,
scale: values.scale,
},
};
setRecord(next);
// debounce + POST to your API
// await fetch("/api/crops", { method: "POST", body: JSON.stringify(next) })
},
});Example JSON in the database:
{
"imageUrl": "https://cdn.example.com/uploads/user-123.jpg",
"imageType": "image/jpeg",
"frameSize": { "width": 600, "height": 600 },
"transform": {
"x": 0.32,
"y": -0.15,
"width": 1.6,
"height": 1.6,
"rotate": 45,
"scale": 0
}
}8. Restore a saved edit
Pass the same object back into setLego:
useEffect(() => {
if (!ready || !saved?.imageUrl) return;
setLego({
imageUrl: saved.imageUrl,
imageType: saved.imageType,
frameSize: saved.frameSize,
transform: saved.transform,
});
}, [ready, saved, setLego]);9. Zoom, rotate, reset, frame size
const {
zoomIn,
zoomOut,
zoomToScale,
getZoomLimits,
rotateTo,
rotateBy,
rotateLeft,
rotateRight,
resetImage,
setFrameSize,
getFrameSize,
} = useImageCrop();
zoomIn();
zoomOut();
zoomToScale(1.2); // 0 = cover minimum
const limits = getZoomLimits(); // { min, max, scale, ... }
rotateTo(45);
rotateBy(15);
rotateLeft(); // -90°
rotateRight(); // +90°
resetImage(); // back to cover fit
await setFrameSize(800, 400);
const size = getFrameSize(); // { width, height }When the frame size changes, keep your outer CSS box in sync:
const [frame, setFrame] = useState({ width: 600, height: 600 });
await setFrameSize(800, 400);
setFrame({ width: 800, height: 400 });
<div style={{ width: frame.width, height: frame.height, overflow: "hidden" }}>
<canvas ref={canvasRef} />
</div>10. Export the cropped image
const { getCanvasDataUrl, getExportMimeType, getSourceMimeType } =
useImageCrop();
// Auto format (PNG stays PNG, JPEG stays JPEG when possible)
const dataUrl = getCanvasDataUrl();
// Force JPEG
const jpeg = getCanvasDataUrl("image/jpeg", 0.92);
const mime = getExportMimeType();
const sourceMime = getSourceMimeType();Upload example:
async function uploadCrop() {
const dataUrl = getCanvasDataUrl();
const res = await fetch(dataUrl);
const blob = await res.blob();
const form = new FormData();
form.append("file", blob, "crop.png");
await fetch("/api/upload", { method: "POST", body: form });
}11. Optional: CSS / DOM preview
Sometimes you want an <img> that mirrors the crop (for a lighter UI).
Use the helpers — they convert fractions → pixels.
import {
useImageCrop,
transformToPixels,
pixelsToCssTransform,
} from "@crafing/react-image-crop";
const { transform, frameSize } = useImageCrop({ onChange: () => {} });
const px =
transform && frameSize
? transformToPixels(transform, frameSize.width, frameSize.height)
: null;
{px ? (
<img
alt=""
src={imageUrl}
style={{
position: "absolute",
left: 0,
top: 0,
width: px.width,
height: px.height,
transformOrigin: "0 0",
objectFit: "contain",
transform: pixelsToCssTransform(px),
}}
/>
) : null}| Helper | Purpose |
|--------|---------|
| transformToPixels(transform, frameW, frameH) | Fractions → { left, top, width, height, rotate, scale } |
| pixelsToTransform(px, frameW, frameH) | Opposite direction |
| pixelsToCssTransform(px) | translate(...) rotate(...) string |
Rule: store fractions from onChange. Convert to pixels only for CSS.
12. Upload from a file input
function onFileChange(e) {
const file = e.target.files?.[0];
if (!file || !ready) return;
const reader = new FileReader();
reader.onload = async () => {
await setLego({
imageUrl: reader.result, // data URL
imageType: file.type,
frameSize: { width: 600, height: 600 },
});
};
reader.readAsDataURL(file);
}
<input type="file" accept="image/*" onChange={onFileChange} />Or with a blob URL:
const url = URL.createObjectURL(file);
await setLego({
imageUrl: url,
imageType: file.type,
frameSize: { width: 600, height: 600 },
});
// later: URL.revokeObjectURL(url)13. Full API reference
useImageCrop({ onChange? })
State
| Field | Type | Meaning |
|-------|------|---------|
| canvasRef | ref | Put on <canvas ref={canvasRef} /> |
| ready | boolean | Cropper attached to canvas |
| loaded | boolean | setLego succeeded |
| error | string \| null | Last error message |
| transform | object | null | Latest onChange values |
| frameSize | { width, height } \| null | Current frame |
Methods
| Method | Description |
|--------|-------------|
| setLego(conf) | Load / restore (Promise) |
| resetImage() | Cover fit |
| zoomIn() / zoomOut() / zoomToScale(n) | Zoom |
| getZoomLimits() | Current zoom limits |
| rotateTo(deg) / rotateBy(delta) | Rotate |
| rotateLeft() / rotateRight() | ±90° |
| setFrameSize(w, h) | Resize frame (Promise) |
| getFrameSize() | Current frame size |
| getImageSize() | Source image size if available |
| getCanvasDataUrl(type?, quality?) | Export data URL |
| getSourceMimeType() | Source MIME |
| getExportMimeType() | Export MIME |
controllerProps
{ canvasRef }14. Data format reference
setLego config
| Field | Required | Description |
|-------|----------|-------------|
| imageUrl | yes | URL / blob URL / data URL |
| imageType | no | MIME type |
| frameSize | no | { width, height } in pixels |
| transform | no | Saved edit; omit for cover fit |
transform fields
| Field | Meaning |
|-------|---------|
| x, y | Visual top-left as fraction of frame size |
| width, height | Drawn image size as fraction of frame |
| rotate | Degrees around frame center |
| scale | Extra zoom above cover; 0 = minimum cover |
15. Common mistakes
No
<canvas ref={canvasRef} />
The hook cannot start.readystays false.Calling
setLegobeforeready
Wait forready === true(usually in auseEffect).Setting
<canvas width={600} height={600}>as React props
That clears/resizes the bitmap incorrectly. UseframeSize/setFrameSizeinstead, and size the wrapper div with CSS.Wrapper div size ≠ frameSize
The visible crop area will look wrong. Keep them equal.Saving pixels instead of fractions
Restore will break when the frame size changes. SavetransformfromonChange.Expecting a full crop UI from the package
There is none — only the hook. Buttons and layout are yours.
License
MIT
