Navigation

v2.1.0
Media

Cropper

A picture with a box over it that says what to keep.

On this page

A cropper is a picture with a box over it that says what to keep: a photo cropped before it is posted, a cover trimmed to a banner's proportions, an avatar framed in a circle. The picture rests in a well. What lies outside the box is dimmed, the box's edge is the white line drawn over a picture, and its handles are pearl discs at the corners and pills on the edges. While the box is held, or keyed, the rule of thirds shows inside it.

Cropper

<div class="cropper max-w(480) mx-auto" style="--cropper-x: .16; --cropper-y: .14; --cropper-width: .62; --cropper-height: .66">  <img class="cropper-image" src="/demo/harbor.svg" alt="A harbor at dusk" width="640" height="480">  <div class="cropper-box" role="application" aria-roledescription="crop box" tabindex="0" aria-label="Crop the photo">    <span class="cropper-handle cropper-handle-top cropper-handle-left"></span>    <span class="cropper-handle cropper-handle-top"></span>    <span class="cropper-handle cropper-handle-top cropper-handle-right"></span>    <span class="cropper-handle cropper-handle-right"></span>    <span class="cropper-handle cropper-handle-bottom cropper-handle-right"></span>    <span class="cropper-handle cropper-handle-bottom"></span>    <span class="cropper-handle cropper-handle-bottom cropper-handle-left"></span>    <span class="cropper-handle cropper-handle-left"></span>  </div>  <p class="cropper-status" role="status"></p></div><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach } from '@master/ui/behaviors'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => attach(root.current!), [])  return (    <div ref={root} className="cropper max-w(480) mx-auto" style={{ '--cropper-x': '.16', '--cropper-y': '.14', '--cropper-width': '.62', '--cropper-height': '.66' } as React.CSSProperties}>      <img className="cropper-image" src="/demo/harbor.svg" alt="A harbor at dusk" width="640" height="480" />      <div className="cropper-box" role="application" aria-roledescription="crop box" tabIndex={0} aria-label="Crop the photo">        <span className="cropper-handle cropper-handle-top cropper-handle-left"></span>        <span className="cropper-handle cropper-handle-top"></span>        <span className="cropper-handle cropper-handle-top cropper-handle-right"></span>        <span className="cropper-handle cropper-handle-right"></span>        <span className="cropper-handle cropper-handle-bottom cropper-handle-right"></span>        <span className="cropper-handle cropper-handle-bottom"></span>        <span className="cropper-handle cropper-handle-bottom cropper-handle-left"></span>        <span className="cropper-handle cropper-handle-left"></span>      </div>      <p className="cropper-status" role="status"></p>    </div>  )}
<script>  import { attach } from '@master/ui/behaviors'</script><div class="cropper max-w(480) mx-auto" style="--cropper-x: .16; --cropper-y: .14; --cropper-width: .62; --cropper-height: .66" {@attach attach}>  <img class="cropper-image" src="/demo/harbor.svg" alt="A harbor at dusk" width="640" height="480">  <div class="cropper-box" role="application" aria-roledescription="crop box" tabindex="0" aria-label="Crop the photo">    <span class="cropper-handle cropper-handle-top cropper-handle-left"></span>    <span class="cropper-handle cropper-handle-top"></span>    <span class="cropper-handle cropper-handle-top cropper-handle-right"></span>    <span class="cropper-handle cropper-handle-right"></span>    <span class="cropper-handle cropper-handle-bottom cropper-handle-right"></span>    <span class="cropper-handle cropper-handle-bottom"></span>    <span class="cropper-handle cropper-handle-bottom cropper-handle-left"></span>    <span class="cropper-handle cropper-handle-left"></span>  </div>  <p class="cropper-status" role="status"></p></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach } from '@master/ui/behaviors'const root = ref(null)let detachonMounted(() => { detach = attach(root.value) })onUnmounted(() => detach?.())</script><template>  <div ref="root" class="cropper max-w(480) mx-auto" style="--cropper-x: .16; --cropper-y: .14; --cropper-width: .62; --cropper-height: .66">    <img class="cropper-image" src="/demo/harbor.svg" alt="A harbor at dusk" width="640" height="480">    <div class="cropper-box" role="application" aria-roledescription="crop box" tabindex="0" aria-label="Crop the photo">      <span class="cropper-handle cropper-handle-top cropper-handle-left"></span>      <span class="cropper-handle cropper-handle-top"></span>      <span class="cropper-handle cropper-handle-top cropper-handle-right"></span>      <span class="cropper-handle cropper-handle-right"></span>      <span class="cropper-handle cropper-handle-bottom cropper-handle-right"></span>      <span class="cropper-handle cropper-handle-bottom"></span>      <span class="cropper-handle cropper-handle-bottom cropper-handle-left"></span>      <span class="cropper-handle cropper-handle-left"></span>    </div>    <p class="cropper-status" role="status"></p>  </div></template>
Drag the box or a handle, or draw a new box across the picture. Focus the box and use the arrows; Alt with an arrow sizes it.

The geometry is four custom properties on the root, each a share of the picture from 0 to 1: --cropper-x and --cropper-y from its top left corner, --cropper-width and --cropper-height. The stylesheet places the box from them, and the dim follows the box. Without a script the box stays where they put it, the whole picture when they are left out.

The value an application reads is the same rectangle in the picture's own pixels, { x, y, width, height }. Cutting the picture is the application's: see cutting the picture.

#The behavior

cropper takes the root, the element with the cropper class, and an object of options, and returns the function that detaches it. Its value is the crop; set it to move the crop from outside, which dispatches nothing.

app.js
import { cropper } from '@master/ui/behaviors/cropper.js'const root = document.querySelector('.cropper')const crop = cropper(root, { ratio: 16 / 9 })root.addEventListener('change', () => {  const { x, y, width, height } = crop.value  form.elements.crop.value = [x, y, width, height].join(' ')})
  • The box. A drag of the box moves it, a drag of a handle moves the edges the handle names, and a drag across the picture outside the box draws a new one. A press there without a drag brings the box to it, so the box can be moved without dragging. The box stays inside the picture and keeps a least size.
  • The picture's pixels. The crop is counted in the width and height of cropper-image. Write the file's own size there: it is also what keeps the frame from moving while the picture loads.
  • The keys. The arrows move the crop by a step, ten steps with Shift. With Alt (Option on a Mac) they size it from its far edges: right and down larger, left and up smaller.
  • Events. The box dispatches input each time the crop changes and change once a drag or a key has ended. Both bubble.
  • What is said. After each change the behavior writes the crop's size into cropper-status, a polite live region: "480 by 270 pixels, 64 from the left and 96 from the top". Pass describe to say it in the page's language.

A picture has no direction, so the box is placed from the left and the top, and the arrows mean left and right, in every writing direction.

OptionWhat it sets
ratioWidth over height the box keeps, such as 16 / 9. Free when left out, unless the root's style writes --cropper-ratio; 0 makes it free
stepHow far an arrow moves the crop, in the picture's pixels. A hundredth of its longer side by default
minThe least width and height, in the picture's pixels. A tenth of its shorter side by default
maxZoomHow far a panned cropper zooms when no range input says so. 4 by default
describeA function from the crop to the words the status says

cropperFit(picture, crop, options), from the same module, fits a crop to a picture as the behavior holds it. A renderer uses it to draw the first crop on a server.

#Proportions

With a ratio, a corner's handle keeps the corner across from it and the box keeps its proportions; an edge's handle sizes the box about its middle. When the behavior is attached with a ratio the box does not have, it gives the box that ratio about its middle, at the same area, and says input and change: that is how a choice of proportions takes effect.

Proportions

<div class="grid gap-md max-w(480) mx-auto">  <div class="segmented segmented-sm mx-auto" role="radiogroup" aria-label="Proportions">    <label class="segmented-item">      <input type="radio" class="segmented-input" name="banner-ratio" value="0" checked>Free    </label>    <label class="segmented-item">      <input type="radio" class="segmented-input" name="banner-ratio" value="1/1">1:1    </label>    <label class="segmented-item">      <input type="radio" class="segmented-input" name="banner-ratio" value="4/3">4:3    </label>    <label class="segmented-item">      <input type="radio" class="segmented-input" name="banner-ratio" value="16/9">16:9    </label>  </div>  <div class="cropper" id="banner-crop" style="--cropper-x: .1; --cropper-y: .2; --cropper-width: .8; --cropper-height: .6">    <img class="cropper-image" src="/demo/tide.svg" alt="The tide coming in over flat sand" width="640" height="400">    <div class="cropper-box" role="application" aria-roledescription="crop box" tabindex="0" aria-label="Crop the banner">      <span class="cropper-handle cropper-handle-top cropper-handle-left"></span>      <span class="cropper-handle cropper-handle-top"></span>      <span class="cropper-handle cropper-handle-top cropper-handle-right"></span>      <span class="cropper-handle cropper-handle-right"></span>      <span class="cropper-handle cropper-handle-bottom cropper-handle-right"></span>      <span class="cropper-handle cropper-handle-bottom"></span>      <span class="cropper-handle cropper-handle-bottom cropper-handle-left"></span>      <span class="cropper-handle cropper-handle-left"></span>    </div>    <p class="cropper-status" role="status"></p>  </div>  <p class="m(0) text-sm fg-text-muted text-center" id="banner-crop-value" aria-hidden="true"></p></div><script>addEventListener('DOMContentLoaded', function () {var root = document.getElementById('banner-crop')var readout = document.getElementById('banner-crop-value')var crop = MasterUI.cropper(root)function show() {  var value = crop.value  readout.textContent = value.width + ' × ' + value.height + ' pixels at ' + value.x + ', ' + value.y}root.addEventListener('input', show)document.querySelectorAll('input[name="banner-ratio"]').forEach(function (input) {  input.addEventListener('change', function () {    var parts = input.value.split('/')    crop = MasterUI.cropper(root, { ratio: parts.length > 1 ? parts[0] / parts[1] : 0 })  })})show()})</script><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
Choose a ratio, then drag a corner or an edge. The line under the picture is the value.

A second call of cropper on one root replaces the first, so the preview attaches it again with the new ratio. MasterUI is the bundle a preview loads; in a project, import cropper as the behavior section shows. A framework component does the same when its ratio changes.

#An avatar

cropper-pan keeps the box in the middle of the frame, at the proportions of --cropper-ratio, and moves the picture under it instead: a drag pans, two fingers pinch, and the wheel zooms with Control or Command held, which is also what a trackpad's pinch sends. cropper-round draws the box as a circle. The crop's value gains zoom: 1 where the crop is as large as the picture allows.

A range input whose aria-controls names the root's id zooms it too, from its min to its max, and follows a zoom made any other way. It is the page's own slider, so it can stand under the frame, beside it or in a toolbar.

An avatar

<div class="grid gap-md w(280) mx-auto">  <div class="cropper cropper-pan cropper-round" id="avatar-crop" style="--cropper-x: .1; --cropper-y: .18; --cropper-width: .8; --cropper-height: .64">    <img class="cropper-image" src="/demo/cairn.svg" alt="A cairn of stones on a ridge" width="480" height="600">    <div class="cropper-box" role="application" aria-roledescription="crop box" tabindex="0" aria-label="Frame your picture"></div>    <p class="cropper-status" role="status"></p>  </div>  <div class="flex items-center gap-sm fg-text-muted">    <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">      <circle cx="7" cy="7" r="4.5" /><path d="M10.182 10.182L14 14" /><path d="M5 7L9 7" />    </svg>    <input type="range" class="slider grow(1)" min="1" max="4" step="any" value="1.25" aria-controls="avatar-crop" aria-label="Zoom">    <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">      <circle cx="7" cy="7" r="4.5" /><path d="M10.182 10.182L14 14" /><path d="M5 7L9 7" /><path d="M7 5L7 9" />    </svg>  </div></div><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach } from '@master/ui/behaviors'import ZoomOutIcon from '@master/icons-react/native/16/soft/zoom-out'import ZoomInIcon from '@master/icons-react/native/16/soft/zoom-in'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => attach(root.current!), [])  return (    <div ref={root} className="grid gap-md w(280) mx-auto">      <div className="cropper cropper-pan cropper-round" id="avatar-crop" style={{ '--cropper-x': '.1', '--cropper-y': '.18', '--cropper-width': '.8', '--cropper-height': '.64' } as React.CSSProperties}>        <img className="cropper-image" src="/demo/cairn.svg" alt="A cairn of stones on a ridge" width="480" height="600" />        <div className="cropper-box" role="application" aria-roledescription="crop box" tabIndex={0} aria-label="Frame your picture"></div>        <p className="cropper-status" role="status"></p>      </div>      <div className="flex items-center gap-sm fg-text-muted">        <ZoomOutIcon className="icon" />        <input type="range" className="slider grow(1)" min="1" max="4" step="any" defaultValue="1.25" aria-controls="avatar-crop" aria-label="Zoom" />        <ZoomInIcon className="icon" />      </div>    </div>  )}
<script>  import { attach } from '@master/ui/behaviors'  import ZoomOutIcon from '@master/icons-svelte/native/16/soft/zoom-out'  import ZoomInIcon from '@master/icons-svelte/native/16/soft/zoom-in'</script><div class="grid gap-md w(280) mx-auto" {@attach attach}>  <div class="cropper cropper-pan cropper-round" id="avatar-crop" style="--cropper-x: .1; --cropper-y: .18; --cropper-width: .8; --cropper-height: .64">    <img class="cropper-image" src="/demo/cairn.svg" alt="A cairn of stones on a ridge" width="480" height="600">    <div class="cropper-box" role="application" aria-roledescription="crop box" tabindex="0" aria-label="Frame your picture"></div>    <p class="cropper-status" role="status"></p>  </div>  <div class="flex items-center gap-sm fg-text-muted">    <ZoomOutIcon class="icon" />    <input type="range" class="slider grow(1)" min="1" max="4" step="any" value="1.25" aria-controls="avatar-crop" aria-label="Zoom">    <ZoomInIcon class="icon" />  </div></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach } from '@master/ui/behaviors'import ZoomOutIcon from '@master/icons-vue/native/16/soft/zoom-out'import ZoomInIcon from '@master/icons-vue/native/16/soft/zoom-in'const root = ref(null)let detachonMounted(() => { detach = attach(root.value) })onUnmounted(() => detach?.())</script><template>  <div ref="root" class="grid gap-md w(280) mx-auto">    <div class="cropper cropper-pan cropper-round" id="avatar-crop" style="--cropper-x: .1; --cropper-y: .18; --cropper-width: .8; --cropper-height: .64">      <img class="cropper-image" src="/demo/cairn.svg" alt="A cairn of stones on a ridge" width="480" height="600">      <div class="cropper-box" role="application" aria-roledescription="crop box" tabindex="0" aria-label="Frame your picture"></div>      <p class="cropper-status" role="status"></p>    </div>    <div class="flex items-center gap-sm fg-text-muted">      <ZoomOutIcon class="icon" />      <input type="range" class="slider grow(1)" min="1" max="4" step="any" value="1.25" aria-controls="avatar-crop" aria-label="Zoom">      <ZoomInIcon class="icon" />    </div>  </div></template>
Drag the picture, pinch it, or move the slider. Focus the circle: the arrows pan, + and - zoom.

The picture fills the box at every zoom, so a panned crop is always inside it. On the keys, the arrows move the crop as they do elsewhere, and Alt with an arrow, or + and -, zoom about the middle of the box. The box has no handles, and --cropper-inset, the room around it, shows a ring of the dimmed picture so the reader sees what is left out.

#Cutting the picture

The cropper says which part to keep; it never touches the file. Send the four numbers with the upload and cut on the server, or cut in the page with a canvas: drawImage takes a part of a picture in its own pixels, which is what the value is.

crop.js
/** The part of a loaded picture a crop keeps, as a file. */function cut(image, { x, y, width, height }, type = 'image/webp') {  const canvas = document.createElement('canvas')  canvas.width = width  canvas.height = height  canvas.getContext('2d').drawImage(image, x, y, width, height, 0, 0, width, height)  return new Promise((resolve) => canvas.toBlob(resolve, type))}const file = await cut(document.querySelector('.cropper-image'), crop.value)
  • The picture must come from the page's own origin, or carry crossorigin and be served with CORS: a canvas that has drawn a picture from elsewhere refuses to give it back.
  • When the width and height of the image are not the file's own size, scale the crop by image.naturalWidth / width first.
  • A round crop is kept square: an avatar draws itself round. Clip the canvas with an arc() only when the file itself must be round.

#Keyboard

KeysAction
ArrowLeft, ArrowRight, ArrowUp, ArrowDownMove the crop by a step of the picture's pixels, a hundredth of its longer side by default; ten steps with Shift
Alt + ArrowRight, Alt + ArrowDownMake the crop wider or taller from its far edge, both at a ratio; on a panned cropper, zoom out
Alt + ArrowLeft, Alt + ArrowUpMake the crop narrower or shorter from its far edge, both at a ratio; on a panned cropper, zoom in
+, -On a panned cropper, zoom in or out about the middle of the box

#Accessibility

  • The box is the one tab stop. It has role="application": it is a single control with keys of its own that no other role describes, and the role tells a screen reader to pass the arrows to it. Name it for what is cropped, and give it aria-roledescription in the page's language so it is announced as a crop box rather than an application.
  • The handles take no focus. Eight more tab stops would tell a keyboard nothing the box does not: the arrows move the crop and Alt with an arrow sizes it, which reaches every crop a handle reaches. Moving the start edges is a move followed by a resize.
  • After each change cropper-status says the crop's size in pixels, politely. Keep it in the markup from the start, so a screen reader has registered it before it first speaks.
  • Every drag has another way: the keys, a press on the picture to bring the box there, and the zoom's slider.
  • Give the picture an alt that says what it shows: the reader is deciding what to keep of it.
  • A handle's target is 24px, 44px on a touch screen, while the disc or the pill drawn in it keeps its size; the room around the picture grows with it. The whole frame takes the pointer, so place a cropper where a finger does not need to scroll past it, as in a dialog or an editor.
  • Under reduced motion the handles do not grow when held. In forced colors the box is drawn with a system outline, the handles in button colors and the dim kept.

#React, Svelte and Vue

The cropper component renders the picture, the box and its handles, attaches the behavior and passes the crop in and out. A panned cropper hands the page's own range input the attributes that join it to the frame. Copy it into the project with npx master-ui add cropper; React, Svelte and Vue says how the components are built and used.

ui/cropper.tsx
'use client'import { useId, useRef, useState, type ComponentProps, type CSSProperties, type ReactNode } from 'react'import { cropper, cropperFit, type Crop } from '@master/ui/behaviors/cropper.js'import { useBehavior } from './use-behavior'export type { Crop }/** What the page's range input takes to zoom a panned cropper: spread it on the input. */export interface CropperZoomAttributes {  type: 'range'  min: number  max: number  step: 'any'  defaultValue: number  disabled?: boolean  'aria-controls': string}export interface CropperProps extends Omit<ComponentProps<'div'>, 'defaultValue' | 'children' | 'ref'> {  /** The picture. */  src: string  alt: string  /** The picture's own size, in pixels: the crop is counted in them. */  width: number  height: number  /** The crop, in the picture's pixels, with `zoom` on a panned cropper. */  value?: Crop  defaultValue?: Crop  /** Called as the crop moves. */  onValueChange?: (crop: Crop) => void  /** Called once a drag, a key, a pinch or a turn of the wheel has ended. */  onValueCommit?: (crop: Crop) => void  /** Width over height the box keeps. Free when left out; 1 on a panned cropper. */  ratio?: number  /** The box stays and the picture pans and zooms under it. */  pan?: boolean  /** A round box, for an avatar. */  round?: boolean  /** The least width and height, in the picture's pixels. */  min?: number  /** How far an arrow key moves the crop, in the picture's pixels. */  step?: number  /** The greatest zoom of a panned cropper. */  maxZoom?: number  /** The name of the box: what is cropped. */  label: string  /** What the box is called in place of "application", such as "crop box". */  roleDescription?: string  /** What the status says of a crop after each change, in the page's language. */  describe?: (crop: Crop) => string  /** A range input of the page's that zooms a panned cropper, given the attributes that join it to the frame. */  zoom?: (attributes: CropperZoomAttributes) => ReactNode  disabled?: boolean}/** A share of the picture as the behavior writes it. */const share = (part: number) => String(Math.round(part * 1e5) / 1e5)/** A picture with a box over it that says what to keep. */export function Cropper({ src, alt, width, height, value, defaultValue, onValueChange, onValueCommit, ratio, pan, round, min, step, maxZoom = 4, label, roleDescription, describe, zoom, disabled, id, className, style, ...root }: CropperProps) {  const generated = useId()  const name = id ?? generated  const [first] = useState(() => cropperFit({ width, height }, value ?? defaultValue, { ratio, pan, min, zoom: [1, maxZoom] }))  const held = useRef(first)  const ref = useBehavior(cropper, { ratio: ratio ?? 0, step, min, maxZoom, describe }, {    value,    defaultValue,    onValueChange: (next: Crop | null) => { if (!next) return; held.current = next; onValueChange?.(next) },    // The box says change once a gesture or a key has ended.    on: { change: (event) => { if ((event.target as Element).classList.contains('cropper-box')) onValueCommit?.(held.current) } },  })  // The first crop is drawn on the server; after that the behavior writes these properties.  const shares = { '--cropper-x': share(first.x / width), '--cropper-y': share(first.y / height), '--cropper-width': share(first.width / width), '--cropper-height': share(first.height / height), '--cropper-ratio': ratio || undefined }  return (    <>      <div id={name} className={['cropper', pan && 'cropper-pan', round && 'cropper-round', className].filter(Boolean).join(' ')} style={{ ...shares, ...style } as CSSProperties} ref={ref} {...root}>        <img className="cropper-image" src={src} alt={alt} width={width} height={height} />        <div className="cropper-box" role="application" tabIndex={disabled ? -1 : 0} aria-label={label} aria-roledescription={roleDescription} aria-disabled={disabled || undefined}>          {pan ? null : (            <>              <span className="cropper-handle cropper-handle-top cropper-handle-left" />              <span className="cropper-handle cropper-handle-top" />              <span className="cropper-handle cropper-handle-top cropper-handle-right" />              <span className="cropper-handle cropper-handle-right" />              <span className="cropper-handle cropper-handle-bottom cropper-handle-right" />              <span className="cropper-handle cropper-handle-bottom" />              <span className="cropper-handle cropper-handle-bottom cropper-handle-left" />              <span className="cropper-handle cropper-handle-left" />            </>          )}        </div>        <p className="cropper-status" role="status" />      </div>      {pan && zoom?.({ type: 'range', min: 1, max: maxZoom, step: 'any', defaultValue: first.zoom ?? 1, disabled, 'aria-controls': name })}    </>  )}
ui/Cropper.svelte
<script lang="ts" module>  import type { Snippet } from 'svelte'  import type { HTMLAttributes } from 'svelte/elements'  import type { Crop } from '@master/ui/behaviors/cropper.js'  export type { Crop }  /** What the page's range input takes to zoom a panned cropper: spread it on the input. */  export interface CropperZoomAttributes {    type: 'range'    min: number    max: number    step: 'any'    value: number    disabled?: boolean    'aria-controls': string  }  export interface CropperProps extends Omit<HTMLAttributes<HTMLDivElement>, 'children'> {    /** The picture. */    src: string    alt: string    /** The picture's own size, in pixels: the crop is counted in them. */    width: number    height: number    /** The crop, in the picture's pixels, with `zoom` on a panned cropper. Bind it, or leave it out. */    value?: Crop    /** Called as the crop moves. */    onValueChange?: (crop: Crop) => void    /** Called once a drag, a key, a pinch or a turn of the wheel has ended. */    onValueCommit?: (crop: Crop) => void    /** Width over height the box keeps. Free when left out; 1 on a panned cropper. */    ratio?: number    /** The box stays and the picture pans and zooms under it. */    pan?: boolean    /** A round box, for an avatar. */    round?: boolean    /** The least width and height, in the picture's pixels. */    min?: number    /** How far an arrow key moves the crop, in the picture's pixels. */    step?: number    /** The greatest zoom of a panned cropper. */    maxZoom?: number    /** The name of the box: what is cropped. */    label: string    /** What the box is called in place of "application", such as "crop box". */    roleDescription?: string    /** What the status says of a crop after each change, in the page's language. */    describe?: (crop: Crop) => string    /** A range input of the page's that zooms a panned cropper, given the attributes that join it to the frame. */    zoom?: Snippet<[CropperZoomAttributes]>    disabled?: boolean  }</script><script lang="ts">  import { untrack } from 'svelte'  import { cropper, cropperFit } from '@master/ui/behaviors/cropper.js'  import { behavior } from './behavior.svelte.js'  let { src, alt, width, height, value = $bindable(), onValueChange, onValueCommit, ratio, pan, round, min, step, maxZoom = 4, label, roleDescription, describe, zoom, disabled, id, class: className, ...root }: CropperProps = $props()  const generated = $props.id()  const name = $derived(id ?? generated)  const first = untrack(() => cropperFit({ width, height }, value, { ratio, pan, min, zoom: [1, maxZoom] }))  // Svelte writes a style again whenever its owner changes it, so it writes the crop the behavior holds.  let crop = $state(first)  const attach = behavior(cropper, () => ({ ratio: ratio ?? 0, step, min, maxZoom, describe }), {    value: () => value,    change: (next) => { if (!next) return; value = crop = next; onValueChange?.(next) },    settled: (held) => { if (held) crop = held },    // The box says change once a gesture or a key has ended.    on: { change: (event) => { if ((event.target as Element).classList.contains('cropper-box')) onValueCommit?.(crop) } },  })  /** A share of the picture as the behavior writes it. */  const share = (part: number) => String(Math.round(part * 1e5) / 1e5)</script><!--  @component  A picture with a box over it that says what to keep.--><div id={name} class={['cropper', pan && 'cropper-pan', round && 'cropper-round', className]} style:--cropper-x={share(crop.x / width)} style:--cropper-y={share(crop.y / height)} style:--cropper-width={share(crop.width / width)} style:--cropper-height={share(crop.height / height)} style:--cropper-ratio={ratio || undefined} {@attach attach} {...root}>  <img class="cropper-image" {src} {alt} {width} {height} />  <!-- The box is one control that the keys move and size: an application of its own. -->  <!-- svelte-ignore a11y_no_noninteractive_tabindex -->  <div class="cropper-box" role="application" tabindex={disabled ? -1 : 0} aria-label={label} aria-roledescription={roleDescription} aria-disabled={disabled || undefined}>    {#if !pan}      <span class="cropper-handle cropper-handle-top cropper-handle-left"></span>      <span class="cropper-handle cropper-handle-top"></span>      <span class="cropper-handle cropper-handle-top cropper-handle-right"></span>      <span class="cropper-handle cropper-handle-right"></span>      <span class="cropper-handle cropper-handle-bottom cropper-handle-right"></span>      <span class="cropper-handle cropper-handle-bottom"></span>      <span class="cropper-handle cropper-handle-bottom cropper-handle-left"></span>      <span class="cropper-handle cropper-handle-left"></span>    {/if}  </div>  <p class="cropper-status" role="status"></p></div>{#if pan}  {@render zoom?.({ type: 'range', min: 1, max: maxZoom, step: 'any', value: first.zoom ?? 1, disabled, 'aria-controls': name })}{/if}
ui/Cropper.vue
<script lang="ts">import type { Crop } from '@master/ui/behaviors/cropper.js'export type { Crop }/** What the page's range input takes to zoom a panned cropper: bind it on the input. */export interface CropperZoomAttributes {  type: 'range'  min: number  max: number  step: 'any'  value: number  disabled?: boolean  'aria-controls': string}</script><script setup lang="ts">import { useAttrs, useId, useTemplateRef, type Ref } from 'vue'import { cropper, cropperFit } from '@master/ui/behaviors/cropper.js'import { useBehavior } from './use-behavior'defineOptions({ inheritAttrs: false })const { width, height, ratio, pan, min, step, maxZoom = 4, describe } = defineProps<{  /** The picture. */  src: string  alt: string  /** The picture's own size, in pixels: the crop is counted in them. */  width: number  height: number  /** Width over height the box keeps. Free when left out; 1 on a panned cropper. */  ratio?: number  /** The box stays and the picture pans and zooms under it. */  pan?: boolean  /** A round box, for an avatar. */  round?: boolean  /** The least width and height, in the picture's pixels. */  min?: number  /** How far an arrow key moves the crop, in the picture's pixels. */  step?: number  /** The greatest zoom of a panned cropper. */  maxZoom?: number  /** The name of the box: what is cropped. */  label: string  /** What the box is called in place of "application", such as "crop box". */  roleDescription?: string  /** What the status says of a crop after each change, in the page's language. */  describe?: (crop: Crop) => string  disabled?: boolean}>()/** The crop, in the picture's pixels, with `zoom` on a panned cropper: `v-model`. It changes as the crop moves. */const model = defineModel<Crop>()const emit = defineEmits<{  /** The crop, once a drag, a key, a pinch or a turn of the wheel has ended. */  valueCommit: [value: Crop]}>()defineSlots<{  /** A range input of the page's that zooms a panned cropper, given the attributes that join it to the frame. */  zoom?: (attributes: CropperZoomAttributes) => unknown}>()/* A picture with a box over it that says what to keep. */const generated = useId()const attrs = useAttrs()const name = () => (attrs.id as string | undefined) ?? generatedconst first = cropperFit({ width, height }, model.value, { ratio, pan, min, zoom: [1, maxZoom] })const root = useTemplateRef<HTMLDivElement>('root')const current = useBehavior(root, cropper, () => ({ ratio: ratio ?? 0, step, min, maxZoom, describe }), model as Ref<Crop | null | undefined>, {  // The box says change once a gesture or a key has ended.  change: (event) => { if ((event.target as Element).classList.contains('cropper-box')) emit('valueCommit', crop()) },})// Vue writes a style again each time it renders, so it writes the crop the behavior holds, not the first one.const crop = () => current() ?? first/** A share of the picture as the behavior writes it. */const share = (part: number) => String(Math.round(part * 1e5) / 1e5)const shares = () => {  const { x, y, width: across, height: down } = crop()  return { '--cropper-x': share(x / width), '--cropper-y': share(y / height), '--cropper-width': share(across / width), '--cropper-height': share(down / height), '--cropper-ratio': ratio || undefined }}</script><template>  <div class="cropper" :class="{ 'cropper-pan': pan, 'cropper-round': round }" :style="shares()" ref="root" v-bind="$attrs" :id="name()">    <img class="cropper-image" :src="src" :alt="alt" :width="width" :height="height">    <div class="cropper-box" role="application" :tabindex="disabled ? -1 : 0" :aria-label="label" :aria-roledescription="roleDescription" :aria-disabled="disabled || undefined">      <template v-if="!pan">        <span class="cropper-handle cropper-handle-top cropper-handle-left" />        <span class="cropper-handle cropper-handle-top" />        <span class="cropper-handle cropper-handle-top cropper-handle-right" />        <span class="cropper-handle cropper-handle-right" />        <span class="cropper-handle cropper-handle-bottom cropper-handle-right" />        <span class="cropper-handle cropper-handle-bottom" />        <span class="cropper-handle cropper-handle-bottom cropper-handle-left" />        <span class="cropper-handle cropper-handle-left" />      </template>    </div>    <p class="cropper-status" role="status" />  </div>  <!-- Vue writes a field's value with every render, so the zoom it is given is the one the behavior holds. -->  <slot v-if="pan" name="zoom" v-bind="{ type: 'range', min: 1, max: maxZoom, step: 'any', value: crop().zoom ?? 1, disabled, 'aria-controls': name() } as CropperZoomAttributes" /></template>

#Classes

ClassDescription
cropperThe frame: a well that holds the picture --cropper-inset in from its edge, and the box over it. The whole frame takes the pointer
cropper-panThe box stays in the middle of the frame, at the proportions of --cropper-ratio, and the picture pans and zooms under itApply with cropper
cropper-roundThe box is a circle, or an ellipse inside a box that is not square: for an avatarApply with cropper
cropper-imageThe picture. Its width and height are the file's own size in pixels: the crop is counted in them
cropper-boxThe crop: one tab stop that the arrow keys move and size, placed from the four properties. It dims the picture outside it and shows the rule of thirds while it is held or keyed
cropper-handleA handle a pointer drags: a 24px target, 44px on a coarse pointer, with a pearl pill on an edge and a pearl disc on a corner. Its modifiers name the edges it moves
cropper-handle-topThe handle moves the top edgeApply with cropper-handle
cropper-handle-bottomThe handle moves the bottom edgeApply with cropper-handle
cropper-handle-leftThe handle moves the left edgeApply with cropper-handle
cropper-handle-rightThe handle moves the right edgeApply with cropper-handle
cropper-statusA polite live region, hidden but read: the script writes the crop's size into it after each change

#Custom properties

PropertyDefaultDescription
--cropper-x0The crop's left edge, as a share of the picture's width from 0 to 1; the script writes it
--cropper-y0The crop's top edge, as a share of the picture's height
--cropper-width1The crop's width, as a share of the picture's width
--cropper-height1The crop's height, as a share of the picture's height
--cropper-ratio1Width over height of a panned box. The script writes the ratio it keeps here, and reads one written in markup
--cropper-inset1remThe room between the picture and the frame: 1.375rem on a coarse pointer, so a handle on the picture's edge stays whole, and 1.5rem around a panned box
--cropper-radiusvar(--radius-surface)Corner of the frame
--cropper-target1.5remThe size of a handle's target; 2.75rem on a coarse pointer. The mark drawn in it keeps its size

#Source

@master/ui/components/cropper.css
/* * Cropper: a picture with a box over it that says what to keep. * The picture rests in a well, --cropper-inset in from its edge, so the handles of a box that reaches the * picture's edge still have room. What lies outside the box is dimmed: the box casts a wide shadow of * --color-image-dim, clipped to the picture, so the dim follows the box's corner, round included, and never * spills past the picture. The box's own edge is the line drawn over a picture (white with a dark shade, * in both themes, as on a comparison), its handles are pearl discs at the corners and pills on the edges, * and the rule of thirds appears inside it while it is held or focused from the keyboard. * * The geometry is four custom properties, shares of the picture from 0 to 1: --cropper-x and --cropper-y * from its top left corner, --cropper-width and --cropper-height. A script writes them; the stylesheet * places the box from them, and with no script the box stays where they put it, the whole picture by default. * A picture has no direction, so the box is placed from the left and the top in every writing direction. * * Panned (cropper-pan): the box stays in the middle of the frame, at the proportions of --cropper-ratio, and * the picture moves and scales under it from the same four properties. Round (cropper-round) draws the box * as a circle, for an avatar. * * A handle's target is 24px, 44px on a coarse pointer, while the disc or the pill drawn in it keeps its * size; the inset grows with the target. Edge handles step aside when the box is too small to hold them. */@layer components.ui {  .cropper {    --cropper-x: 0;    --cropper-y: 0;    --cropper-width: 1;    --cropper-height: 1;    --cropper-ratio: 1;    --cropper-inset: 1rem;    --cropper-radius: var(--radius-surface);    --cropper-target: 1.5rem;    position: relative;    display: block;    box-sizing: border-box;    min-width: 0;    margin: 0;    padding: var(--cropper-inset);    overflow: clip;    border-radius: calc(var(--cropper-radius) * var(--corner-scale));    corner-shape: var(--corner-shape);    background: var(--color-surface-inset);    box-shadow: var(--shadow-pressed);    cursor: crosshair;    touch-action: none;    user-select: none;    -webkit-user-select: none;    -webkit-touch-callout: none;    -webkit-tap-highlight-color: transparent;    isolation: isolate;    @media (pointer: coarse) {      --cropper-target: 2.75rem;      --cropper-inset: 1.375rem;    }    /*     * Panned: the frame holds the box, --cropper-inset in from every edge, and the picture is placed under it     * so that the part the four properties name fills the box exactly.     */    &.cropper-pan {      --cropper-inset: 1.5rem;      display: grid;      cursor: grab;      &:active {        cursor: grabbing;      }      /* The inward line every picture gets, over the picture that now runs to the frame's edge. */      &::after {        content: '';        position: absolute;        inset: 0;        z-index: 2;        border-radius: inherit;        corner-shape: inherit;        box-shadow: inset 0 0 0 1px var(--color-line-image);        pointer-events: none;      }      .cropper-image {        position: absolute;        top: var(--cropper-inset);        left: var(--cropper-inset);        width: calc((100% - var(--cropper-inset) * 2) / var(--cropper-width));        max-width: none;        translate: calc(var(--cropper-x) * -100%) calc(var(--cropper-y) * -100%);        outline: 0;      }      .cropper-box {        position: relative;        inset: auto;        width: 100%;        height: auto;        aspect-ratio: var(--cropper-ratio);        cursor: inherit;      }    }    &.cropper-round .cropper-box {      border-radius: 50%;      corner-shape: round;    }    &:has(.cropper-box[aria-disabled="true"]) {      cursor: default;    }    @media (forced-colors: active) {      outline: 1px solid CanvasText;      outline-offset: -1px;    }  }  /* The picture: as wide as the well, at its own proportions, from the width and height it is given. */  .cropper-image {    display: block;    width: 100%;    max-width: 100%;    height: auto;    margin: 0;    border: 0;    outline: .5px solid var(--color-line-image-strong);    outline-offset: -.5px;    pointer-events: none;    -webkit-user-drag: none;  }  /*   * The box: placed from the four properties, inside the well's inset. Its edge is a white line with a   * dark shade; ::before casts the dim over the rest of the picture and ::after holds the thirds.   */  .cropper-box {    position: absolute;    top: calc(var(--cropper-inset) + var(--cropper-y) * (100% - var(--cropper-inset) * 2));    left: calc(var(--cropper-inset) + var(--cropper-x) * (100% - var(--cropper-inset) * 2));    width: calc(var(--cropper-width) * (100% - var(--cropper-inset) * 2));    height: calc(var(--cropper-height) * (100% - var(--cropper-inset) * 2));    box-sizing: border-box;    container: cropper-box / size;    margin: 0;    padding: 0;    border: 0;    outline: none;    box-shadow: inset 0 0 0 1px var(--color-on-image), 0 0 0 .5px var(--color-on-image-shade), 0 0 6px var(--color-on-image-shade);    cursor: move;    touch-action: none;    /* Its own layer: the dim it casts lies under its focus ring, and over the picture. */    isolation: isolate;    /*     * The dim: a shadow wide enough for any picture, clipped to the picture. The clip is the picture's own     * edge, measured from the box: it starts x / width box-widths to the left, and so on for each side.     */    &::before {      content: '';      position: absolute;      inset: 0;      z-index: -1;      border-radius: inherit;      corner-shape: inherit;      box-shadow: 0 0 0 9999px var(--color-image-dim);      clip-path: polygon(        calc(var(--cropper-x) / var(--cropper-width) * -100%) calc(var(--cropper-y) / var(--cropper-height) * -100%),        calc((1 - var(--cropper-x)) / var(--cropper-width) * 100%) calc(var(--cropper-y) / var(--cropper-height) * -100%),        calc((1 - var(--cropper-x)) / var(--cropper-width) * 100%) calc((1 - var(--cropper-y)) / var(--cropper-height) * 100%),        calc(var(--cropper-x) / var(--cropper-width) * -100%) calc((1 - var(--cropper-y)) / var(--cropper-height) * 100%)      );      pointer-events: none;    }    /* The rule of thirds: two fine lines each way, shown while the box is held or keyed. */    &::after {      content: '';      position: absolute;      inset: 0;      border-radius: inherit;      corner-shape: inherit;      background:        linear-gradient(to right, transparent calc(100% / 3 - .5px), var(--color-on-image) 0 calc(100% / 3 + .5px), transparent 0 calc(200% / 3 - .5px), var(--color-on-image) 0 calc(200% / 3 + .5px), transparent 0),        linear-gradient(to bottom, transparent calc(100% / 3 - .5px), var(--color-on-image) 0 calc(100% / 3 + .5px), transparent 0 calc(200% / 3 - .5px), var(--color-on-image) 0 calc(200% / 3 + .5px), transparent 0);      opacity: 0;      pointer-events: none;      transition: opacity var(--duration-quick) var(--easing-glide);    }    /* As on a comparison's grip: an ink ring at the edge and a white one outside it, so one reads on any picture or well. */    &:focus-visible {      outline: 2px solid var(--color-on-image);      outline-offset: 2px;      box-shadow: inset 0 0 0 1px var(--color-on-image), 0 0 0 2px var(--color-focus), 0 0 6px var(--color-on-image-shade);    }    &:focus-visible::after {      opacity: .6;    }    &[aria-disabled="true"] {      cursor: default;      .cropper-handle {        display: none;      }    }    @media (forced-colors: active) {      outline: 2px solid CanvasText;      outline-offset: -1px;      &::before {        forced-color-adjust: none;      }      &:focus-visible {        outline-color: Highlight;      }    }  }  /* While the box, a handle or the picture under a panned box is held, the thirds show; not on a disabled box. */  .cropper:active .cropper-box:not([aria-disabled="true"])::after {    opacity: .6;  }  /*   * A handle: a target as large as --cropper-target, centered on a corner or on the middle of an edge, and   * a mark drawn in it that keeps its size. Its modifiers name the edges it moves: one for an edge, two for   * a corner.   */  .cropper-handle {    position: absolute;    top: 50%;    left: 50%;    width: var(--cropper-target);    height: var(--cropper-target);    translate: -50% -50%;    touch-action: none;    /* The mark: a pill on an edge, turned with the edge. */    &::after {      content: '';      position: absolute;      inset: 0;      width: 1.25rem;      height: .375rem;      margin: auto;      border-radius: 999px;      corner-shape: round;      @apply --surface-thumb;      box-shadow: 0 0 0 .5px var(--color-on-image-shade), 0 1px 2px -.5px var(--color-on-image-shade), 0 2px 6px -1px var(--color-on-image-shade);      transition: scale var(--duration-quick) var(--easing-glide);    }    &.cropper-handle-top {      top: 0;      cursor: ns-resize;    }    &.cropper-handle-bottom {      top: 100%;      cursor: ns-resize;    }    &.cropper-handle-left {      left: 0;      cursor: ew-resize;    }    &.cropper-handle-right {      left: 100%;      cursor: ew-resize;    }    &.cropper-handle-left::after, &.cropper-handle-right::after {      width: .375rem;      height: 1.25rem;    }    /* A corner: a disc, over the edges it meets. */    &:is(.cropper-handle-top, .cropper-handle-bottom):is(.cropper-handle-left, .cropper-handle-right) {      z-index: 1;      &::after {        width: .75rem;        height: .75rem;      }    }    &.cropper-handle-top.cropper-handle-left, &.cropper-handle-bottom.cropper-handle-right {      cursor: nwse-resize;    }    &.cropper-handle-top.cropper-handle-right, &.cropper-handle-bottom.cropper-handle-left {      cursor: nesw-resize;    }    @media (hover: hover) {      &:hover::after {        scale: 1.2;      }    }    &:active::after {      scale: 1.2;    }    @media (prefers-reduced-motion: reduce) {      &::after {        transition: none;      }      &:hover::after, &:active::after {        scale: none;      }    }    @media (forced-colors: active) {      &::after {        forced-color-adjust: none;        background: ButtonText;        box-shadow: 0 0 0 1px ButtonFace;      }    }  }  /*   * An edge's handle steps aside when the box is too small to hold it apart from the corners. On a coarse   * pointer the targets are 44px, and an edge's would reach into a corner's until the box is twice that.   */  @container cropper-box (width < 4.5rem) {    .cropper-handle.cropper-handle-top:not(.cropper-handle-left, .cropper-handle-right),    .cropper-handle.cropper-handle-bottom:not(.cropper-handle-left, .cropper-handle-right) {      display: none;    }  }  @container cropper-box (height < 4.5rem) {    .cropper-handle.cropper-handle-left:not(.cropper-handle-top, .cropper-handle-bottom),    .cropper-handle.cropper-handle-right:not(.cropper-handle-top, .cropper-handle-bottom) {      display: none;    }  }  @media (pointer: coarse) {    @container cropper-box (width < 5.5rem) {      .cropper-handle.cropper-handle-top:not(.cropper-handle-left, .cropper-handle-right),      .cropper-handle.cropper-handle-bottom:not(.cropper-handle-left, .cropper-handle-right) {        display: none;      }    }    @container cropper-box (height < 5.5rem) {      .cropper-handle.cropper-handle-left:not(.cropper-handle-top, .cropper-handle-bottom),      .cropper-handle.cropper-handle-right:not(.cropper-handle-top, .cropper-handle-bottom) {        display: none;      }    }  }  /* What the script says after a change, for assistive technology only. */  .cropper-status {    position: absolute;    width: 1px;    height: 1px;    margin: -1px;    padding: 0;    overflow: hidden;    clip-path: inset(50%);    white-space: nowrap;  }}