Skip to content

Beautiful Open-Source Form Builder

Normalize saved signatures for consistent rendering (#1236)

Julien Nahum4bc1088cd9eb
diff --git a/client/components/forms/heavy/SignatureInput.vue b/client/components/forms/heavy/SignatureInput.vue
index 7674bed68..6d174dcb0 100644
--- a/client/components/forms/heavy/SignatureInput.vue
+++ b/client/components/forms/heavy/SignatureInput.vue
@@ -77,6 +77,7 @@
import { VueSignaturePad } from 'vue-signature-pad'
import { inputProps, useFormInput } from '../useFormInput.js'
import { storeFile } from '~/lib/file-uploads.js'
+import { getNormalizedSignatureData } from '~/lib/forms/normalize-signature.js'
import { signatureInputTheme } from '~/lib/forms/themes/signature-input.theme.js'
export default {
@@ -139,9 +140,7 @@ export default {
if (this.disabled) {
this.$refs.signaturePad.clearSignature()
} else {
- /* eslint-disable-next-line */
- const { isEmpty, data } = this.$refs.signaturePad?.saveSignature()
- this.form[this.name] = !isEmpty && data ? data : null
+ this.form[this.name] = getNormalizedSignatureData(this.$refs.signaturePad)
}
},
openFileUpload() {
diff --git a/client/lib/forms/normalize-signature.js b/client/lib/forms/normalize-signature.js
new file mode 100644
index 000000000..cf8626ba5
--- /dev/null
+++ b/client/lib/forms/normalize-signature.js
@@ -0,0 +1,79 @@
+const getSignatureBounds = (sourceCanvas) => {
+ const sourceContext = sourceCanvas.getContext('2d')
+ if (!sourceContext) {
+ throw new Error('Unable to read signature canvas')
+ }
+
+ const { width, height } = sourceCanvas
+ const pixels = sourceContext.getImageData(0, 0, width, height).data
+ let minX = width
+ let minY = height
+ let maxX = -1
+ let maxY = -1
+
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ if (pixels[(y * width + x) * 4 + 3] === 0) continue
+
+ minX = Math.min(minX, x)
+ minY = Math.min(minY, y)
+ maxX = Math.max(maxX, x)
+ maxY = Math.max(maxY, y)
+ }
+ }
+
+ if (maxX < minX || maxY < minY) {
+ return { x: 0, y: 0, width, height }
+ }
+
+ const padding = Math.max(8, Math.round(Math.min(width, height) * 0.04))
+ const x = Math.max(0, minX - padding)
+ const y = Math.max(0, minY - padding)
+ const right = Math.min(width, maxX + padding + 1)
+ const bottom = Math.min(height, maxY + padding + 1)
+
+ return { x, y, width: right - x, height: bottom - y }
+}
+
+export function normalizeSignatureCanvas(sourceCanvas, createCanvas = () => document.createElement('canvas')) {
+ const bounds = getSignatureBounds(sourceCanvas)
+ const normalizedCanvas = createCanvas()
+ normalizedCanvas.width = bounds.width
+ normalizedCanvas.height = bounds.height
+
+ const context = normalizedCanvas.getContext('2d')
+ if (!context) {
+ throw new Error('Unable to normalize signature canvas')
+ }
+
+ context.drawImage(
+ sourceCanvas,
+ bounds.x,
+ bounds.y,
+ bounds.width,
+ bounds.height,
+ 0,
+ 0,
+ bounds.width,
+ bounds.height,
+ )
+
+ context.globalCompositeOperation = 'source-in'
+ context.fillStyle = '#000000'
+ context.fillRect(0, 0, normalizedCanvas.width, normalizedCanvas.height)
+
+ context.globalCompositeOperation = 'destination-over'
+ context.fillStyle = '#ffffff'
+ context.fillRect(0, 0, normalizedCanvas.width, normalizedCanvas.height)
+
+ return normalizedCanvas.toDataURL('image/png')
+}
+
+export function getNormalizedSignatureData(signaturePad, normalizeCanvas = normalizeSignatureCanvas) {
+ if (signaturePad.isEmpty()) return null
+
+ const signatureCanvas = signaturePad.signaturePad?.canvas
+ if (signatureCanvas) return normalizeCanvas(signatureCanvas)
+
+ return signaturePad.saveSignature().data || null
+}
diff --git a/client/test/unit/normalize-signature.test.ts b/client/test/unit/normalize-signature.test.ts
new file mode 100644
index 000000000..351442e76
--- /dev/null
+++ b/client/test/unit/normalize-signature.test.ts
@@ -0,0 +1,87 @@
+import { describe, expect, it, vi } from 'vitest'
+import {
+ getNormalizedSignatureData,
+ normalizeSignatureCanvas,
+} from '../../lib/forms/normalize-signature.js'
+
+describe('normalizeSignatureCanvas', () => {
+ it('exports signature pixels as black ink on an opaque white background', () => {
+ const operations: string[][] = []
+ const normalizedContext = {
+ drawImage: vi.fn((...args) => operations.push(['drawImage', ...args.slice(1).map(String)])),
+ fillRect: vi.fn(() => operations.push(['fillRect'])),
+ }
+
+ Object.defineProperties(normalizedContext, {
+ globalCompositeOperation: {
+ set(value: string) {
+ operations.push(['globalCompositeOperation', value])
+ },
+ },
+ fillStyle: {
+ set(value: string) {
+ operations.push(['fillStyle', value])
+ },
+ },
+ })
+
+ const normalizedCanvas = {
+ width: 0,
+ height: 0,
+ getContext: vi.fn(() => normalizedContext),
+ toDataURL: vi.fn(() => 'data:image/png;base64,normalized'),
+ }
+ const sourceWidth = 100
+ const sourceHeight = 50
+ const pixels = new Uint8ClampedArray(sourceWidth * sourceHeight * 4)
+ for (let y = 10; y < 30; y++) {
+ for (let x = 20; x < 60; x++) {
+ pixels[(y * sourceWidth + x) * 4 + 3] = 255
+ }
+ }
+ const sourceCanvas = {
+ width: sourceWidth,
+ height: sourceHeight,
+ getContext: vi.fn(() => ({
+ getImageData: vi.fn(() => ({ data: pixels })),
+ })),
+ } as unknown as HTMLCanvasElement
+ const result = normalizeSignatureCanvas(
+ sourceCanvas,
+ () => normalizedCanvas as unknown as HTMLCanvasElement,
+ )
+
+ expect(normalizedCanvas.width).toBe(56)
+ expect(normalizedCanvas.height).toBe(36)
+ expect(operations).toEqual([
+ ['drawImage', '12', '2', '56', '36', '0', '0', '56', '36'],
+ ['globalCompositeOperation', 'source-in'],
+ ['fillStyle', '#000000'],
+ ['fillRect'],
+ ['globalCompositeOperation', 'destination-over'],
+ ['fillStyle', '#ffffff'],
+ ['fillRect'],
+ ])
+ expect(normalizedCanvas.toDataURL).toHaveBeenCalledWith('image/png')
+ expect(result).toBe('data:image/png;base64,normalized')
+ })
+
+ it('normalizes the canvas without encoding the original signature first', () => {
+ const canvas = {} as HTMLCanvasElement
+ const normalizeCanvas = vi.fn(() => 'data:image/png;base64,normalized')
+ const saveSignature = vi.fn(() => ({
+ isEmpty: false,
+ data: 'data:image/png;base64,original',
+ }))
+
+ const result = getNormalizedSignatureData({
+ isEmpty: vi.fn(() => false),
+ saveSignature,
+ signaturePad: { canvas },
+ }, normalizeCanvas)
+
+ expect(normalizeCanvas).toHaveBeenCalledWith(canvas)
+ expect(saveSignature).not.toHaveBeenCalled()
+ expect(result).toBe('data:image/png;base64,normalized')
+ })
+})