Signature
以 canvas 為基礎的簽名板。指標事件(滑鼠 / 觸控 / 手寫筆)歸一為 LhSignaturePoint(版面偏移取自 canvas.getBoundingClientRect(),比例 = 實體 / CSS 像素),每個線段以 drawSmoothSegment(二次貝茲中點平滑)增量繪製,復原則以筆跡快照經 redrawSnapshot 重繪。所有平滑、去重與空態邏輯均消費 @lh-ui/share/core/signature 純函式,因此各端語意完全一致。
- 預設高度為
200px;canvas 緩衝區隨devicePixelRatio縮放,筆跡與匯出在 retina 螢幕上依然銳利。 guideline在高度 2/3 處繪製虛線基準線;backgroundColor在繪製前填充畫布(匯出時亦使用)。eraser將筆跡切換為destination-out合成以擦除像素;每筆筆跡在進入復原堆疊前皆經dedupePoints去重,抖動不會撐爆堆疊。- 空態在第一筆筆跡確定前渲染
lh-signature__placeholder。
基本用法
Signature(輔助線 / 復原 / 清空 / 匯出預覽 / 橡皮擦)
请在此处签名
isEmpty: true
请在此处签名
import { LhSignature } from '@lh-ui/react'
export default function Demo() {
return (
<>
<LhSignature guideline height={180} penColor="#1D2129" backgroundColor="#FFFFFF" />
<LhSignature eraser height={120} />
</>
)
}
繪製回呼
onStart / onSigning / onEnd 對齊其他端的 start / signing / end 事件。onSigning 接收每個歸一點,便於筆跡統計:
<LhSignature
onStart={(point) => console.log('落笔', point)}
onSigning={(point) => console.log('行笔', point)}
onEnd={() => console.log('收笔')}
/>
命令式 API(ref)
命令經 forwardRef + useImperativeHandle 暴露,受控與非受控形態皆可用:
import { useRef } from 'react'
import { LhSignature, type LhSignatureRef } from '@lh-ui/react'
const ref = useRef<LhSignatureRef>(null)
ref.current?.toDataURL('image/png') // export the canvas (type / quality passthrough)
ref.current?.undo() // pop the last stroke and repaint
ref.current?.clear() // clear all strokes and repaint the base layer
ref.current?.isEmpty() // snapshot-based blank state
Signature API
| Prop | Description | Type | Default |
|---|---|---|---|
| penColor | 筆色(未傳走畫布預設黑色) | string | 畫布預設 |
| lineWidth | 筆跡線寬 px | number | 3 |
| backgroundColor | 畫布背景填充 | string | 透明 |
| disabled | 停用繪製(加 --disabled,阻擋指標) | boolean | false |
| guideline | 高度 2/3 處的虛線基準線 | boolean | false |
| height | 畫布高度 px | number | 200 |
| eraser | 橡皮擦模式(destination-out 合成) | boolean | false |
| onStart | 落筆時觸發(歸一點) | (point: LhSignaturePoint) => void | — |
| onSigning | 每個移動點觸發 | (point: LhSignaturePoint) => void | — |
| onEnd | 筆跡確定時觸發 | () => void | — |
| label | 無障礙名稱(aria-label) | string | 签名画布 |
| sx | 快速版面屬性 | LhSxProps | — |
LhSignatureRef
| Method | Description | Signature |
|---|---|---|
| toDataURL | 將畫布匯出為 data URL(無 canvas 環境時回傳 null) | (type?: string, quality?: number) => string | null |
| clear | 清空全部筆跡並重繪底層 | () => void |
| undo | 撤銷最後一筆(快照出棧 + 重繪) | () => void |
| isEmpty | 空態(快照口径) | () => boolean |
無障礙
- 根節點帶有
role="img"與aria-label(label屬性或签名画布兜底),螢幕閱讀器可朗讀簽名板。 - 停用態由
lh-signature--disabled修飾傳達(阻擋指標並降低不透明度);橡皮擦態由lh-signature--eraser游標提示傳達。 - 繪製僅支援指標;若需要鍵盤等價操作,請包裹簽名板並提供
undo/clear按鈕(如上方範例)。