90 lines
3.7 KiB
Plaintext
90 lines
3.7 KiB
Plaintext
---
|
|
title: 几何计算与导出
|
|
description: 使用原图坐标、纯函数和 Canvas 输出裁剪结果。
|
|
order: 20
|
|
toc:
|
|
- id: controlled-state
|
|
title: 受控状态
|
|
- id: geometry
|
|
title: 几何函数
|
|
- id: export
|
|
title: 导出图片
|
|
- id: api
|
|
title: API
|
|
- id: cross-origin
|
|
title: 跨域图片
|
|
---
|
|
|
|
## 受控状态 {#controlled-state}
|
|
|
|
```tsx
|
|
const [value, setValue] = React.useState({ x: 0, y: 0, zoom: 1 })
|
|
|
|
<Cropper
|
|
src={src}
|
|
value={value}
|
|
onValueChange={setValue}
|
|
onCropComplete={(area) => saveDraft(area)}
|
|
/>
|
|
```
|
|
|
|
`onCropAreaChange` 在有效裁剪区域变化时调用;`onCropComplete` 在拖拽或滚轮交互结束以及离散键盘操作后调用,更适合触发持久化。
|
|
|
|
## 几何函数 {#geometry}
|
|
|
|
`getCoverScale`、`getCropperBounds`、`constrainCropperValue`、`getCropArea` 和 `zoomCropperValueAtPoint` 都是无 DOM 依赖的纯函数,可在自定义 UI 或测试中单独使用。
|
|
|
|
## 导出图片 {#export}
|
|
|
|
最短路径是通过组件 ref 导出当前结果:
|
|
|
|
```tsx
|
|
import { Cropper, type CropperHandle } from "@workspace/cropper"
|
|
|
|
const cropperRef = React.useRef<CropperHandle>(null)
|
|
|
|
const result = await cropperRef.current?.getCropImage({
|
|
outputType: "base64",
|
|
type: "image/jpeg",
|
|
quality: 0.9,
|
|
width: 1200,
|
|
})
|
|
|
|
<Cropper ref={cropperRef} src={src} />
|
|
```
|
|
|
|
`getCropImage()` 在图片尚未加载时返回 `undefined`。`outputType` 默认为 `"blob"`;设为 `"base64"` 时返回可直接用于预览或表单值的 data URL。质量必须位于 `0` 到 `1` 之间。
|
|
|
|
需要脱离组件使用时,继续使用纯函数:
|
|
|
|
```tsx
|
|
const blob = await cropImage(src, area, {
|
|
type: "image/webp",
|
|
quality: 0.9,
|
|
width: 1200,
|
|
})
|
|
```
|
|
|
|
只指定 `width` 或 `height` 时会保持裁剪区域宽高比。`shape: "circle"` 会使用椭圆路径裁剪;需要 JPEG 背景色时可以提供 `background`。`getCropImage(source, area, options)` 是支持 Blob/base64 返回值的对应纯函数。
|
|
|
|
## API {#api}
|
|
|
|
| 属性 | 类型 | 说明 |
|
|
| ------------------------------ | ----------------------------------- | ------------------------------ |
|
|
| `src` | `string \| Blob` | 图片 URL、Blob 或 File。 |
|
|
| `aspectRatio` | `number \| \`${number}:${number}\`` | 裁剪视口比例,默认为 `1`。 |
|
|
| `width` / `height` | `CSSProperties` 对应值 | 可选的内联容器尺寸。 |
|
|
| `value` / `defaultValue` | `CropperValue` | 受控或非受控的平移、缩放状态。 |
|
|
| `minZoom` / `maxZoom` | `number` | 缩放范围,默认 `1` 到 `4`。 |
|
|
| `shape` | `"rectangle" \| "circle"` | 视口形状。 |
|
|
| `showGrid` | `boolean` | 是否显示三等分辅助线。 |
|
|
| `onCropAreaChange` | `(area) => void` | 有效原图裁剪区域变化时触发。 |
|
|
| `onCropComplete` | `(area, value) => void` | 一次交互或重置完成时触发。 |
|
|
| `onImageLoad` / `onImageError` | 回调函数 | 监听图片加载状态。 |
|
|
|
|
`CropperHandle` 提供 `element`、`getCropArea()`、`getCropImage(options)` 和 `reset()`。需要原始 DOM ref 时使用 `rootRef`,组件 `ref` 专用于命令式句柄。
|
|
|
|
## 跨域图片 {#cross-origin}
|
|
|
|
跨域 URL 必须由图片服务器返回允许 Canvas 使用的 CORS 响应头,并同时向 `Cropper` 和 `cropImage` 传入 `crossOrigin="anonymous"`。否则浏览器会将 Canvas 标记为 tainted,无法编码 Blob。
|