# SignaturePad

> Signature capture from @salmonui/inputs/signature-pad on a Canvas 2D with Pointer Events, pressure and velocity widths, undo / redo, PNG / JPEG / SVG output, a keyboard "type your name" mode and form submission.

Canonical: https://salmonui.dev/docs/inputs/signature-pad

`SignaturePad` captures a handwritten signature. The strokes are the source
of truth and the canvas is a render of them: undo and redo walk a stack of
states, a resize or a devicePixelRatio change redraws from the strokes, and
`toSVG()` writes the same smoothed curves.

```tsx
import { useRef } from 'react';
import { SignaturePad, type SignaturePadApi } from '@salmonui/inputs/signature-pad';
import '@salmonui/inputs/signature-pad/styles.css';

const pad = useRef<SignaturePadApi>(null);
<SignaturePad ref={pad} name="signature" label="Signature" backgroundColor="#ffffff" />
// later: const blob = await pad.current!.toBlob('image/png');
```

### Live demo: SignaturePad basics

Live demo: https://salmonui.dev/demos/inputs/signature-pad-basics

A signature pad with undo, redo, SVG export and the keyboard "type your name" mode.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { SignaturePad, type SignaturePadApi } from '@salmonui/inputs/signature-pad';

// Undo / redo and SVG export through the SignaturePadApi ref; the last action is shown below the pad.
export default function SignaturePadBasicsDemo() {
  const pad = useRef<SignaturePadApi>(null);
  const [action, setAction] = useState('none');
  const [svgBytes, setSvgBytes] = useState<number | null>(null);
  return (
    <div style={{ display: 'grid', gap: 12, maxInlineSize: 420 }}>
      <SignaturePad ref={pad} label="Signature" description="Sign inside the box" backgroundColor="#ffffff" onValueChange={(_value, details) => setAction(details.action)} />
      <div style={{ display: 'flex', gap: 8 }}>
        <Button type="button" variant="outline" onClick={() => pad.current?.undo()}>
          Undo
        </Button>
        <Button type="button" variant="outline" onClick={() => pad.current?.redo()}>
          Redo
        </Button>
        <Button type="button" variant="outline" onClick={() => setSvgBytes(pad.current?.toSVG().length ?? null)}>
          Export SVG
        </Button>
      </div>
      <output>
        Last action: {action}
        {svgBytes === null ? '' : `, SVG ${svgBytes} bytes`}
      </output>
    </div>
  );
}
```

## Drawing

Mouse, touch and pen draw through Pointer Events with pointer capture.
Every sample of `getCoalescedEvents()` is kept, moves are drawn
once per animation frame and only the new segments of the live stroke are
painted, so React does not render while drawing (a median 120 Hz
move frame well under 2 ms). `touch-action: none` is set on the canvas only,
so the page still scrolls around the pad.

- `strokeColor` (default `'#000000'`).
- `minStrokeWidth` (0.5), `maxStrokeWidth` (2.5) and `velocity` (the
  velocity filter weight, 0.7) shape the line: faster strokes are
  thinner; a pen's `pressure` maps linearly between the two widths.
- `backgroundColor` fills the canvas and `backgroundImage` (a
  same-origin or CORS-enabled URL) is drawn under the strokes, stretched to
  the pad. Both are image data, not theme colors, so exported
  images look the same in light and dark mode.
- `height` (default 160) sizes the pad; the width follows the container.

## Value and changes

`onValueChange(value, details)` fires after a stroke, undo, redo, clear,
load, typed text or form reset, with the PNG data URL (`null` when
empty) and `details.action` `'stroke' | 'undo' | 'redo' | 'clear' | 'load'
| 'text' | 'reset'` (also `details.reason`) and `details.source`. A
controlled `value` (data URL) or `defaultValue` is drawn as the signature
image; an outside value starts a new undo baseline. Without
`value` the pad is uncontrolled.

### Live demo: Signature export and loading

Live demo: https://salmonui.dev/demos/inputs/signature-pad-export

SignaturePad stroke widths and velocity, a background color and image, a controlled value with api.load, api.clear and api.isEmpty, PNG and JPEG data URLs and blobs with or without the background, and strokes redrawn on resize.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Select } from '@salmonui/dropdowns/select';
import { SignaturePad, type SignaturePadApi } from '@salmonui/inputs/signature-pad';
import { Slider } from '@salmonui/inputs/slider';

// A signature line as an inline SVG data URL (image data, not theme); the
// pad stretches the image over its whole surface.
const RULED = `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="480" height="160" viewBox="0 0 480 160" preserveAspectRatio="none"><line x1="24" y1="124.5" x2="456" y2="124.5" stroke="#9db4d6" stroke-width="1"/></svg>')}`;

// A sample signature loaded through api.load().
const SAMPLE = `data:image/svg+xml,${encodeURIComponent(
  '<svg xmlns="http://www.w3.org/2000/svg" width="360" height="140"><path d="M20 100 C 50 20, 80 20, 90 90 S 130 140, 150 70 S 190 30, 210 90 S 260 120, 280 60 L 340 60" fill="none" stroke="#1d3557" stroke-width="3" stroke-linecap="round"/></svg>',
)}`;

const BACKGROUNDS = { white: '#ffffff', ivory: '#fffbea', none: 'transparent' } as const;
type Background = keyof typeof BACKGROUNDS;
const BACKGROUND_OPTIONS = [
  { value: 'white', label: 'white' },
  { value: 'ivory', label: 'ivory' },
  { value: 'none', label: 'transparent' },
];
const SLIDER_STYLE = { minInlineSize: 140 };

// Stroke widths and velocity, a background color and image, a controlled
// value with load / clear / isEmpty, PNG and JPEG data URLs and blobs with or
// without the background, and redraw on resize.
export default function SignaturePadExportDemo() {
  const pad = useRef<SignaturePadApi>(null);
  const [value, setValue] = useState<string | null>(null);
  const [minWidth, setMinWidth] = useState(0.5);
  const [maxWidth, setMaxWidth] = useState(2.5);
  const [velocity, setVelocity] = useState(0.7);
  const [background, setBackground] = useState<Background>('ivory');
  const [ruled, setRuled] = useState(true);
  const [withBackground, setWithBackground] = useState(true);
  const [wide, setWide] = useState(true);
  const [preview, setPreview] = useState<string | null>(null);
  const [status, setStatus] = useState('Draw a signature or load the sample.');
  return (
    <>
      <div className="demo-toolbar">
        <Slider label={`Min stroke width ${minWidth}`} min={0.1} max={3} step={0.1} value={minWidth} onValueChange={setMinWidth} style={SLIDER_STYLE} />
        <Slider label={`Max stroke width ${maxWidth}`} min={1} max={8} step={0.5} value={maxWidth} onValueChange={setMaxWidth} style={SLIDER_STYLE} />
        <Slider label={`Velocity ${velocity}`} min={0} max={1} step={0.1} value={velocity} onValueChange={setVelocity} style={SLIDER_STYLE} />
        <label>
          Background
          <Select aria-label="Background" data={BACKGROUND_OPTIONS} value={background} onValueChange={(next) => next != null && setBackground(next as Background)} />
        </label>
        <Checkbox checked={ruled} onCheckedChange={(checked) => setRuled(checked)}>
          Signature line
        </Checkbox>
        <Checkbox checked={wide} onCheckedChange={(checked) => setWide(checked)}>
          Wide pad
        </Checkbox>
      </div>
      <div style={{ maxInlineSize: wide ? 480 : 300, transition: 'max-inline-size 0.2s' }}>
        <SignaturePad
          ref={pad}
          label="Signature"
          description="Uncheck Wide pad after drawing: the strokes are redrawn at the new size"
          height={160}
          minStrokeWidth={minWidth}
          maxStrokeWidth={maxWidth}
          velocity={velocity}
          backgroundColor={BACKGROUNDS[background]}
          backgroundImage={ruled ? RULED : undefined}
          value={value}
          onValueChange={(next, details) => {
            setValue(next);
            setStatus(`onValueChange: ${details.action}, value ${next === null ? 'null' : `${next.slice(0, 22)}… (${next.length} chars)`}`);
          }}
        />
      </div>
      <div className="demo-toolbar" style={{ marginBlockStart: 12 }}>
        <Button type="button" variant="outline" onClick={() => void pad.current?.load(SAMPLE).then(() => setStatus('api.load(sample) finished'))}>
          Load sample
        </Button>
        <Button type="button" variant="outline" onClick={() => pad.current?.clear()}>
          api.clear()
        </Button>
        <Button type="button" variant="outline" onClick={() => setStatus(`api.isEmpty(): ${String(pad.current?.isEmpty())}`)}>
          api.isEmpty()
        </Button>
        <Button type="button" variant="outline" onClick={() => setValue(null)}>
          Set value to null
        </Button>
        <Checkbox checked={withBackground} onCheckedChange={(checked) => setWithBackground(checked)}>
          Export with background
        </Checkbox>
        <Button
          type="button"
          variant="outline"
          onClick={() => {
            const url = pad.current?.toDataURL('image/png', { background: withBackground }) ?? null;
            setPreview(url);
            setStatus(`toDataURL('image/png'): ${url?.length ?? 0} chars`);
          }}
        >
          PNG data URL
        </Button>
        <Button
          type="button"
          variant="outline"
          onClick={() => {
            const url = pad.current?.toDataURL('image/jpeg', { background: withBackground }) ?? null;
            setPreview(url);
            setStatus(`toDataURL('image/jpeg'): ${url?.length ?? 0} chars`);
          }}
        >
          JPEG data URL
        </Button>
        <Button type="button" variant="outline" onClick={() => void pad.current?.toBlob('image/png', { background: withBackground }).then((blob) => setStatus(`toBlob('image/png'): ${blob ? `${blob.type}, ${blob.size} bytes` : 'null'}`))}>
          PNG blob
        </Button>
      </div>
      <p className="demo-status" role="status">
        {status}
      </p>
      {preview ? (
        <img src={preview} alt="Exported signature" style={{ maxInlineSize: 240, border: '1px dashed var(--salmon-border-subtle)', background: 'repeating-conic-gradient(#ccc 0% 25%, #fff 0% 50%) 0 0 / 16px 16px' }} />
      ) : null}
    </>
  );
}
```

## API

`ref` is a `SignaturePadApi`:

| Member | Description |
| --- | --- |
| `element` | The root element |
| `undo()`, `redo()`, `canUndo()`, `canRedo()` | Stroke-stack history |
| `clear()`, `isEmpty()` | Clears the pad; reports whether it holds no strokes |
| `drawText(text, { fontFamily, fontSize })` | Replaces the signature with centered text, fitted to the pad without `fontSize` |
| `load(source)` | Loads a data URL or image URL as the signature; resolves when drawn |
| `toDataURL(type, { background })` | `'image/png'` (default) or `'image/jpeg'` at the canvas resolution; `background: false` leaves out `backgroundColor` / `backgroundImage` |
| `toBlob(type, { background })` | A `Promise<Blob \| null>` |
| `toSVG({ background })` | Vector markup from the stroke model in CSS pixels: one cubic Bézier path per segment, the same curves and widths as the canvas |
| `focus()` | Focuses the canvas |

## Form submission

With `name` a hidden input submits the PNG data URL (empty without a
signature). A signature PNG is typically 5 to 30 KB as a data URL,
so prefer `multipart/form-data` or upload `toBlob()` for large pads.
`required` (or `validation`) reports an empty pad through the field error;
`form` and `disabled` are forwarded. An uncontrolled pad restores
`defaultValue` on the owning form's `reset`.

### Live demo: Fields in a form

Live demo: https://salmonui.dev/demos/inputs/field-forms

Uncontrolled text, masked, number, radio, checkbox, switch, range slider, rating and signature fields in a native form - names and values submitted through FormData, a required incomplete mask blocking the submit, and a form reset restoring every default.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Form } from '@salmonui/inputs/form';
import { MaskedField } from '@salmonui/inputs/masked-field';
import { NumberField } from '@salmonui/inputs/number-field';
import { Radio, RadioGroup } from '@salmonui/inputs/radio-group';
import { Rating } from '@salmonui/inputs/rating';
import { Select } from '@salmonui/dropdowns/select';
import { SignaturePad } from '@salmonui/inputs/signature-pad';
import { Slider } from '@salmonui/inputs/slider';
import { Switch } from '@salmonui/inputs/switch';
import { TextField } from '@salmonui/inputs/text-field';

/** One line per FormData entry; long data URLs are shortened. */
function entriesOf(form: HTMLFormElement): string[] {
  return Array.from(new FormData(form), ([key, value]) => {
    const text = typeof value === 'string' ? value : `File ${value.name}`;
    return `${key} = ${text.length > 48 ? `${text.slice(0, 40)}… (${text.length} chars)` : JSON.stringify(text)}`;
  });
}

// Every field is uncontrolled inside a native form: names submit through
// FormData (custom-drawn controls through native or hidden inputs) and the
// Reset button restores each defaultValue and clears the shown errors.
export default function FieldFormsDemo() {
  const [submitValue, setSubmitValue] = useState<'raw' | 'masked'>('raw');
  const [entries, setEntries] = useState<readonly string[]>([]);
  const [status, setStatus] = useState('Change some fields, then submit or reset.');
  return (
    <>
      <div className="demo-toolbar">
        <label>
          MaskedField submitValue
          <Select aria-label="MaskedField submitValue" data={['raw', 'masked']} value={submitValue} onValueChange={(value) => value != null && setSubmitValue(value as 'raw' | 'masked')} />
        </label>
      </div>
      <Form
        aria-label="Delivery preferences"
        style={{ display: 'grid', gap: 16, maxInlineSize: 420 }}
        onSubmit={(event) => {
          event.preventDefault();
          setEntries(entriesOf(event.currentTarget));
          setStatus('Submitted: the FormData entries are listed below.');
        }}
        onValidate={({ valid }) => !valid && setStatus('Not submitted: fix the highlighted field.')}
        onReset={() => {
          setEntries([]);
          setStatus('Reset: every field is back to its defaultValue.');
        }}
      >
        <TextField name="name" label="Name" defaultValue="Ada Lovelace" required />
        <MaskedField name="phone" label="Phone" mask="(000) 000-0000" defaultValue="5551234567" required submitValue={submitValue} description="Required: an incomplete number blocks the submit" />
        <NumberField name="parcels" label="Parcels" defaultValue={2} min={1} max={9} />
        <RadioGroup name="slot" label="Delivery slot" defaultValue="am" orientation="horizontal">
          <Radio value="am">Morning</Radio>
          <Radio value="pm">Afternoon</Radio>
        </RadioGroup>
        <Checkbox name="extras" value="gift-wrap" defaultChecked>
          Gift wrap
        </Checkbox>
        <Switch name="notify" value="sms">
          Text me when it ships
        </Switch>
        <Slider name="window" label="Delivery window (hours)" defaultValue={[9, 17]} min={6} max={22} ticks={{ placement: 'after', majorStep: 4 }} />
        <Rating name="priority" label="Priority" defaultValue={2} count={3} />
        <SignaturePad name="signature" label="Signature" description="Optional: submitted as a PNG data URL" height={120} backgroundColor="#ffffff" />
        <div style={{ display: 'flex', gap: 8 }}>
          <Button type="submit" tone="primary">
            Submit
          </Button>
          <Button type="reset" variant="outline">
            Reset
          </Button>
        </div>
      </Form>
      <p className="demo-status" role="status">
        {status}
      </p>
      <pre className="demo-log" aria-label="Submitted FormData">
        {entries.length === 0 ? '(nothing submitted yet)' : entries.join('\n')}
      </pre>
    </>
  );
}
```

## Keyboard and screen readers

The canvas is focusable with `role="img"`, named by `label` and by
`localeText.empty` / `localeText.signed` ("Signature, empty" /
"Signature, signed") so screen readers hear whether it is signed.
"Type your name" (a toggle button, `aria-pressed`) shows a name field whose
text is drawn with `drawText` in `fontFamily` (default `'cursive'`); one
typing session is one undo step. `toolbar={false}` hides the toggle and the
Clear button for a custom UI.

| Key | Action |
| --- | --- |
| Tab / Shift+Tab | Canvas, then the "Type your name" and Clear buttons |
| Ctrl+Z / Cmd+Z (canvas focused) | Undo |
| Ctrl+Shift+Z / Cmd+Shift+Z, Ctrl+Y (canvas focused) | Redo |
| Enter / Space on "Type your name" | Shows or hides the name field |
| Enter / Space on Clear | Clears the pad |

## Resize and high-DPI screens

The backing store is sized to the canvas box times `devicePixelRatio` after
mount and on every resize or DPR change, and the strokes are redrawn.
The server renders the sized container and an empty canvas, so
the markup hydrates without a mismatch.

## Design notes

- no save-to-file method: triggering a download is application
  policy (file name, share sheet, or an upload instead). Build the download
  from `await api.toBlob('image/png')` and an object URL.
- no save event or Ctrl+S shortcut: a global shortcut conflicts
  with the browser and assistive technology. Call `api.toBlob()` from your
  own save button.

## Props

| Prop | Type | Default |
| --- | --- | --- |
| `value`, `defaultValue` | `string \| null` (data URL) | `null` |
| `onValueChange` | `(value, { source, reason, action }) => void` | |
| `strokeColor` | `string` | `'#000000'` |
| `minStrokeWidth`, `maxStrokeWidth` | `number` | `0.5`, `2.5` |
| `velocity` | `number` (0..1) | `0.7` |
| `backgroundColor`, `backgroundImage` | `string` | none |
| `height` | `number \| string` | `160` |
| `toolbar` | `boolean` | `true` |
| `fontFamily` | `string` | `'cursive'` |
| `name`, `form` | `string` | not submitted |
| `required`, `disabled`, `readOnly` | `boolean` | `false` |
| `label`, `description`, `errorMessage`, `invalid`, `validation` | see [Field](https://salmonui.dev/docs/inputs/field) | |
| `localeText` | `{ empty, signed, typeMode, typeLabel, clear, validation* }` | `'Signature, empty'`, `'Signature, signed'`, `'Type your name'`, `'Name'`, `'Clear'` |
| `size` | `'sm' \| 'md' \| 'lg'` | `'md'` |
| `dir`, `id`, `className`, `style` | root passthrough | |
| `classNames` | `{ label, surface, canvas, toolbar, description, error }` | |
| `ref` | `SignaturePadApi` | |

Full signatures: [`@salmonui/inputs/signature-pad` API reference](https://salmonui.dev/docs/reference/inputs/signature-pad).
