Signature pad
Draw and export a signature with stroke undo and redo, alongside an always available typed name field.
pnpm dlx shadcn@latest add @haze/signature-pad---
import { cn } from "../../../lib/haze/utils";
interface Props {
id: string;
name?: string;
drawingName?: string;
label?: string;
signer?: string;
required?: boolean;
disabled?: boolean;
fileName?: string;
class?: string;
[key: string]: unknown;
}
const { id, name = id, drawingName = `${name}-drawing`, label = "Your signature", signer = "", required = false, disabled, fileName = "signature", class: className, ...rest } = Astro.props;
const button = "h-8 cursor-pointer rounded-lg border border-frame bg-field px-3 text-[0.8125rem]/5 font-medium text-foreground shadow-key transition-[background-color,scale] duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-[0.97] active:duration-75 motion-reduce:transition-none motion-reduce:active:scale-100 disabled:cursor-not-allowed disabled:opacity-50";
---
<fieldset data-haze-signature-pad data-file-name={fileName} disabled={disabled} class={cn("grid w-full min-w-0 gap-3", className)}>
<legend class="mb-3 text-[1.0625rem]/6 font-medium text-foreground">{label}</legend>
<div data-drawing-tools hidden class="grid gap-2">
<p id={`${id}-hint`} class="text-xs text-muted-foreground">Draw with a pointer, or type your full name below. Ctrl/⌘ Z undoes a stroke when the pad has focus.</p>
<div class="relative">
<canvas data-signature-canvas width="600" height="260" tabindex="0" role="img" aria-label="Signature drawing area. A typed name is available below." aria-describedby={`${id}-hint`} class="h-44 w-full touch-none rounded-xl border border-frame-input bg-field text-foreground transition-[border-color,box-shadow] duration-150 ease-snappy hover:border-frame-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/24 focus-visible:outline-hidden">Type your name in the field below to provide a signature.</canvas>
<span aria-hidden="true" class="pointer-events-none absolute inset-x-4 bottom-12 border-t border-dashed border-border-strong"></span>
<span aria-hidden="true" class="pointer-events-none absolute inset-x-4 bottom-7 text-xs/4 text-muted-foreground">Sign above the line</span>
</div>
<div class="flex flex-wrap gap-2"><button type="button" data-signature-undo disabled class={button}>Undo</button><button type="button" data-signature-redo disabled class={button}>Redo</button><button type="button" data-signature-clear disabled class={button}>Clear drawing</button><button type="button" data-signature-download disabled class={button}>Save PNG</button></div>
<input type="hidden" name={drawingName} data-signature-value value="" />
</div>
<div class="grid gap-2"><label for={id} class="text-[0.8125rem]/5 font-medium text-foreground">Type your full name{required && <span aria-hidden="true"> *</span>}</label><input id={id} name={name} type="text" autocomplete="name" value={signer} required={required} class="h-10 w-full min-w-0 rounded-lg border border-frame-input bg-field px-3 text-sm text-foreground transition-[border-color,box-shadow] duration-150 ease-snappy hover:border-frame-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/24 focus-visible:outline-hidden disabled:opacity-50" {...rest} /></div>
<p data-signature-status role="status" class="text-xs text-muted-foreground">Your typed name is submitted with the form.</p>
</fieldset>
<script>
type SignaturePoint = { x: number; y: number; pressure: number };
function enhance(root: HTMLFieldSetElement) {
if (root.hasAttribute("data-enhanced")) return;
const canvas = root.querySelector<HTMLCanvasElement>("[data-signature-canvas]");
const value = root.querySelector<HTMLInputElement>("[data-signature-value]");
const status = root.querySelector<HTMLElement>("[data-signature-status]");
const undo = root.querySelector<HTMLButtonElement>("[data-signature-undo]");
const redo = root.querySelector<HTMLButtonElement>("[data-signature-redo]");
const clear = root.querySelector<HTMLButtonElement>("[data-signature-clear]");
const save = root.querySelector<HTMLButtonElement>("[data-signature-download]");
const context = canvas?.getContext("2d");
if (!canvas || !context || !value || !status || !undo || !redo || !clear || !save) return;
let strokes: SignaturePoint[][] = [], future: SignaturePoint[][] = [];
let current: SignaturePoint[] | null = null, pointer: number | null = null;
const draw = () => {
context.clearRect(0, 0, canvas.width, canvas.height);
context.strokeStyle = getComputedStyle(root).getPropertyValue("--foreground").trim();
context.fillStyle = context.strokeStyle;
context.lineCap = "round"; context.lineJoin = "round";
[...strokes, ...(current ? [current] : [])].forEach((stroke) => {
if (!stroke.length) return;
const first = stroke[0];
if (stroke.length === 1) { context.beginPath(); context.arc(first.x * canvas.width, first.y * canvas.height, 2, 0, Math.PI * 2); context.fill(); }
else for (let index = 1; index < stroke.length; index++) { const previous = stroke[index - 1], point = stroke[index]; context.lineWidth = 2 + point.pressure * 3; context.beginPath(); context.moveTo(previous.x * canvas.width, previous.y * canvas.height); context.lineTo(point.x * canvas.width, point.y * canvas.height); context.stroke(); }
});
};
const sync = (message: string) => {
draw(); value.value = strokes.length ? canvas.toDataURL("image/png") : "";
undo.disabled = !strokes.length || root.disabled; redo.disabled = !future.length || root.disabled;
clear.disabled = !strokes.length || root.disabled; save.disabled = !strokes.length || root.disabled;
status.textContent = message;
canvas.setAttribute("aria-label", `Signature drawing area, ${strokes.length} ${strokes.length === 1 ? "stroke" : "strokes"}. A typed name is available below.`);
root.dispatchEvent(new CustomEvent("haze:signature-change", { bubbles: true, detail: { strokes: strokes.length, dataUrl: value.value } }));
};
const point = (event: PointerEvent): SignaturePoint => { const rect = canvas.getBoundingClientRect(); return { x: Math.max(0, Math.min(1, (event.clientX - rect.left) / rect.width)), y: Math.max(0, Math.min(1, (event.clientY - rect.top) / rect.height)), pressure: event.pressure || 0.5 }; };
canvas.addEventListener("pointerdown", (event) => {
if (root.closest("fieldset:disabled") || !event.isPrimary || event.button !== 0) return;
pointer = event.pointerId; current = [point(event)]; canvas.setPointerCapture(event.pointerId); canvas.focus({ preventScroll: true }); draw();
});
canvas.addEventListener("pointermove", (event) => {
if (pointer !== event.pointerId || !current) return;
const events = typeof event.getCoalescedEvents === "function" ? event.getCoalescedEvents() : [event];
(events.length ? events : [event]).forEach((entry) => current!.push(point(entry))); draw();
});
const finish = (event: PointerEvent, canceled: boolean) => {
if (pointer !== event.pointerId || !current) return;
if (!canceled) { current.push(point(event)); strokes.push(current); future = []; }
current = null; pointer = null;
if (canvas.hasPointerCapture(event.pointerId)) canvas.releasePointerCapture(event.pointerId);
sync(canceled ? "Stroke canceled." : `${strokes.length} ${strokes.length === 1 ? "stroke" : "strokes"} drawn.`);
};
canvas.addEventListener("pointerup", (event) => finish(event, false));
canvas.addEventListener("pointercancel", (event) => finish(event, true));
canvas.addEventListener("lostpointercapture", (event) => { if (current) finish(event, true); });
const undoStroke = () => { const stroke = strokes.pop(); if (stroke) { future.push(stroke); sync("Last stroke undone."); } };
undo.addEventListener("click", undoStroke);
redo.addEventListener("click", () => { const stroke = future.pop(); if (stroke) { strokes.push(stroke); sync("Stroke restored."); } });
clear.addEventListener("click", () => { strokes = []; future = []; current = null; pointer = null; sync("Drawing cleared. Your typed name is unchanged."); });
canvas.addEventListener("keydown", (event) => { if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "z") { event.preventDefault(); if (event.shiftKey) redo.click(); else undoStroke(); } if (event.key === "Escape" && current) { current = null; pointer = null; draw(); status.textContent = "Stroke canceled."; } });
save.addEventListener("click", () => canvas.toBlob((blob) => { if (!blob) return; const url = URL.createObjectURL(blob); const link = document.createElement("a"); link.href = url; link.download = `${root.dataset.fileName || "signature"}.png`; link.click(); setTimeout(() => URL.revokeObjectURL(url), 1000); status.textContent = "Signature PNG saved."; }, "image/png"));
root.form?.addEventListener("reset", () => queueMicrotask(() => { strokes = []; future = []; current = null; pointer = null; sync("Signature drawing reset."); }));
root.querySelector<HTMLElement>("[data-drawing-tools]")!.hidden = false;
root.setAttribute("data-enhanced", ""); sync("Draw a signature or type your full name below.");
}
const init = () => document.querySelectorAll<HTMLFieldSetElement>("[data-haze-signature-pad]").forEach(enhance);
init();
if (!document.documentElement.hasAttribute("data-haze-signature-pad-listener")) {
document.documentElement.setAttribute("data-haze-signature-pad-listener", "");
document.addEventListener("astro:page-load", init);
}
</script>When to use
- A delivery or acknowledgment form benefits from an optional drawn mark plus a typed signer name.
- A local signature drawing needs PNG export and a form value without an external drawing dependency.
When not to use
- Use input when a typed name is sufficient for the acknowledgment.
- Use a dedicated signing service when identity verification, audit trails or legal signing workflows are required.
Installation
Add the Haze registry to components.json once, then install Signature pad with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/signature-padnpx shadcn@latest add @haze/signature-padyarn dlx shadcn@latest add @haze/signature-padbunx --bun shadcn@latest add @haze/signature-padFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| id* | string | – | Unique caller supplied prefix for the control and its associated content. |
| name | string | id | Name submitted by the native form control. |
| drawingName | string | name-drawing | Name of the hidden PNG data URL field. |
| label | string | Your signature | Legend for the drawing and name controls. |
| signer | string | Empty | Initial typed full name. |
| required | boolean | false | Requires the typed name; drawing remains optional. |
| disabled | boolean | false | Prevents user changes through the native disabled state. |
| fileName | string | signature | Base file name used for PNG download. |
| class | string | – | Additional classes on this component's outer wrapper. |
| [key: string] | unknown | – | Other attributes applied to the typed name input. |
Keyboard interactions
- Ctrl/⌘ Z on the pad
- Undo the latest stroke; add Shift to redo.
- Escape on the pad
- Cancel an in progress stroke.
- Tab
- Reach the drawing tools and the equivalent typed name field.
Accessibility
- The typed full name is an equivalent always available input; a signature never requires the ability to draw with a pointer.
- Undo, redo, clear and PNG export are labelled buttons, and the drawing's accessible name includes the stroke count.
- Only the canvas disables touch scrolling; pen, mouse and primary touch strokes use pointer capture and a canceled stroke is discarded.
- Clearing the drawing preserves the typed name, while a form reset clears the drawing and restores native field defaults.
- The PNG field and haze:signature-change event carry local drawing data; the component performs no remote signing or upload.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI component "Signature pad" with `npx shadcn@latest add @haze/signature-pad`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import SignaturePad from "@/components/haze/ui/signature-pad.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: http://localhost:4329/ui/signature-pad.md
Customize with real content
Adapt the Haze signature-pad ui for our product. Replace the demo values of these props with our real content: id, name, drawingName, label, signer, required, disabled, fileName, class, [key: string]. Keep the layout, the heading level rules and these accessibility details: The typed full name is an equivalent always available input; a signature never requires the ability to draw with a pointer. Undo, redo, clear and PNG export are labelled buttons, and the drawing's accessible name includes the stroke count. Only the canvas disables touch scrolling; pen, mouse and primary touch strokes use pointer capture and a canceled stroke is discarded. Clearing the drawing preserves the typed name, while a form reset clears the drawing and restores native field defaults. The PNG field and haze:signature-change event carry local drawing data; the component performs no remote signing or upload. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using signature-pad, check it fits: use it when a delivery or acknowledgment form benefits from an optional drawn mark plus a typed signer name.; a local signature drawing needs png export and a form value without an external drawing dependency.. Avoid it when use input when a typed name is sufficient for the acknowledgment.; use a dedicated signing service when identity verification, audit trails or legal signing workflows are required.. Alternatives: @haze/input, @haze/textarea, @haze/file-upload.
Dependencies
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.