← Components

Selection and input

Signature pad

Draw a signature: the ink thins when you move fast, like a real pen. Clear fades the ink away. Type instead gives a text field.

Examples and variants

Draw or type

Draw with the mouse or a finger.

Example
function SignatureDemo() {
  return (
    <div className="w-full max-w-sm">
      <SignaturePad />
    </div>
  )
}

Spec drawing

Measured from the live component at default density. Each code maps to the token that sets it; change the token and the drawing follows.

Install

With the CLI

The shadcn CLI only delivers files: it copies our code from the Isotopi registry into your project and installs the packages it uses. Add the foundation once, then the component.

Terminal
npx shadcn@latest add https://isotopi.com/r/minimal.json
npx shadcn@latest add https://isotopi.com/r/signature-pad.json

By hand

No CLI needed. Add the foundation once (see Getting started), then follow these steps. They include every component this one builds on.

  1. Install the packages it uses.

    Terminal
    npm install @base-ui/react class-variance-authority cn lucide-react
  2. Copy these 2 files to the same paths in your project. Imports use the @/ alias for your project root.

    • components/ui/button.tsxbutton
      components/ui/button.tsx
      "use client"
      
      import { useRef, useState } from "react"
      import { Button as ButtonPrimitive } from "@base-ui/react/button"
      import { CheckIcon, XIcon } from "lucide-react"
      import { tokenMs } from "@/lib/motion/token-ms"
      import { cva, type VariantProps } from "class-variance-authority"
      import { cn } from "cn"
      
      // Minimal: no strokes on controls (DESIGN.md rule 11), token sizes, token focus ring,
      // liquid press squash instead of shadcn's translate-y nudge.
      // Every visual spec reads a component token (styles/tokens/components.css, --button-*).
      // Sizes: sm | md | lg (default = md). Variants: primary (default) | secondary | outline | ghost | link.
      const filled = {
        primary:
          "bg-(--button-primary-container) text-(--button-primary-label) hover:bg-(--button-primary-container-hover) active:bg-(--button-primary-container-pressed)",
        secondary:
          "bg-(--button-secondary-container) text-(--button-secondary-label) hover:bg-(--button-secondary-container-hover) active:bg-(--button-secondary-container-pressed) aria-expanded:bg-(--button-secondary-container-hover)",
      }
      
      const buttonVariants = cva(
        "liquid-press group/button relative inline-flex shrink-0 items-center justify-center overflow-hidden rounded-(--button-corner) border-solid border-(length:--button-stroke-width) border-(--stroke-color-default) bg-clip-padding text-(length:--button-label-size) [font-weight:var(--button-label-weight)] whitespace-nowrap outline-none select-none focus-visible:shadow-(--focus-ring) disabled:pointer-events-none disabled:bg-(--button-container-disabled) disabled:text-(--button-label-disabled) disabled:shadow-none aria-invalid:shadow-(--focus-ring-invalid) [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-(--button-icon-size)",
        {
          variants: {
            variant: {
              primary: filled.primary,
              default: filled.primary,
              secondary: filled.secondary,
              outline:
                "bg-(--button-outline-container) text-(--button-secondary-label) shadow-(--button-outline-elevation) hover:bg-(--button-outline-container-hover) active:bg-(--button-outline-container-pressed) aria-expanded:bg-(--button-outline-container-hover)",
              ghost: "text-(--button-secondary-label) hover:bg-(--button-ghost-container-hover) active:bg-(--button-ghost-container-pressed) aria-expanded:bg-(--button-ghost-container-hover) disabled:bg-transparent",
              destructive: "",
              link: "text-(--button-link-label) underline-offset-4 hover:underline disabled:bg-transparent",
            },
            size: {
              xs: "active:not-disabled:rounded-(--button-corner-pressed) h-(--button-height-xs) gap-(--button-gap-sm) px-(--button-padding-x-xs) text-(length:--button-label-size-sm) [&_svg:not([class*='size-'])]:size-(--button-icon-size-sm)",
              sm: "active:not-disabled:rounded-(--button-corner-pressed) h-(--button-height-sm) gap-(--button-gap-sm) px-(--button-padding-x-sm) [&_svg:not([class*='size-'])]:size-(--button-icon-size-sm)",
              md: "active:not-disabled:rounded-(--button-corner-pressed) h-(--button-height-md) gap-(--button-gap) px-(--button-padding-x-md) has-data-[icon=inline-end]:pe-(--button-padding-x-sm) has-data-[icon=inline-start]:ps-(--button-padding-x-sm)",
              default: "active:not-disabled:rounded-(--button-corner-pressed) h-(--button-height-md) gap-(--button-gap) px-(--button-padding-x-md) has-data-[icon=inline-end]:pe-(--button-padding-x-sm) has-data-[icon=inline-start]:ps-(--button-padding-x-sm)",
              lg: "active:not-disabled:rounded-(--button-corner-pressed) h-(--button-height-lg) gap-(--button-gap) px-(--button-padding-x-lg) has-data-[icon=inline-end]:pe-(--button-padding-x-md) has-data-[icon=inline-start]:ps-(--button-padding-x-md) [&_svg:not([class*='size-'])]:size-(--button-icon-size-lg)",
              icon: "size-(--icon-button-size-md) rounded-(--icon-button-corner)",
              "icon-xs": "size-(--button-height-xs) rounded-(--icon-button-corner) [&_svg:not([class*='size-'])]:size-(--button-icon-size-sm)",
              "icon-sm": "size-(--icon-button-size-sm) rounded-(--icon-button-corner) [&_svg:not([class*='size-'])]:size-(--button-icon-size-sm)",
              "icon-md": "size-(--icon-button-size-md) rounded-(--icon-button-corner)",
              "icon-lg": "size-(--icon-button-size-lg) rounded-(--icon-button-corner) [&_svg:not([class*='size-'])]:size-(--button-icon-size-lg)",
            },
            tone: {
              neutral: "",
              danger: "",
              success: "",
            },
          },
          // tone: colour intent on any variant (component-model.md §7). destructive = tone danger.
          compoundVariants: [
            {
              tone: "danger",
              variant: ["primary", "default", "secondary", "outline", "destructive"],
              className:
                "bg-(--button-danger-container) text-(--button-danger-label) shadow-none hover:bg-(--button-danger-container-hover) active:bg-(--button-danger-container-pressed) [--focus-ring-color:var(--color-danger)]",
            },
            {
              tone: "danger",
              variant: ["ghost", "link"],
              className: "text-(--button-danger-label) hover:bg-(--button-danger-container) active:bg-(--button-danger-container-hover) [--focus-ring-color:var(--color-danger)]",
            },
            {
              tone: "success",
              variant: ["primary", "default", "secondary", "outline"],
              className: "bg-(--button-success-container) text-(--button-success-label) shadow-none hover:bg-(--button-success-container-hover) active:bg-(--button-success-container-pressed)",
            },
          ],
          defaultVariants: {
            variant: "primary",
            size: "md",
            tone: "neutral",
          },
        }
      )
      
      type Wash = { id: number; x: number; y: number }
      type Status = "idle" | "loading" | "success" | "error"
      type ButtonProps = ButtonPrimitive.Props &
        VariantProps<typeof buttonVariants> & {
          /**
           * The button shows its own result inside a fixed width: spinner, then a
           * check or a cross. Prefer this to a toast (component-model.md §5).
           */
          status?: Status
          /** "hold": the click only happens after holding for --duration-fill (pointer, Space or Enter). */
          confirm?: "hold"
          /** Screen reader text for the success and error states. */
          statusLabel?: { success?: string; error?: string }
          /** @deprecated use status="loading" */
          loading?: boolean
          /** @deprecated use status="success" */
          success?: boolean
        }
      
      function Button({
        className,
        variant = "primary",
        size = "md",
        tone = "neutral",
        status: statusProp,
        confirm,
        statusLabel,
        loading = false,
        success = false,
        children,
        onClick,
        onPointerUp,
        onPointerDown,
        onPointerLeave,
        onKeyDown,
        onKeyUp,
        ...props
      }: ButtonProps) {
        const status: Status = statusProp ?? (loading ? "loading" : success ? "success" : "idle")
        const busy = status === "loading"
        const [wash, setWash] = useState<Wash | null>(null)
        const [held, setHeld] = useState(false)
        const holdTimer = useRef(0)
        const allowClick = useRef(false)
        const self = useRef<HTMLElement | null>(null)
        const resolvedTone = variant === "destructive" ? "danger" : tone
      
        function startHold(element: HTMLElement) {
          if (confirm !== "hold" || busy) return
          self.current = element
          setHeld(true)
          window.clearTimeout(holdTimer.current)
          holdTimer.current = window.setTimeout(() => {
            setHeld(false)
            allowClick.current = true
            self.current?.click()
            allowClick.current = false
          }, tokenMs("--duration-fill", element))
        }
      
        function stopHold() {
          if (confirm !== "hold") return
          setHeld(false)
          window.clearTimeout(holdTimer.current)
        }
      
        function handleClick(event: Parameters<NonNullable<ButtonProps["onClick"]>>[0]) {
          if (busy || (confirm === "hold" && !allowClick.current)) {
            event.preventDefault()
            return
          }
          onClick?.(event)
        }
      
        function handlePointerUp(event: Parameters<NonNullable<ButtonProps["onPointerUp"]>>[0]) {
          onPointerUp?.(event)
          stopHold()
          if (event.defaultPrevented || busy || confirm === "hold") return
          if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return
          const motion = event.currentTarget.closest<HTMLElement>("[data-motion]")?.dataset.motion
          if (motion === "calm" || motion === "still") return
          const rect = event.currentTarget.getBoundingClientRect()
          setWash({
            id: Date.now(),
            x: event.clientX - rect.left,
            y: event.clientY - rect.top,
          })
        }
      
        const showResult = status === "success" || status === "error"
      
        return (
          <ButtonPrimitive
            data-slot="button"
            data-icon={typeof size === "string" && size.startsWith("icon") ? "" : undefined}
            data-tone={resolvedTone}
            data-status={status}
            data-confirm={confirm}
            aria-busy={busy || undefined}
            aria-disabled={busy || undefined}
            {...props}
            className={cn(
              buttonVariants({ variant, size, tone: resolvedTone, className }),
              status === "error" && "animate-[isotope-nudge_var(--duration-fast)_var(--ease-out)]"
            )}
            onClick={handleClick}
            onPointerUp={handlePointerUp}
            onPointerDown={(event) => {
              onPointerDown?.(event)
              if (event.button === 0) startHold(event.currentTarget)
            }}
            onPointerLeave={(event) => {
              onPointerLeave?.(event)
              stopHold()
            }}
            onKeyDown={(event) => {
              onKeyDown?.(event)
              if (confirm === "hold" && (event.key === " " || event.key === "Enter") && !event.repeat) {
                startHold(event.currentTarget)
              }
            }}
            onKeyUp={(event) => {
              onKeyUp?.(event)
              if (event.key === " " || event.key === "Enter") stopHold()
            }}
          >
            {confirm === "hold" ? (
              <span
                aria-hidden
                data-held={held ? "" : undefined}
                className="hold-fill pointer-events-none absolute inset-y-0 left-0 w-full bg-current opacity-20"
              />
            ) : null}
            <span
              className={cn(
                "button-label relative inline-flex items-center justify-center gap-[inherit]",
                (busy || showResult) &&
                  "opacity-0 blur-(--motion-blur-enter) transition-[opacity,filter] duration-(--duration-fast) ease-(--ease-out)"
              )}
            >
              {children}
              {confirm === "hold" ? <span className="sr-only">(hold to confirm)</span> : null}
            </span>
            {showResult ? (
              <span className="button-success absolute inset-0 inline-flex items-center justify-center" role="status">
                <span className="sr-only">
                  {status === "success" ? statusLabel?.success ?? "Done" : statusLabel?.error ?? "Failed"}
                </span>
                {status === "success" ? <CheckIcon aria-hidden /> : <XIcon aria-hidden />}
              </span>
            ) : null}
            {busy ? (
              <span className="absolute inset-0 inline-flex items-center justify-center gap-inline-xs">
                <span className="sr-only">Loading</span>
                {[0, 1, 2].map((dot) => (
                  <span
                    key={dot}
                    aria-hidden
                    className="size-inline-xs rounded-full bg-current animate-[isotope-pulse_var(--duration-pulse)_var(--ease-out)_infinite]"
                    style={{ animationDelay: `calc(var(--duration-stagger) * ${dot})` }}
                  />
                ))}
              </span>
            ) : null}
            {wash ? (
              <span
                key={wash.id}
                aria-hidden
                onAnimationEnd={() => setWash(null)}
                className="pointer-events-none absolute size-[calc(var(--size-control-lg)*4)] rounded-full bg-current animate-[isotope-wash_var(--duration-settle)_var(--ease-out)_both]"
                style={{ left: wash.x, top: wash.y }}
              />
            ) : null}
          </ButtonPrimitive>
        )
      }
      
      export { Button, buttonVariants }
      export type { ButtonProps }
      
    • components/ui/signature-pad.tsxsignature-pad
      components/ui/signature-pad.tsx
      "use client"
      
      import * as React from "react"
      import { cn } from "cn"
      import { Button } from "@/components/ui/button"
      import { motionLevel } from "@/lib/overlay"
      
      /*
        Signature pad: draw a signature. The stroke is thinner when you move fast,
        like real ink. Clear makes the ink fade and shrink toward the centre.
        "Type instead" gives a text field for keyboard and screen reader users.
      */
      function SignaturePad({
        onChange,
        label = "Signature",
        className,
      }: {
        /** PNG data URL of the drawing, or the typed name. Empty string when cleared. */
        onChange?: (value: string) => void
        label?: string
        className?: string
      }) {
        const canvasRef = React.useRef<HTMLCanvasElement>(null)
        const last = React.useRef<{ x: number; y: number; t: number; w: number } | null>(null)
        const [typed, setTyped] = React.useState<string | null>(null)
        const [clearing, setClearing] = React.useState(false)
        const [empty, setEmpty] = React.useState(true)
      
        React.useEffect(() => {
          const canvas = canvasRef.current
          if (!canvas) return
          const ratio = window.devicePixelRatio || 1
          canvas.width = canvas.offsetWidth * ratio
          canvas.height = canvas.offsetHeight * ratio
          canvas.getContext("2d")?.scale(ratio, ratio)
        }, [typed])
      
        function point(event: React.PointerEvent<HTMLCanvasElement>) {
          const box = event.currentTarget.getBoundingClientRect()
          return { x: event.clientX - box.left, y: event.clientY - box.top, t: performance.now() }
        }
      
        function clear() {
          const canvas = canvasRef.current
          const finish = () => {
            canvas?.getContext("2d")?.clearRect(0, 0, canvas.width, canvas.height)
            setClearing(false)
            setEmpty(true)
            onChange?.("")
          }
          if (!canvas || motionLevel(canvas) === "still") return finish()
          setClearing(true)
          canvas.addEventListener("animationend", finish, { once: true })
        }
      
        if (typed !== null) {
          return (
            <div className={cn("flex w-full flex-col gap-2", className)}>
              <label className="text-sm font-medium" htmlFor="signature-typed">
                {label}
              </label>
              <input
                id="signature-typed"
                value={typed}
                onChange={(event) => {
                  setTyped(event.target.value)
                  onChange?.(event.target.value)
                }}
                placeholder="Type your full name"
                className="h-(--field-height-lg) rounded-(--field-corner) bg-(--field-container) px-(--field-padding-x) font-serif text-lg italic outline-none focus-visible:bg-(--field-container-focus) focus-visible:shadow-(--field-focus-shadow)"
              />
              <Button size="sm" variant="ghost" className="self-start" onClick={() => setTyped(null)}>
                Draw instead
              </Button>
            </div>
          )
        }
      
        return (
          <div data-slot="signature-pad" className={cn("flex w-full flex-col gap-2", className)}>
            <canvas
              ref={canvasRef}
              aria-label={`${label}. Draw with a pointer, or choose Type instead.`}
              role="img"
              data-clearing={clearing || undefined}
              className="signature-canvas h-(--signature-height) w-full touch-none rounded-(--signature-corner) bg-(--signature-container) shadow-1"
              onPointerDown={(event) => {
                event.currentTarget.setPointerCapture(event.pointerId)
                last.current = { ...point(event), w: 2.5 }
              }}
              onPointerMove={(event) => {
                const prev = last.current
                const ctx = event.currentTarget.getContext("2d")
                if (!prev || !ctx) return
                const p = point(event)
                const speed = Math.hypot(p.x - prev.x, p.y - prev.y) / Math.max(1, p.t - prev.t)
                const w = prev.w * 0.6 + Math.max(1, 4 - speed * 2) * 0.4
                ctx.strokeStyle = getComputedStyle(event.currentTarget).getPropertyValue("--signature-ink").trim() || "currentColor"
                ctx.lineCap = "round"
                ctx.lineWidth = w
                ctx.beginPath()
                ctx.moveTo(prev.x, prev.y)
                ctx.lineTo(p.x, p.y)
                ctx.stroke()
                last.current = { ...p, w }
                if (empty) setEmpty(false)
              }}
              onPointerUp={(event) => {
                last.current = null
                onChange?.(event.currentTarget.toDataURL("image/png"))
              }}
            />
            <div className="flex justify-between">
              <Button size="sm" variant="ghost" onClick={() => setTyped("")}>
                Type instead
              </Button>
              <Button size="sm" variant="secondary" disabled={empty} onClick={clear}>
                Clear
              </Button>
            </div>
          </div>
        )
      }
      
      export { SignaturePad }
      

Imports

What the examples on this page import:

Imports
import { Badge } from "@/components/ui/badge"
import { PagePeel } from "@/components/ui/page-peel"
import { PullToRefresh } from "@/components/ui/pull-to-refresh"
import { SignaturePad } from "@/components/ui/signature-pad"
import { SortableList } from "@/components/ui/sortable-list"
import { SwipeDeck } from "@/components/ui/swipe-deck"
import { tokenMs } from "@/lib/motion/token-ms"

Anatomy

  1. 1Canvas · --signature-container, --signature-corner, --signature-height; ink --signature-ink.
  2. 2Clear and Type instead · Buttons.

Props

PropTypeDefaultDescription
onChange(value: string) => void—PNG data URL, or the typed name.
labelstring"Signature"Accessible name.

Tokens

Every visual spec is a component token in styles/tokens/components.css, pointing at a semantic token. Change a token to restyle the component; themes change the semantic layer.

TokenPoints toLightDark
--signature-inkvar(--on-surface)oklch(0.22 0.01 260)oklch(1 0 0)
--signature-containervar(--surface-container-lowest)oklch(1 0 0)oklch(0.14 0 0)
--signature-cornervar(--shape-lg)22pxsame
--signature-heightcalc(var(--space-32) + var(--space-8))calc(var(--space-32) + var(--space-8))same

Motion

TriggerWhat happensTokens
ClearInk fades, shrinks and blurs away.--duration-medium

Calm keeps the motion without overshoot. Still (and reduced motion) keeps a designed frame with no movement.

Accessibility

  • Type instead is always offered.

Usage

Do

  • Use where a drawn signature is expected.

Don’t

  • Don't require drawing for legal consent without a typed option.

Code

components/ui/signature-pad.tsx
"use client"

import * as React from "react"
import { cn } from "cn"
import { Button } from "@/components/ui/button"
import { motionLevel } from "@/lib/overlay"

/*
  Signature pad: draw a signature. The stroke is thinner when you move fast,
  like real ink. Clear makes the ink fade and shrink toward the centre.
  "Type instead" gives a text field for keyboard and screen reader users.
*/
function SignaturePad({
  onChange,
  label = "Signature",
  className,
}: {
  /** PNG data URL of the drawing, or the typed name. Empty string when cleared. */
  onChange?: (value: string) => void
  label?: string
  className?: string
}) {
  const canvasRef = React.useRef<HTMLCanvasElement>(null)
  const last = React.useRef<{ x: number; y: number; t: number; w: number } | null>(null)
  const [typed, setTyped] = React.useState<string | null>(null)
  const [clearing, setClearing] = React.useState(false)
  const [empty, setEmpty] = React.useState(true)

  React.useEffect(() => {
    const canvas = canvasRef.current
    if (!canvas) return
    const ratio = window.devicePixelRatio || 1
    canvas.width = canvas.offsetWidth * ratio
    canvas.height = canvas.offsetHeight * ratio
    canvas.getContext("2d")?.scale(ratio, ratio)
  }, [typed])

  function point(event: React.PointerEvent<HTMLCanvasElement>) {
    const box = event.currentTarget.getBoundingClientRect()
    return { x: event.clientX - box.left, y: event.clientY - box.top, t: performance.now() }
  }

  function clear() {
    const canvas = canvasRef.current
    const finish = () => {
      canvas?.getContext("2d")?.clearRect(0, 0, canvas.width, canvas.height)
      setClearing(false)
      setEmpty(true)
      onChange?.("")
    }
    if (!canvas || motionLevel(canvas) === "still") return finish()
    setClearing(true)
    canvas.addEventListener("animationend", finish, { once: true })
  }

  if (typed !== null) {
    return (
      <div className={cn("flex w-full flex-col gap-2", className)}>
        <label className="text-sm font-medium" htmlFor="signature-typed">
          {label}
        </label>
        <input
          id="signature-typed"
          value={typed}
          onChange={(event) => {
            setTyped(event.target.value)
            onChange?.(event.target.value)
          }}
          placeholder="Type your full name"
          className="h-(--field-height-lg) rounded-(--field-corner) bg-(--field-container) px-(--field-padding-x) font-serif text-lg italic outline-none focus-visible:bg-(--field-container-focus) focus-visible:shadow-(--field-focus-shadow)"
        />
        <Button size="sm" variant="ghost" className="self-start" onClick={() => setTyped(null)}>
          Draw instead
        </Button>
      </div>
    )
  }

  return (
    <div data-slot="signature-pad" className={cn("flex w-full flex-col gap-2", className)}>
      <canvas
        ref={canvasRef}
        aria-label={`${label}. Draw with a pointer, or choose Type instead.`}
        role="img"
        data-clearing={clearing || undefined}
        className="signature-canvas h-(--signature-height) w-full touch-none rounded-(--signature-corner) bg-(--signature-container) shadow-1"
        onPointerDown={(event) => {
          event.currentTarget.setPointerCapture(event.pointerId)
          last.current = { ...point(event), w: 2.5 }
        }}
        onPointerMove={(event) => {
          const prev = last.current
          const ctx = event.currentTarget.getContext("2d")
          if (!prev || !ctx) return
          const p = point(event)
          const speed = Math.hypot(p.x - prev.x, p.y - prev.y) / Math.max(1, p.t - prev.t)
          const w = prev.w * 0.6 + Math.max(1, 4 - speed * 2) * 0.4
          ctx.strokeStyle = getComputedStyle(event.currentTarget).getPropertyValue("--signature-ink").trim() || "currentColor"
          ctx.lineCap = "round"
          ctx.lineWidth = w
          ctx.beginPath()
          ctx.moveTo(prev.x, prev.y)
          ctx.lineTo(p.x, p.y)
          ctx.stroke()
          last.current = { ...p, w }
          if (empty) setEmpty(false)
        }}
        onPointerUp={(event) => {
          last.current = null
          onChange?.(event.currentTarget.toDataURL("image/png"))
        }}
      />
      <div className="flex justify-between">
        <Button size="sm" variant="ghost" onClick={() => setTyped("")}>
          Type instead
        </Button>
        <Button size="sm" variant="secondary" disabled={empty} onClick={clear}>
          Clear
        </Button>
      </div>
    </div>
  )
}

export { SignaturePad }