Dev.to WebDev πŸ›  Dev πŸ‘ 2 πŸ“– 6 min read

Building a Zero-Dependency E-Signature Pad in Pure JS: Quadratic Smoothing, Alpha Auto-Crop & True Vector SVG

If you have ever built an HTML5 <canvas> signature pad for a form, invoice app, or contract workflow, you probably ran into four surprisingly annoying bugs within the first hour: Jagged Polygonal Handwriting: Connecti

If you have ever built an HTML5 <canvas> signature pad for a form, invoice app, or contract workflow, you probably ran into four surprisingly annoying bugs within the first hour:

  1. Jagged Polygonal Handwriting: Connecting raw mousemove coordinates with ctx.lineTo() turns smooth mouse or trackpad cursive into harsh zigzag corners.
  2. Canvas Wiped on Window Resize: Assigning canvas.width = rect.width resets the entire bitmap immediately, erasing the user's signature whenever a mobile viewport rotates or a browser window resizes.
  3. Giant Empty Whitespace Around Exports: Calling canvas.toDataURL('image/png') directly exports a massive 900Γ—280 transparent rectangle around a tiny 180Γ—60 signatureβ€”making it impossible to align cleanly on PDF or invoice lines.
  4. Fake "SVG" Wrappers: Many web tools fake SVG export by wrapping a raster base64 PNG inside an <image> tag instead of generating genuine mathematical vector <path> curves.

You can solve all four cleanly in ~140 lines of zero-dependency JavaScript. Here is the exact client-side architecture powering our browser-local Online Signature Generator on EasyDailyTools.

1. Store Vector Stroke History Instead of Painting Destructively

The single most important architectural choice is treating the <canvas> as a pure view layer over an immutable array of stroke objects ({ points, color, width }):

let strokes = [];
let activeStroke = null;

function startDraw(e) {
  isDrawing = true;
  activeStroke = {
    points: [getPos(e)],
    color: currentColor,
    width: strokeWidth,
  };
  strokes.push(activeStroke);
  redrawAllStrokes();
}

Why this immediately eliminates three headaches at once:

  • Resize Resilience: When resizeCanvas() updates canvas.width, calling redrawAllStrokes() restores the exact signature instantaneously.
  • O(1) Step-by-Step Undo: strokes.pop(); redrawAllStrokes(); works with zero offscreen image snapshot memory overhead.
  • Lossless Vector SVG Export: Because raw pointer coordinates live in memory, exporting true <path> curves is just geometry serializationβ€”no bitmap tracing required.

2. Smooth Mouse & Touch Curves With Quadratic Bezier Midpoints

Raw pointer events sample unevenly (especially on 60Hz mice or throttled touchpads). Instead of drawing straight segments from p[i] to p[i+1], use each captured point p[i] as the quadratic Bezier control point and draw to the midpoint between p[i] and p[i+1]:

function redrawAllStrokes() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  for (const s of strokes) {
    if (!s.points.length) continue;
    ctx.beginPath();
    ctx.strokeStyle = s.color;
    ctx.lineWidth = s.width;
    ctx.lineCap = 'round';
    ctx.lineJoin = 'round';

    if (s.points.length === 1) {
      // Single tap / dot (e.g., dotting an "i")
      ctx.arc(s.points[0].x, s.points[0].y, s.width / 2, 0, Math.PI * 2);
      ctx.fillStyle = s.color;
      ctx.fill();
      continue;
    }

    ctx.moveTo(s.points[0].x, s.points[0].y);
    for (let i = 1; i < s.points.length - 1; i++) {
      const midX = (s.points[i].x + s.points[i + 1].x) / 2;
      const midY = (s.points[i].y + s.points[i + 1].y) / 2;
      ctx.quadraticCurveTo(s.points[i].x, s.points[i].y, midX, midY);
    }
    const last = s.points[s.points.length - 1];
    ctx.lineTo(last.x, last.y);
    ctx.stroke();
  }
}

Because consecutive quadratic segments share exact tangent slopes at every midpoint, strokes achieve CΒΉ continuity automaticallyβ€”zero sharp elbows, zero external curve libraries.

3. Serialize True Infinite-Scale Vector SVG <path> Data

Once strokes live in an array, generating a tight, standards-compliant SVG takes under 35 lines. Compute the bounding box across every point plus half the stroke width (hw = s.width / 2), shift coordinates into a padded local viewBox, and emit exact M / Q / L SVG commands matching the canvas renderer pixel-for-pixel:

function buildTrueVectorSvg(strokes, pad = 14) {
  let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
  for (const s of strokes) {
    const hw = s.width / 2;
    for (const p of s.points) {
      if (p.x - hw < minX) minX = p.x - hw;
      if (p.y - hw < minY) minY = p.y - hw;
      if (p.x + hw > maxX) maxX = p.x + hw;
      if (p.y + hw > maxY) maxY = p.y + hw;
    }
  }

  const vbX = Math.max(0, minX - pad);
  const vbY = Math.max(0, minY - pad);
  const vbW = Math.max(20, (maxX - minX) + pad * 2);
  const vbH = Math.max(20, (maxY - minY) + pad * 2);

  let paths = '';
  for (const s of strokes) {
    if (!s.points.length) continue;
    if (s.points.length === 1) {
      paths += `<circle cx="${(s.points[0].x - vbX).toFixed(2)}" cy="${(s.points[0].y - vbY).toFixed(2)}" r="${(s.width / 2).toFixed(2)}" fill="${s.color}"/>\n  `;
      continue;
    }
    let d = `M ${(s.points[0].x - vbX).toFixed(2)} ${(s.points[0].y - vbY).toFixed(2)}`;
    for (let i = 1; i < s.points.length - 1; i++) {
      const midX = (s.points[i].x + s.points[i + 1].x) / 2 - vbX;
      const midY = (s.points[i].y + s.points[i + 1].y) / 2 - vbY;
      d += ` Q ${(s.points[i].x - vbX).toFixed(2)} ${(s.points[i].y - vbY).toFixed(2)} ${midX.toFixed(2)} ${midY.toFixed(2)}`;
    }
    const last = s.points[s.points.length - 1];
    d += ` L ${(last.x - vbX).toFixed(2)} ${(last.y - vbY).toFixed(2)}`;
    paths += `<path d="${d}" fill="none" stroke="${s.color}" stroke-width="${s.width}" stroke-linecap="round" stroke-linejoin="round"/>\n  `;
  }

  return `<?xml version="1.0" encoding="UTF-8"?>\n<svg xmlns="http://www.w3.org/2000/svg" width="${Math.ceil(vbW)}" height="${Math.ceil(vbH)}" viewBox="0 0 ${vbW.toFixed(2)} ${vbH.toFixed(2)}">\n  ${paths.trim()}\n</svg>`;
}

The resulting .svg file is typically 1–4 KB, stays mathematically crisp at 10,000% print magnification, and drops cleanly into letterheads, vector layouts, and CAD title blocks.

4. Alpha-Channel Pixel Bounding-Box Auto-Crop + Clipboard PNG

For raster Transparent PNG, White JPG (for older exam/KYC portals that reject PNG transparency), and 1-Click Clipboard Copy, scanning the RGBA ImageData alpha channel (data[i + 3] > 0) strips empty canvas margins tightly around both drawn strokes and typed calligraphy fonts:

function cropAlphaCanvas(sourceCanvas, transparent = true, pad = 12) {
  const { width: w, height: h } = sourceCanvas;
  const data = sourceCanvas.getContext('2d').getImageData(0, 0, w, h).data;

  let minX = w, minY = h, maxX = 0, maxY = 0, found = false;
  for (let y = 0; y < h; y++) {
    for (let x = 0; x < w; x++) {
      if (data[(y * w + x) * 4 + 3] > 0) {
        if (x < minX) minX = x;
        if (x > maxX) maxX = x;
        if (y < minY) minY = y;
        if (y > maxY) maxY = y;
        found = true;
      }
    }
  }
  if (!found) return sourceCanvas;

  const cw = (maxX - minX + 1) + pad * 2;
  const ch = (maxY - minY + 1) + pad * 2;
  const out = document.createElement('canvas');
  out.width = cw;
  out.height = ch;
  const octx = out.getContext('2d');

  if (!transparent) {
    octx.fillStyle = '#ffffff';
    octx.fillRect(0, 0, cw, ch);
  }
  octx.drawImage(sourceCanvas, minX, minY, maxX - minX + 1, maxY - minY + 1, pad, pad, maxX - minX + 1, maxY - minY + 1);
  return out;
}

Pairing this cropped canvas with out.toBlob(blob => navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })])) lets users copy a tightly trimmed transparent signature straight into documents without saving a single temporary file to disk.

Bonus: Avoiding Clipped Edges on Typed Signatures

When offering a "Type Signature" tab using italic cursive fonts, never render onto a fixed 600px offscreen canvasβ€”long names and credentials will silently clip off both ends. Probe width first with measureText() and allocate dynamically:

const probe = document.createElement('canvas').getContext('2d');
probe.font = selectedFont;
const textWidth = probe.measureText(fullName).width;

const offCanvas = document.createElement('canvas');
offCanvas.width = Math.max(700, Math.ceil(textWidth + 120));
offCanvas.height = 180;

Try the Live Client-Side Engines & Related Browser-Local Tools

Everything above runs 100% client-side in local browser memory (zero uploads, zero telemetry, zero watermarks):

Have you tried velocity-based variable stroke width (calligraphy pressure simulation) on top of quadratic midpoint smoothing? Drop your favorite canvas drawing tricks in the comments!

πŸ“° Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.