Image cropper
Pan and zoom an image under a fixed-aspect or circle crop frame, then read the crop rect in image pixels or export a data URL.
pnpm dlx shadcn@latest add @haze/image-cropper---
import { cn } from "../../../lib/haze/utils";
import Slider from "./slider.astro";
interface Props {
id: string;
label?: string;
/** Width divided by height of the crop frame. */
aspect?: number;
shape?: "rect" | "circle";
src?: string;
maxZoom?: number;
class?: string;
[key: string]: unknown;
}
const { id, label = "Crop image", aspect = 1, shape = "rect", src, maxZoom = 3, class: className, ...rest } = Astro.props;
const ratio = Number.isFinite(aspect) && aspect > 0 ? aspect : 1;
const top = Number.isFinite(maxZoom) && maxZoom > 1 ? maxZoom : 3;
const circle = shape === "circle";
---
<div id={id} data-haze-image-cropper data-aspect={ratio} data-max-zoom={top} data-shape={shape} data-src={src} class={cn("grid w-full min-w-0 gap-3", className)} {...rest}>
<div
data-crop-stage
role="group"
tabindex="0"
aria-label={label}
aria-describedby={`${id}-help`}
class="group/stage relative aspect-[4/3] w-full touch-none overflow-hidden rounded-xl border border-border bg-muted select-none focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring data-[dragging]:cursor-grabbing data-[ready]:cursor-grab"
>
<p data-crop-empty class="absolute inset-0 grid place-items-center p-4 text-center text-[0.8125rem]/5 text-muted-foreground [[data-ready]_&]:hidden">No image loaded</p>
<img data-crop-image alt="" width="1" height="1" draggable="false" hidden class="pointer-events-none absolute top-0 left-0 max-w-none origin-top-left" />
<div data-crop-frame aria-hidden="true" hidden class={cn("pointer-events-none absolute inset-0 m-auto border border-foreground/70 outline-[100vmax] outline-solid outline-background/70", circle && "rounded-full")}>
<div class="absolute inset-y-0 left-1/3 border-l border-border opacity-0 transition-opacity duration-150 ease-snappy group-data-[dragging]/stage:opacity-100 motion-reduce:transition-none"></div>
<div class="absolute inset-y-0 left-2/3 border-l border-border opacity-0 transition-opacity duration-150 ease-snappy group-data-[dragging]/stage:opacity-100 motion-reduce:transition-none"></div>
<div class="absolute inset-x-0 top-1/3 border-t border-border opacity-0 transition-opacity duration-150 ease-snappy group-data-[dragging]/stage:opacity-100 motion-reduce:transition-none"></div>
<div class="absolute inset-x-0 top-2/3 border-t border-border opacity-0 transition-opacity duration-150 ease-snappy group-data-[dragging]/stage:opacity-100 motion-reduce:transition-none"></div>
{!circle && <div class="absolute -top-[3px] -left-[3px] size-5 border-t-2 border-l-2 border-foreground"></div>}
{!circle && <div class="absolute -top-[3px] -right-[3px] size-5 border-t-2 border-r-2 border-foreground"></div>}
{!circle && <div class="absolute -bottom-[3px] -left-[3px] size-5 border-b-2 border-l-2 border-foreground"></div>}
{!circle && <div class="absolute -right-[3px] -bottom-[3px] size-5 border-r-2 border-b-2 border-foreground"></div>}
</div>
</div>
<p id={`${id}-help`} class="text-xs text-muted-foreground">Drag the image to move it. Scroll or pinch to zoom. With the area focused, use the arrow keys to move (Shift for larger steps), plus and minus to zoom, and 0 to reset.</p>
<div class="flex min-w-0 items-center gap-3">
<label for={`${id}-zoom`} class="shrink-0 text-[0.8125rem]/5 font-medium text-foreground">Zoom</label>
<Slider id={`${id}-zoom`} name={`${id}-zoom`} min={1} max={top} step={0.01} value={1} class="min-w-0 flex-1" data-crop-zoom />
<button type="button" data-crop-reset class="min-h-8 shrink-0 cursor-pointer rounded-lg border border-frame bg-field px-3 text-[0.8125rem]/5 font-medium text-foreground shadow-key transition-[background-color,scale] duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-[0.97] active:duration-75 motion-reduce:transition-none motion-reduce:active:scale-100">Reset</button>
</div>
<p data-crop-status role="status" class="sr-only data-[error]:not-sr-only data-[error]:text-xs data-[error]:text-destructive"></p>
</div>
<script>
function enhance(root: HTMLElement & { load?: (src: string) => void; getCrop?: () => unknown; toDataURL?: (type?: string, maxSize?: number) => string }) {
if (root.hasAttribute("data-enhanced")) return;
const stage = root.querySelector<HTMLElement>("[data-crop-stage]");
const img = root.querySelector<HTMLImageElement>("[data-crop-image]");
const frame = root.querySelector<HTMLElement>("[data-crop-frame]");
const slider = root.querySelector<HTMLInputElement>("[data-crop-zoom]");
const status = root.querySelector<HTMLElement>("[data-crop-status]");
if (!stage || !img || !frame || !slider || !status) return;
const aspect = Number(root.dataset.aspect) || 1, maxZoom = Number(root.dataset.maxZoom) || 3;
const circle = root.dataset.shape === "circle";
let syncing = false, nw = 0, nh = 0, zoom = 1, cx = 0, cy = 0, fw = 0, fh = 0, sw = 0, sh = 0, timer = 0;
const pointers = new Map<number, { x: number; y: number }>();
const scale = () => Math.max(fw / nw, fh / nh) * zoom;
const rect = () => { const s = scale(); return { x: Math.round(cx - fw / 2 / s), y: Math.round(cy - fh / 2 / s), width: Math.round(fw / s), height: Math.round(fh / s) }; };
const apply = () => {
if (!nw) return;
const s = scale();
cx = Math.min(nw - fw / 2 / s, Math.max(fw / 2 / s, cx)); cy = Math.min(nh - fh / 2 / s, Math.max(fh / 2 / s, cy));
img.style.width = `${nw * s}px`; img.style.height = `${nh * s}px`; img.style.translate = `${sw / 2 - cx * s}px ${sh / 2 - cy * s}px`;
syncing = true; slider.value = String(zoom); slider.dispatchEvent(new Event("input")); syncing = false;
root.dispatchEvent(new CustomEvent("haze:crop-change", { bubbles: true, detail: { ...rect(), zoom } }));
clearTimeout(timer);
timer = window.setTimeout(() => { status.removeAttribute("data-error"); const r = rect(); status.textContent = `Crop ${r.width} by ${r.height} pixels, zoom ${Math.round(zoom * 100)} percent.`; }, 250);
};
const layout = () => {
sw = stage.clientWidth; sh = stage.clientHeight;
fw = Math.min(sw - 32, (sh - 32) * aspect); fh = fw / aspect;
frame.style.width = `${fw}px`; frame.style.height = `${fh}px`;
apply();
};
const setZoom = (value: number) => { zoom = Math.min(maxZoom, Math.max(1, value)); apply(); };
const reset = () => { cx = nw / 2; cy = nh / 2; setZoom(1); };
root.load = (src: string) => {
const probe = new Image();
probe.onerror = () => { clearTimeout(timer); status.setAttribute("data-error", ""); status.textContent = "This image could not be loaded. The previous image is kept."; };
probe.onload = () => {
status.removeAttribute("data-error"); status.textContent = "";
img.onload = () => { nw = img.naturalWidth; nh = img.naturalHeight; img.hidden = frame.hidden = false; stage.setAttribute("data-ready", ""); layout(); reset(); };
img.src = src;
};
probe.src = src;
};
root.getCrop = () => ({ ...rect(), zoom });
root.toDataURL = (type = "image/png", maxSize = 1024) => {
const r = rect(), k = Math.min(1, maxSize / Math.max(r.width, r.height));
const canvas = document.createElement("canvas"); canvas.width = Math.max(1, Math.round(r.width * k)); canvas.height = Math.max(1, Math.round(r.height * k));
const context = canvas.getContext("2d"); if (!context || !nw) return "";
if (circle) { context.beginPath(); context.ellipse(canvas.width / 2, canvas.height / 2, canvas.width / 2, canvas.height / 2, 0, 0, Math.PI * 2); context.clip(); }
context.drawImage(img, r.x, r.y, r.width, r.height, 0, 0, canvas.width, canvas.height);
return canvas.toDataURL(type);
};
stage.addEventListener("pointerdown", (event) => {
if (!nw || (event.pointerType === "mouse" && event.button !== 0)) return;
stage.setPointerCapture(event.pointerId); pointers.set(event.pointerId, { x: event.clientX, y: event.clientY }); stage.setAttribute("data-dragging", "");
});
const spread = () => { const [a, b] = [...pointers.values()]; return b ? Math.hypot(b.x - a.x, b.y - a.y) : 0; };
stage.addEventListener("pointermove", (event) => {
const last = pointers.get(event.pointerId); if (!last) return;
const before = spread();
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
if (pointers.size === 2) {
if (before > 0) setZoom(zoom * (spread() / before));
} else { const s = scale(); cx -= (event.clientX - last.x) / s; cy -= (event.clientY - last.y) / s; apply(); }
});
const release = (event: PointerEvent) => { pointers.delete(event.pointerId); if (!pointers.size) stage.removeAttribute("data-dragging"); };
stage.addEventListener("pointerup", release); stage.addEventListener("pointercancel", release);
stage.addEventListener("wheel", (event) => { if (!nw) return; event.preventDefault(); setZoom(zoom * Math.exp(-event.deltaY * 0.002)); }, { passive: false });
stage.addEventListener("keydown", (event) => {
if (!nw) return;
const step = (event.shiftKey ? 50 : 10) / scale(), moves: Record<string, [number, number]> = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] };
if (event.key in moves) { cx += moves[event.key][0]; cy += moves[event.key][1]; apply(); }
else if (event.key === "+" || event.key === "=") setZoom(zoom + 0.1);
else if (event.key === "-" || event.key === "_") setZoom(zoom - 0.1);
else if (event.key === "0") reset();
else return;
event.preventDefault();
});
slider.addEventListener("input", () => { if (!syncing) setZoom(slider.valueAsNumber); });
root.querySelector<HTMLButtonElement>("[data-crop-reset]")?.addEventListener("click", reset);
new ResizeObserver(() => nw && layout()).observe(stage);
root.setAttribute("data-enhanced", "");
if (root.dataset.src) root.load(root.dataset.src);
root.dispatchEvent(new CustomEvent("haze:cropper-ready", { bubbles: true }));
}
const init = () => document.querySelectorAll<HTMLElement>("[data-haze-image-cropper]").forEach(enhance);
init();
if (!document.documentElement.hasAttribute("data-haze-image-cropper-listener")) {
document.documentElement.setAttribute("data-haze-image-cropper-listener", "");
document.addEventListener("astro:page-load", init);
}
</script>When to use
- An image must be cropped to a fixed aspect ratio, such as a square cover or a round avatar, before it is saved.
- The caller needs the crop rectangle in image pixels or a canvas-rendered result.
When not to use
- Use avatar-upload when the whole flow, including the file input and a submitted PNG, is wanted for a profile photo.
- Use aspect-ratio when an image is only displayed in a fixed ratio.
- Free-form crop handles and rotation are not supported.
Installation
Add the Haze registry to components.json once, then install Image cropper with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/image-croppernpx shadcn@latest add @haze/image-cropperyarn dlx shadcn@latest add @haze/image-cropperbunx --bun shadcn@latest add @haze/image-cropperFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| id* | string | – | Unique id of the wrapper; the zoom slider and help text derive their ids from it. |
| label | string | Crop image | Accessible name of the crop area. |
| aspect | number | 1 | Width divided by height of the crop frame. |
| shape | "rect" | "circle" | rect | Frame outline; a circle also clips the exported image. |
| src | string | – | Optional image URL loaded on init. Otherwise call the load method. |
| maxZoom | number | 3 | Largest zoom, as a multiple of the size that just covers the frame. |
| class | string | – | Additional classes on this component's outer wrapper. |
| [key: string] | unknown | – | Additional attributes on the wrapper. |
Keyboard interactions
- Arrow keys
- Move the image under the frame; Shift moves further.
- +-
- Zoom in or out.
- 0
- Reset zoom and position.
- Tab
- Move to the zoom slider and Reset button.
Accessibility
- The crop area is a focusable group with an accessible name and help text that lists the keys; dragging, wheel and pinch all have keyboard and slider alternatives.
- Zoom is a native range input and a Reset button restores the starting view.
- The crop size and zoom are announced politely after changes settle.
- The script sets load(src), getCrop() and toDataURL(type, maxSize) on the wrapper element and dispatches haze:crop-change with { x, y, width, height, zoom } in image pixels. The image always covers the frame.
- The rule-of-thirds grid shows while dragging only; reduced motion removes its fade.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI component "Image cropper" with `npx shadcn@latest add @haze/image-cropper`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import ImageCropper from "@/components/haze/ui/image-cropper.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: http://localhost:4329/ui/image-cropper.md
Customize with real content
Adapt the Haze image-cropper ui for our product. Replace the demo values of these props with our real content: id, label, aspect, shape, src, maxZoom, class, [key: string]. Keep the layout, the heading level rules and these accessibility details: The crop area is a focusable group with an accessible name and help text that lists the keys; dragging, wheel and pinch all have keyboard and slider alternatives. Zoom is a native range input and a Reset button restores the starting view. The crop size and zoom are announced politely after changes settle. The script sets load(src), getCrop() and toDataURL(type, maxSize) on the wrapper element and dispatches haze:crop-change with { x, y, width, height, zoom } in image pixels. The image always covers the frame. The rule-of-thirds grid shows while dragging only; reduced motion removes its fade. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using image-cropper, check it fits: use it when an image must be cropped to a fixed aspect ratio, such as a square cover or a round avatar, before it is saved.; the caller needs the crop rectangle in image pixels or a canvas-rendered result.. Avoid it when use avatar-upload when the whole flow, including the file input and a submitted png, is wanted for a profile photo.; use aspect-ratio when an image is only displayed in a fixed ratio.; free-form crop handles and rotation are not supported.. Alternatives: @haze/avatar-upload, @haze/aspect-ratio, @haze/slider, @haze/file-upload.
Dependencies
- @haze/slider
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.