图像注释组件使用概述
@frank17008/image-annotation 是一个使用 React + TypeScript 的图像注释组件,支持 Canvas 2D。支持矩形、圆形、箭头、文本和自由手绘工具,具有撤销/重做、拖拽、导出、键盘快捷键、缩放/平移和 DPR 感知渲染功能。
包位置:packages/image-annotation/src/
发布路径:@frank17008/image-annotation
何时使用
触发短语:"如何集成图像注释组件"、"在我的 React 应用中添加注释"、"画布为空白,尽管图像已加载"、"注释未保存"、"自定义图像上传与注释"、"受控模式不工作"、"HiDPI/Retina 显示模糊"
安装
pnpm add @frank17008/image-annotation
# 或 npm install @frank17008/image-annotation
基本集成
最小设置
import { useState } from 'react';
import { ImageAnnotation, type Annotation } from '@frank17008/image-annotation';
import '@frank17008/image-annotation/dist/index.css';
export default function App() {
const [annotations, setAnnotations] = useState([]);
return (
);
}
关键:父容器必须具有显式高度。否则,画布将具有 0×0 尺寸 → 空白画布。
类型导入
始终使用显式类型导入 TypeScript:
import type { Annotation, ToolType } from '@frank17008/image-annotation';
// 或
import { type Annotation, type ToolType } from '@frank17008/image-annotation';
受控与非受控模式
非受控(默认)
console.log(annotations)} />
组件管理其自身的状态。
受控(外部状态)
const [myAnnotations, setMyAnnotations] = useState([]);
规则:
value → 外部注释(组件的只读)
onChange → 注释更改时调用
如果同时提供 value 和 onChange → 受控模式
如果都没有 → 非受控模式
如果只有 value 没有 onChange → React 警告
同步受控到非受控
{
setAnnotations(newAnnotations);
// 保存到后端、localStorage 等
saveToBackend(newAnnotations);
}} />
自定义图像上传模式
模式 1:外部按钮
import { useState, useRef } from 'react';
import { ImageAnnotation } from '@frank17008/image-annotation';
export function ImageUploader() {
const [imageSrc, setImageSrc] = useState(null);
const fileInputRef = useRef(null);
const handleFileChange = (e: React.ChangeEvent) => {
const file = e.target.files?.[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (event) => {
const result = event.target?.result;
if (typeof result === 'string') {
setImageSrc(result);
// base64 字符串
}
};
reader.readAsDataURL(file);
e.target.value = '';
// 重置为相同文件重新选择
};
return (
fileInputRef.current?.click()}>
上传图像
{imageSrc && (
{}} />
)}
);
}
模式 2:组件的上传按钮
const handleUpload = () => fileInputRef.current?.click();
组件在工具栏中显示上传按钮,当提供 onUpload 时。
注释类型参考
// 矩形注释
{ type: 'rectangle', x: number, y: number, width: number, height: number, color: string, lineWidth?: number }
// 圆形注释
{ type: 'circle', x: number, y: number, radius: number, color: string, lineWidth?: number }
// 箭头注释
{ type: 'arrow', x: number, y: number, toX: number, toY: number, color: string, lineWidth?: number }
// 文本注释
{ type: 'text', x: number, y: number, text: string, color: string, lineWidth?: number }
// 自由手绘注释
{ type: 'freehand', points: Array<{ x: number, y: number }>, color: string, lineWidth?: number }
类型导出
import type { Annotation, RectangleAnnotation, CircleAnnotation, ArrowAnnotation, TextAnnotation, FreehandAnnotation, ToolType, Point, } from '@frank17008/image-annotation';
Props API
属性 类型 必需 描述
src string √ 图像 URL 或 base64 值
Annotation[] × 受控注释
onChange (annotations: Annotation[]) => void × 注释更改回调
className string × 容器 className
onUpload () => void × 上传按钮调用