# Image Cropper

移动选区或调整它的大小，或者在选区下方平移和缩放图片，选出图片里要保留的部分。

用图片裁剪器选出照片里要保留的部分，比如头像或封面图。裁剪区域是图片自身像素里的一个方框，带有顺时针四分之一圈的旋转和一次翻转，可以直接传给 [`cropImage`](/docs/core/image)。

<ComponentExample
  name="image-cropper/basic"
  inspect
  caption="选一个比例，拖动选区或它的一个手柄，然后按 Crop。用 Tab 移到选区，用方向键移动，加 Shift 可以走得更远。"
/>

## 安装
```bash
npm install @ui-sdk/web @ui-sdk/core
```

导入组件来注册它的元素。这个导入在服务端是安全的。

```ts
import "@ui-sdk/web/image-cropper"
```

## 组合
用下面的组合构建 `ui-image-cropper`：

```text
ui-image-cropper
├── ui-image-cropper-viewport
│   ├── ui-image-cropper-image
│   ├── ui-image-cropper-selection
│   │   └── ui-image-cropper-grid
│   └── ui-image-cropper-handle
├── ui-image-cropper-zoom
├── ui-image-cropper-rotate
└── ui-image-cropper-flip
```

- **ui-image-cropper** 持有裁剪区域和图片的 `src`，是包住各部件的一组。
- **ui-image-cropper-viewport** 是图片显示的区域。给它一个尺寸，它的内边距会让图片与边缘保持距离。
- **ui-image-cropper-image** 包住你的 `<img>`（连同它的 `alt`），并旋转和翻转它。
- **ui-image-cropper-selection** 在图片上显示裁剪区域。它是一个滑块，你可以拖动它，或者用方向键移动它。
- **ui-image-cropper-grid** 在选区上画出三等分的线，供你设置样式。
- **ui-image-cropper-handle** 从一条边或一个角调整选区大小，位置由它的 `position` 决定，比如 `"se"` 表示右下角。它放在选区旁边，而不是里面，落在选区的边或角上。
- **ui-image-cropper-zoom** 包住一个范围输入框，从 1（最大的裁剪区域）到 `max-zoom`。
- **ui-image-cropper-rotate** 把图片顺时针旋转四分之一圈。
- **ui-image-cropper-flip** 左右镜像图片；设置 `direction="vertical"` 时上下镜像。

视口、图片和选区是必需的，其余都是可选的。缩放、旋转和翻转使用你放进它们里面的 `<input>` 或 `<button>`，没有的话就自己创建一个。

## 用法
导入部件并把它们组合起来：

```html
<script type="module">
  import "@ui-sdk/web/image-cropper"
</script>

<ui-image-cropper aria-label="Cover photo" src="cover.jpg" aspect-ratio="3">
  <ui-image-cropper-viewport>
    <ui-image-cropper-image>
      <img alt="Your cover photo" />
    </ui-image-cropper-image>
    <ui-image-cropper-selection></ui-image-cropper-selection>
    <ui-image-cropper-handle position="nw"></ui-image-cropper-handle>
    <ui-image-cropper-handle position="se"></ui-image-cropper-handle>
  </ui-image-cropper-viewport>
</ui-image-cropper>
```

用 `aria-label` 给裁剪器命名。在图片加载完成之前，根部件带有 `data-loading` 和 `aria-busy`，选区是隐藏的。之后裁剪区域从中间开始，按 `aspectRatio` 取图片允许的最大尺寸的五分之四，好让裁剪区域的边缘露出来；在外框里则取允许的最大尺寸，除非你设置 `defaultCrop` property：

```ts
const cropper = document.querySelector("ui-image-cropper")!
cropper.defaultCrop = { x: 40, y: 40, width: 320, height: 240 }
```

## 宽高比
设置 `aspect-ratio`，让裁剪区域的宽度和高度保持固定比例，比如 `1` 表示正方形，或者 `16 / 9`。修改它时，裁剪区域会以中心为基准适应新的比例。不设置时，裁剪区域是自由的；拖动某个手柄时按住 Shift，会保持当前的比例。`min-width` 和 `min-height` 以图片像素为单位，防止它变得太小。

```ts title="aspect-ratio.ts"
import "@ui-sdk/web/image-cropper"

const photo = `data:image/svg+xml,${encodeURIComponent(
  `<svg xmlns="http://www.w3.org/2000/svg" width="640" height="420"><rect width="640" height="420" fill="#e5e5e5"/><circle cx="460" cy="150" r="56" fill="#fafafa"/><path d="M0 280 120 170l110 100 120-130 130 125 90-60 70 40v175H0z" fill="#a3a3a3"/><path d="M0 330l160-80 120 70 150-80 210 85v95H0z" fill="#525252"/><path d="M0 380q160-35 320-10t320-5v55H0z" fill="#262626"/></svg>`
)}`

const ratios = [
  { label: "Free", value: "" },
  { label: "Square", value: "1" },
  { label: "Wide", value: String(16 / 9) },
]

const handles = ["nw", "n", "ne", "e", "se", "s", "sw", "w"]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <div data-slot="controls">
        ${ratios
          .map(
            (ratio) =>
              `<button type="button" aria-pressed="${ratio.value === ""}" data-ratio="${ratio.value}">${ratio.label}</button>`
          )
          .join("")}
      </div>
      <ui-image-cropper aria-label="Photo" src="${photo}" min-width="64" min-height="64">
        <ui-image-cropper-viewport>
          <ui-image-cropper-image><img alt="Mountains at sunset" /></ui-image-cropper-image>
          <ui-image-cropper-selection>
            <ui-image-cropper-grid></ui-image-cropper-grid>
          </ui-image-cropper-selection>
          ${handles.map((position) => `<ui-image-cropper-handle position="${position}"></ui-image-cropper-handle>`).join("")}
        </ui-image-cropper-viewport>
        <div data-slot="row">
          <ui-image-cropper-flip>Flip</ui-image-cropper-flip>
          <ui-image-cropper-flip direction="vertical">Flip Vertically</ui-image-cropper-flip>
        </div>
      </ui-image-cropper>
    </div>
  `
  const cropper = root.querySelector("ui-image-cropper")!
  const buttons = root.querySelectorAll<HTMLButtonElement>("[data-ratio]")
  for (const button of buttons) {
    button.addEventListener("click", () => {
      for (const other of buttons) {
        other.setAttribute("aria-pressed", String(other === button))
      }
      if (button.dataset.ratio) {
        cropper.setAttribute("aspect-ratio", button.dataset.ratio)
      } else {
        cropper.removeAttribute("aspect-ratio")
      }
    })
  }
}

export { mount }
```

选择 Square 或 Wide，然后拖动一条边。Flip 会镜像图片，裁剪区域随之翻转。

## 外框模式
设置 `mode="frame"`，得到一个头像编辑器。选区保持不动，并占据能放下的最大尺寸；拖动可以在选区下面平移图片，转轮、双指捏合或缩放输入框可以缩放。外框里不显示手柄。

设置 `shape="circle"` 会把选区变成圆形，但裁剪区域仍然是它的方框，所以也要把 `shape: "circle"` 传给 `cropImage`。这里的 Save Avatar 会裁出一个 128 像素的圆形文件：

```ts title="avatar.ts"
import "@ui-sdk/web/image-cropper"
import { cropImage } from "@ui-sdk/web"

const photo = `data:image/svg+xml,${encodeURIComponent(
  `<svg xmlns="http://www.w3.org/2000/svg" width="640" height="420"><rect width="640" height="420" fill="#e5e5e5"/><circle cx="460" cy="150" r="56" fill="#fafafa"/><path d="M0 280 120 170l110 100 120-130 130 125 90-60 70 40v175H0z" fill="#a3a3a3"/><path d="M0 330l160-80 120 70 150-80 210 85v95H0z" fill="#525252"/><path d="M0 380q160-35 320-10t320-5v55H0z" fill="#262626"/></svg>`
)}`

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-image-cropper aria-label="Profile photo" src="${photo}" mode="frame" aspect-ratio="1" shape="circle" max-zoom="4">
      <ui-image-cropper-viewport>
        <ui-image-cropper-image><img alt="Mountains at sunset" /></ui-image-cropper-image>
        <ui-image-cropper-selection></ui-image-cropper-selection>
      </ui-image-cropper-viewport>
      <div data-slot="row">
        <ui-image-cropper-zoom></ui-image-cropper-zoom>
        <ui-image-cropper-rotate>Rotate</ui-image-cropper-rotate>
      </div>
      <div data-slot="row">
        <button type="button">Save Avatar</button>
        <img data-slot="image-cropper-avatar" alt="Your new avatar" hidden />
      </div>
    </ui-image-cropper>
  `
  const cropper = root.querySelector("ui-image-cropper")!
  const avatar = root.querySelector<HTMLImageElement>(
    '[data-slot="image-cropper-avatar"]'
  )!
  root
    .querySelector("[data-slot=row] > button")!
    .addEventListener("click", async () => {
      if (!cropper.crop) {
        return
      }
      const file = await cropImage(photo, cropper.crop, {
        width: 128,
        shape: "circle",
      })
      if (avatar.src) {
        URL.revokeObjectURL(avatar.src)
      }
      avatar.src = URL.createObjectURL(file)
      avatar.hidden = false
    })
}

export { mount }
```

拖动图片或调整缩放，然后按 Save Avatar。新头像显示在按钮旁边。

## 旋转与翻转
`ui-image-cropper-rotate` 把图片顺时针旋转四分之一圈，键盘上的 R 也能做到，按 Shift 则转回来。`ui-image-cropper-flip` 镜像图片。裁剪区域随图片一起旋转和翻转，所以它保留照片的同一部分。它的 `x` 和 `y` 从图片显示时的左上角算起，此时已经过旋转和翻转，这正是 `cropImage` 接收的值。

## 禁用
设置 `disabled`。选区和手柄不能获得焦点，也不能拖动，缩放输入框和按钮会被禁用。

```html
<ui-image-cropper aria-label="Photo" src="photo.jpg" disabled>
  <!-- … -->
</ui-image-cropper>
```

## 受控
监听 `cropchange` 获取每次变更。每次变更都带一个[原因](https://ui-sdk.cn/docs/web-components/components/image-cropper#reasons)，比如 `drag`、`step-key` 或 `zoom-input`。调用 `event.preventDefault()` 保留当前的裁剪区域。

`cropchange` 在拖动的每一步触发，图片加载完成时也触发一次。`cropcommit` 只触发一次，在拖动、按键或转轮结束时，所以监听它来保存。元素的 `crop` property 读取裁剪区域，它的 `api` property 可以从任何地方设置它：

```ts
import "@ui-sdk/web/image-cropper"

const cropper = document.querySelector("ui-image-cropper")!

cropper.addEventListener("cropcommit", (event) => {
  console.log(event.detail.value, event.detail.reason)
})

document
  .querySelector("#zoom-in")!
  .addEventListener("click", () => cropper.api.setZoom(2))
```

受控状态、取消和调试见[状态与事件](/docs/web-components/state-and-events)。

## 样式
部件没有样式，除了它们需要的位置：视口是 `position: relative` 加 `overflow: hidden`，图片、选区和每个手柄的位置都来自以像素为单位的内联样式。手柄的位置是它所在边或角上的那个点，所以要给它尺寸，并用 `translate: -50% -50%` 把它居中。也要给视口一个尺寸。

方框模式的视口会装下整张图片，所以把它的 `aspect-ratio` 设为 `--image-cropper-aspect-ratio`。在选区上放一个很大的 `box-shadow`，会压暗它外面的图片。只在选区带有 `data-dragging` 时显示网格。

每个部件都有一个 `data-slot`，比如 `image-cropper-selection`，它的状态属性列在[数据属性](https://ui-sdk.cn/docs/web-components/components/image-cropper#data-attributes)下。

### ui-image-cropper-viewport
- `--image-cropper-aspect-ratio`: The image's width over its height as it shows, turned, once it loads. Give the viewport `aspect-ratio: var(--image-cropper-aspect-ratio)` to fit the image.

## 数据属性
### ui-image-cropper
`[data-slot="image-cropper"]`

- `data-mode` (`box`, `frame`): How the crop changes.
- `data-shape` (`rectangle`, `circle`): The selection's shape.
- `data-loading`: Present until the image loads, while nothing can change.
- `data-disabled`: Present when the cropper is disabled.
- `data-error`: Present when the image failed to load.
- `data-dragging`: Present while a pointer drags the selection, the image or, on a handle, that handle. Show the grid with it.

### ui-image-cropper-viewport
`[data-slot="image-cropper-viewport"]`

- `data-mode` (`box`, `frame`): How the crop changes.
- `data-shape` (`rectangle`, `circle`): The selection's shape.
- `data-loading`: Present until the image loads, while nothing can change.
- `data-disabled`: Present when the cropper is disabled.
- `data-error`: Present when the image failed to load.
- `data-dragging`: Present while a pointer drags the selection, the image or, on a handle, that handle. Show the grid with it.

### ui-image-cropper-image
`[data-slot="image-cropper-image"]`

- `data-mode` (`box`, `frame`): How the crop changes.
- `data-shape` (`rectangle`, `circle`): The selection's shape.
- `data-loading`: Present until the image loads, while nothing can change.
- `data-disabled`: Present when the cropper is disabled.
- `data-error`: Present when the image failed to load.

### ui-image-cropper-selection
`[data-slot="image-cropper-selection"]`

- `data-mode` (`box`, `frame`): How the crop changes.
- `data-shape` (`rectangle`, `circle`): The selection's shape.
- `data-loading`: Present until the image loads, while nothing can change.
- `data-disabled`: Present when the cropper is disabled.
- `data-error`: Present when the image failed to load.
- `data-dragging`: Present while a pointer drags the selection, the image or, on a handle, that handle. Show the grid with it.

### ui-image-cropper-grid
`[data-slot="image-cropper-grid"]`

- `data-mode` (`box`, `frame`): How the crop changes.
- `data-shape` (`rectangle`, `circle`): The selection's shape.
- `data-loading`: Present until the image loads, while nothing can change.
- `data-disabled`: Present when the cropper is disabled.
- `data-error`: Present when the image failed to load.
- `data-dragging`: Present while a pointer drags the selection, the image or, on a handle, that handle. Show the grid with it.

### ui-image-cropper-handle
`[data-slot="image-cropper-handle"]`

- `data-position` (`n`, `e`, `s`, `w`, `ne`, `nw`, `se`, `sw`): The edge or corner the handle resizes.
- `data-mode` (`box`, `frame`): How the crop changes.
- `data-shape` (`rectangle`, `circle`): The selection's shape.
- `data-loading`: Present until the image loads, while nothing can change.
- `data-disabled`: Present when the cropper is disabled.
- `data-error`: Present when the image failed to load.
- `data-dragging`: Present while a pointer drags the selection, the image or, on a handle, that handle. Show the grid with it.

### ui-image-cropper-zoom
`[data-slot="image-cropper-zoom"]`

- `data-mode` (`box`, `frame`): How the crop changes.
- `data-shape` (`rectangle`, `circle`): The selection's shape.
- `data-loading`: Present until the image loads, while nothing can change.
- `data-disabled`: Present when the cropper is disabled.
- `data-error`: Present when the image failed to load.

### ui-image-cropper-rotate
`[data-slot="image-cropper-rotate"]`

- `data-mode` (`box`, `frame`): How the crop changes.
- `data-shape` (`rectangle`, `circle`): The selection's shape.
- `data-loading`: Present until the image loads, while nothing can change.
- `data-disabled`: Present when the cropper is disabled.
- `data-error`: Present when the image failed to load.

### ui-image-cropper-flip
`[data-slot="image-cropper-flip"]`

- `data-direction` (`horizontal`, `vertical`): Which way the button mirrors the image.
- `data-mode` (`box`, `frame`): How the crop changes.
- `data-shape` (`rectangle`, `circle`): The selection's shape.
- `data-loading`: Present until the image loads, while nothing can change.
- `data-disabled`: Present when the cropper is disabled.
- `data-error`: Present when the image failed to load.

## API 参考
属性是 kebab 命名的 attribute，比如 `aspect-ratio` 和 `max-zoom`。`defaultCrop` 和 `controller` 是 property。`crop` 是实时 property。回调是 DOM 事件。

### ui-image-cropper
- `src?` (`string`): The image's URL, like an object URL for a file someone picked.
- `crop?` (`ImageCrop`): The crop, in the image's own pixels, from the top left of the image as it shows once turned and flipped, with its `rotation`, `flipX` and `flipY`. Pass it straight to `cropImage`. Pass it to control the cropper.
- `defaultCrop?` (`ImageCrop`): The crop at first, when uncontrolled.
- `cropchange event`: Runs while the crop changes: on every step of a drag, a key or the wheel, and once an image loads. `details.cancel()` stops it.
- `cropcommit event`: Runs once an interaction that changed the crop ends: the pointer lifts, a key is pressed, the wheel pauses. For saving.
- `mode?` (`ImageCropperMode`): `"box"` moves and resizes a selection over the whole image. `"frame"` keeps the selection still and as large as it fits, and pans and zooms the image under it, like an avatar editor.
- `aspectRatio?` (`number`): Keeps the crop's width over its height, like `1` for a square or `16 / 9`. Changing it fits the crop to the new ratio.
- `shape?` (`ImageCropperShape`): The selection's shape, as `data-shape`. A circle is still a box to the crop, so pass `shape: "circle"` to `cropImage` too.
- `minWidth?` (`number`): The narrowest the crop gets, in image pixels.
- `minHeight?` (`number`): The shortest the crop gets, in image pixels.
- `maxZoom?` (`number`): How far the crop magnifies the image, where 1 is the largest crop the image allows.
- `disabled?` (`boolean`): Stops every change: the selection can't be focused, and the buttons and zoom are disabled.
- `controller?` (`object`): Sets the crop from anywhere. Create one with `createImageCropperController()`.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### ui-image-cropper-handle
- `position` (`ImageCropperHandlePosition`): The edge or corner it resizes, like `"nw"` for the top left corner.

### ui-image-cropper-flip
- `direction?` (`ImageCropperFlipDirection`): Which way it mirrors the image.

### 状态
同样的状态会作为数据属性显示在每个元素上。

- `crop` (`Required<ImageCrop> | null`): The crop, or null until the image loads.
- `zoom` (`number`): How far the crop magnifies: 1 when it's as large as the image allows at its ratio.
- `loading` (`boolean`): Whether the image is still loading, so nothing can change yet.
- `error` (`boolean`): Whether the image failed to load.
- `dragging` (`boolean`): Whether a pointer is dragging the selection, a handle or the image.
- `mode` (`ImageCropperMode`): How the crop changes.
- `shape` (`ImageCropperShape`): The selection's shape.
- `disabled` (`boolean`): Whether the `disabled` option stops every change.

- `crop` (`Required<ImageCrop> | null`): The crop, or null until the image loads.
- `zoom` (`number`): How far the crop magnifies: 1 when it's as large as the image allows at its ratio.
- `loading` (`boolean`): Whether the image is still loading, so nothing can change yet.
- `error` (`boolean`): Whether the image failed to load.
- `dragging` (`boolean`): Whether a pointer is dragging the selection, a handle or the image.
- `mode` (`ImageCropperMode`): How the crop changes.
- `shape` (`ImageCropperShape`): The selection's shape.
- `disabled` (`boolean`): Whether the `disabled` option stops every change.
- `position` (`ImageCropperHandlePosition`): The edge or corner it resizes.

### 原因
`event.detail.reason` 说明裁剪区域为什么变化。

- `image-load` (`Event | undefined`): An image loaded. No event when it was already in the browser's cache.
- `drag` (`PointerEvent`): A slider thumb or a resize handle was dragged, or an item was dragged to a new place in a list.
- `pinch`
- `wheel` (`WheelEvent`): The mouse wheel stepped a focused number input.
- `step-key` (`KeyboardEvent`): Arrow, Page Up, Page Down, Home or End stepped a slider or a number input.
- `zoom-key`
- `zoom-input`
- `rotate-key`
- `rotate-press`
- `flip-press`
- `aspect-ratio-change`
- `imperative` (`none`): A controller or `api` call.

### 控制器
元素的 `api` property 有相同的方法。`crop` property 读取和设置裁剪区域。

每个写入方法接受可选的 `{ reason, event }`，像拖动一样触发变更事件，并在没有任何变化或变更被取消时返回 `false`。

- `getCrop()` (`() => Required<ImageCrop> | null`): The crop, or null until the image loads.
- `setCrop(crop, options?)` (`(crop: ImageCrop, options?: ImageCropperChangeOptions | undefined) => boolean`): Sets the crop, as a user would. Returns whether it changed.
- `rotate(direction?, options?)` (`(direction?: 1 | -1 | undefined, options?: ImageCropperChangeOptions | undefined) => boolean`): Turns the image a quarter clockwise, or counterclockwise with `-1`.
- `flip(direction?, options?)` (`(direction?: ImageCropperFlipDirection | undefined, options?: ImageCropperChangeOptions | undefined) => boolean`): Mirrors the image left to right, or top to bottom with `"vertical"`.
- `getZoom()` (`() => number`): How far the crop magnifies: 1 when it's as large as the image allows at its ratio.
- `setZoom(zoom, options?)` (`(zoom: number, options?: ImageCropperChangeOptions | undefined) => boolean`): Zooms to a level, about the crop's middle, within 1 and `maxZoom`.
- `focus()` (`() => void`): Moves focus to the selection.

### 事件
事件在各自的元素上触发，不冒泡，新的裁剪区域在 `event.detail.value` 里，旁边是 `reason` 和 `event`。在 `cropchange` 上调用 `preventDefault()` 会取消变更。

| 成员              | 所属               | 说明                                           |
| ----------------- | ------------------ | ---------------------------------------------- |
| `crop` property   | `ui-image-cropper` | 裁剪区域，图片加载完成前是 `null`              |
| `api` property    | `ui-image-cropper` | [控制器](https://ui-sdk.cn/docs/web-components/components/image-cropper#controller)                          |
| `cropchange` 事件 | `ui-image-cropper` | `detail: { value, reason, event }`             |
| `cropcommit` 事件 | `ui-image-cropper` | `detail: { value, reason, event }`，交互结束时 |

## 无障碍
没有 WAI-ARIA 模式直接覆盖图片裁剪器，所以它由已有的模式搭成。裁剪器是一个分组。选区和每个手柄遵循 [WAI-ARIA 滑块模式](https://www.w3.org/WAI/ARIA/apg/patterns/slider/)，并用文字说出裁剪区域，比如“300 by 300 pixels, at 50, 0”。缩放是一个原生范围输入框，会说出它的级别，比如“125%”。

选区、手柄和缩放默认用英语命名。传入 `aria-label` 来用其他语言命名它们。

### 键盘
| 按键                | 作用                                        |
| ------------------- | ------------------------------------------- |
| Arrow keys          | 移动选区；在手柄上时，移动它的边            |
| Shift with an arrow | 移动十倍远                                  |
| Plus or Minus       | 以裁剪区域的中心为基准放大或缩小            |
| R                   | 把图片顺时针旋转四分之一圈，加 Shift 转回来 |
| Escape              | 拖动过程中，把裁剪区域放回拖动开始的位置    |

每次按键都会提交，就像一次拖动结束。

### 经过测试的行为
下面每一行都是一个自动化测试。

**Loading**

- The crop starts once the image loads, as four fifths of the largest at the ratio.

**Box**

- A drag moves the selection over the image and commits once.
- A handle resizes from its corner, within the image.
- Each handle sits on its edge or corner of the selection, and follows it.
- At a ratio, a handle keeps it.
- Escape during a drag puts the selection back.

**Keyboard**

- Arrows move the selection, ten times as far with Shift.
- Arrows on a handle move its edges, and the next Tab reaches it.
- Plus and minus zoom about the middle, and R turns the image.

**Controls**

- The zoom input zooms the crop.
- Rotate turns the image a quarter clockwise, and flip mirrors it.
- A controller sets the crop, and a canceled change keeps it.
- Disabled, nothing takes focus or changes.

**Frame**

- The selection stays put and a drag pans the image under it.
- Escape during a pan puts the image back.
- The wheel zooms at the pointer and commits after a pause.

Runs in React、Vue 和 web components.
