npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@crafing/react-image-crop

v0.1.2

Published

React state wrapper for lego-image cropper (no UI — host apps render the canvas)

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):

Image crop on Crafing


Table of contents

  1. What you get
  2. Install
  3. Important rules (read first)
  4. Minimal working app (copy-paste)
  5. Step-by-step integration
  6. Load an image (first time)
  7. Save transform to a database
  8. Restore a saved edit
  9. Zoom, rotate, reset, frame size
  10. Export the cropped image
  11. Optional: CSS / DOM preview
  12. Upload from a file input
  13. Full API reference
  14. Data format reference
  15. 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-crop

Peer dependency: React 18+. Depends on lego-image.


3. Important rules (read first)

  1. You must render a <canvas> and attach canvasRef to it.
  2. Do not set React width / height props on <canvas>.
    The cropper sets the bitmap size from frameSize / setFrameSize.
  3. Wrap the canvas in a box with fixed CSS size and overflow: hidden matching the frame.
  4. Call setLego(...) only after ready === true (canvas is bound).
  5. Save the transform object from onChange, 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

  1. Install from npm: npm install @crafing/react-image-crop
  2. Paste the code into your React app.
  3. You should see an image inside a 600×600 box.
  4. Drag to pan, Ctrl+scroll to zoom, use the buttons.
  5. 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

  1. No <canvas ref={canvasRef} />
    The hook cannot start. ready stays false.

  2. Calling setLego before ready
    Wait for ready === true (usually in a useEffect).

  3. Setting <canvas width={600} height={600}> as React props
    That clears/resizes the bitmap incorrectly. Use frameSize / setFrameSize instead, and size the wrapper div with CSS.

  4. Wrapper div size ≠ frameSize
    The visible crop area will look wrong. Keep them equal.

  5. Saving pixels instead of fractions
    Restore will break when the frame size changes. Save transform from onChange.

  6. Expecting a full crop UI from the package
    There is none — only the hook. Buttons and layout are yours.


License

MIT