Skip to content

About

A modern, lightweight, and event-driven JavaScript library for creating beautiful, pressure-sensitive digital signatures. Built with an ES6 Class structure, a clean event-based architecture using Pointer Events, and extensive customization options.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

7 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 

Repository files navigation

czSignature.js

A modern, lightweight, and event-driven JavaScript library for creating beautiful, pressure-sensitive digital signatures. Built with an ES6 Class structure, a clean event-based architecture using Pointer Events, and extensive customization options.

License: MIT


✨ Features

  • Modern JavaScript: Written in a clean, modern ES6 Class structure with private fields and uses Pointer Events for unified input.
  • ✍️ Natural Pen Feel: Produces smooth, variable-width strokes with natural start/end taper — just like a real pen.
  • 🖊️ Pressure Sensitive: Captures stylus pressure for natural strokes, with a fallback to velocity-based width for standard inputs like a mouse.
  • ⚡ Smooth Rendering: Fill-based polygon rendering engine with outline offset algorithm — no jagged edges or notches.
  • Event-Driven Architecture: Emits events like drawStart, drawEnd, and clear for robust user interface integration.
  • Highly Customizable: Control all aspects, from colors and brush dynamics to smoothing algorithms, taper, and velocity sensitivity.
  • 🔧 Advanced Export: Trim whitespace around the signature, override colors on-the-fly, and set custom DPI for high-quality image exports.
  • 📱 Responsive: Automatically adjusts when the canvas size is changed, with optimized layouts for mobile and tablet.
  • 💾 Serialization: Easily save the raw signature data as a JavaScript object with toData() and load it back with fromData() (deep copy).
  • Multiple Outputs: Export signatures as clean, vector-based SVG files or high-DPI PNG/JPEG Data URLs.
  • No Dependencies: Lightweight and self-contained.

🎨 Demo

The included index.html provides a full-featured interactive demo with:

  • Three Themes: 🌙 Dark, ☀️ Light, 💎 Glass (Liquid Glass with frosted effect)
  • Live Settings Panel: Adjust brush dynamics, smoothing, and export options in real-time
  • Preview & Quick Download: Export as SVG, PNG, or JPG with one click
  • Save/Load Data: Serialize and restore signatures via JSON
  • Responsive Layout: Optimized for desktop, tablet, and mobile

How to Use

1. HTML Setup

You only need a single <canvas> element. Ensure it has the touch-action: none; style to prevent unwanted scrolling on touch devices.

<canvas id="signature-area" style="width: 100%; height: 250px; border: 1px solid #ccc; touch-action: none;"></canvas>

<script src="czSignature.js"></script>
<script src="your-app-logic.js"></script> 

2. Initialization

Instantiate the czSignature class by passing the canvas element and an optional configuration object.

// Inside your-app-logic.js
const canvas = document.getElementById('signature-area');

const options = {
    penColor: '#0033a0',
    maxWidth: 4.0,
    backgroundColor: '#f8f9fa',
    velocitySensitivity: 5.0,
    taperStart: 3,
    taperEnd: 3,
    smoothingMode: 'live'
};

const signatureComponent = new czSignature(canvas, options);

API Reference

Properties (Options)

These properties can be passed during initialization or updated later using the updateOptions() method.

Brush Dynamics

Property Type Default Description
penColor String '#000000' The color of the signature stroke.
backgroundColor String '#ffffff' The background color of the canvas.
minWidth Number 0.5 The minimum width of the brush (fastest strokes).
maxWidth Number 2.5 The maximum width of the brush (slowest strokes).
velocityFilterWeight Number 0.5 Smoothes brush width changes (0-1). Lower = more responsive.
velocitySensitivity Number 5.0 How aggressively line width responds to speed (1-10). Higher = thinner lines at lower speeds.
taperStart Number 3 Number of points to apply pen touchdown taper (thin → thick). Set 0 to disable.
taperEnd Number 3 Number of points to apply pen liftoff taper (thick → thin tail). Set 0 to disable.
dotSize Number 2.0 The radius of a single-tap dot.
pressureSupport Boolean false Enables stylus pressure sensitivity. If false, width is based on velocity.

Smoothing

Property Type Default Description
smoothingMode String 'post' 'post' (smoothes on end) or 'live' (smoothes during draw).
smoothingRatio Number 0.5 Amount of curve smoothing (0-1).
smoothingFadePoints Number 4 Points at start/end of a stroke with less smoothing.
minDistance Number 0.8 Minimum distance between points before a new one is recorded.

Export Options

Property Type Default Description
dpi Number 300 DPI for raster image exports (PNG/JPEG).
trimOutput Boolean false If true, crops the output to the signature bounds.
trimPadding Number 16 Padding (px) around a trimmed signature.
outputPenColor String null Overrides the pen color for export. null = use live penColor.
outputBackgroundColor String null Overrides background for export. Can be 'transparent'.

Methods

  • clear(): Clears the canvas.
  • undo(): Removes the last stroke.
  • isEmpty(): Returns true if the canvas is empty.
  • updateOptions(newOptions): Updates the instance with new options.
  • toData(): Returns a deep copy of the raw signature data as an array of stroke objects.
  • fromData(data): Draws a signature from a data array (deep copied internally).
  • toSVG(): Returns the signature as an SVG string.
  • toDataURL(format): Returns the signature as a Base64 Data URL.
    • format (String, optional): 'image/png' (default) or 'image/jpeg'.
  • on(eventName, callback): Registers an event listener.
  • off(eventName, callback): Removes a previously registered event listener.
  • destroy(): Removes all event listeners and cleans up resources.

Advanced Export Workflow

To use export-specific options like trimOutput or outputPenColor, temporarily update the options, export, and then restore.

// 1. Get a snapshot of the current live options
const originalOptions = { ...signatureComponent.options };

// 2. Set the desired export options
signatureComponent.updateOptions({
    trimOutput: true,
    outputBackgroundColor: 'transparent',
    outputPenColor: '#000000',
    dpi: 600
});

// 3. Generate the image or SVG
const dataURL = signatureComponent.toDataURL('image/png');
// const svg = signatureComponent.toSVG();

// 4. (Important!) Restore the original options
signatureComponent.updateOptions(originalOptions);

Serialization Example

Save and load a signature's raw data.

// Save the signature data
const signatureData = signatureComponent.toData();
const jsonString = JSON.stringify(signatureData);
// Store jsonString in localStorage or a database

// ... later on ...

// Load the signature data back
const loadedData = JSON.parse(jsonString);
signatureComponent.fromData(loadedData);

Events

Listen to events using .on(). Remove listeners with .off().

Event Data Description
clear — Fired when the canvas is cleared.
undo { strokesLeft: Number } Fired after a stroke is removed.
drawStart — Fired when a new stroke begins.
drawEnd { stroke: Object } Fired when a stroke is completed.
resize — Fired after the canvas adjusts to a window resize.

Example:

signatureComponent.on('drawEnd', () => {
    console.log('A new stroke has been completed!');
    document.getElementById('save-button').disabled = false;
});

signatureComponent.on('clear', () => {
    console.log('The signature area has been cleared.');
    document.getElementById('save-button').disabled = true;
});

Rendering Engine

czSignature uses a fill-based polygon rendering engine instead of traditional stroke-based rendering. This eliminates visible notches/steps when line width changes dynamically.

How it works:

  1. Calculates two offset outlines (left & right) along the stroke path using normal vectors
  2. Applies exponential decay velocity-to-width mapping for natural thick→thin transitions
  3. Adds rounded semicircle caps at start and end
  4. Connects outlines with smooth quadratic curves
  5. Fills the entire shape as a single polygon

This same technique is used for both canvas rendering and SVG export, ensuring visual consistency.


License

This project is licensed under the MIT License.

MIT License

Copyright (c) 2025 Cyberzilla

About

A modern, lightweight, and event-driven JavaScript library for creating beautiful, pressure-sensitive digital signatures. Built with an ES6 Class structure, a clean event-based architecture using Pointer Events, and extensive customization options.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages