UNPKG

17.5 kBPlain TextView Raw
1/**
2 * The main idea and some parts of the code (e.g. drawing variable width Bézier curve) are taken from:
3 * http://corner.squareup.com/2012/07/smoother-signatures.html
4 *
5 * Implementation of interpolation using cubic Bézier curves is taken from:
6 * http://www.benknowscode.com/2012/09/path-interpolation-using-cubic-bezier_9742.html
7 *
8 * Algorithm for approximated length of a Bézier curve is taken from:
9 * http://www.lemoda.net/maths/bezier-length/index.html
10 */
11
12import { Bezier } from './bezier';
13import { BasicPoint, Point } from './point';
14import { throttle } from './throttle';
15
16declare global {
17 interface CSSStyleDeclaration {
18 msTouchAction: string;
19 }
20}
21
22export interface Options {
23 dotSize?: number | (() => number);
24 minWidth?: number;
25 maxWidth?: number;
26 minDistance?: number;
27 backgroundColor?: string;
28 penColor?: string;
29 throttle?: number;
30 velocityFilterWeight?: number;
31 onBegin?: (event: MouseEvent | Touch) => void;
32 onEnd?: (event: MouseEvent | Touch) => void;
33}
34
35export interface PointGroup {
36 color: string;
37 points: BasicPoint[];
38}
39
40export default class SignaturePad {
41 // Public stuff
42 public dotSize: number | (() => number);
43 public minWidth: number;
44 public maxWidth: number;
45 public minDistance: number;
46 public backgroundColor: string;
47 public penColor: string;
48 public throttle: number;
49 public velocityFilterWeight: number;
50 public onBegin?: (event: MouseEvent | Touch) => void;
51 public onEnd?: (event: MouseEvent | Touch) => void;
52
53 // Private stuff
54 /* tslint:disable: variable-name */
55 private _ctx: CanvasRenderingContext2D;
56 private _mouseButtonDown: boolean;
57 private _isEmpty: boolean;
58 private _lastPoints: Point[]; // Stores up to 4 most recent points; used to generate a new curve
59 private _data: PointGroup[]; // Stores all points in groups (one group per line or dot)
60 private _lastVelocity: number;
61 private _lastWidth: number;
62 private _strokeMoveUpdate: (event: MouseEvent | Touch) => void;
63 /* tslint:enable: variable-name */
64
65 constructor(
66 private canvas: HTMLCanvasElement,
67 private options: Options = {},
68 ) {
69 this.velocityFilterWeight = options.velocityFilterWeight || 0.7;
70 this.minWidth = options.minWidth || 0.5;
71 this.maxWidth = options.maxWidth || 2.5;
72 this.throttle = ('throttle' in options ? options.throttle : 16) as number; // in milisecondss
73 this.minDistance = ('minDistance' in options
74 ? options.minDistance
75 : 5) as number; // in pixels
76 this.dotSize =
77 options.dotSize ||
78 function dotSize(this: SignaturePad): number {
79 return (this.minWidth + this.maxWidth) / 2;
80 };
81 this.penColor = options.penColor || 'black';
82 this.backgroundColor = options.backgroundColor || 'rgba(0,0,0,0)';
83 this.onBegin = options.onBegin;
84 this.onEnd = options.onEnd;
85
86 this._strokeMoveUpdate = this.throttle
87 ? throttle(SignaturePad.prototype._strokeUpdate, this.throttle)
88 : SignaturePad.prototype._strokeUpdate;
89 this._ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
90
91 this.clear();
92
93 // Enable mouse and touch event handlers
94 this.on();
95 }
96
97 public clear(): void {
98 const { _ctx: ctx, canvas } = this;
99
100 // Clear canvas using background color
101 ctx.fillStyle = this.backgroundColor;
102 ctx.clearRect(0, 0, canvas.width, canvas.height);
103 ctx.fillRect(0, 0, canvas.width, canvas.height);
104
105 this._data = [];
106 this._reset();
107 this._isEmpty = true;
108 }
109
110 public fromDataURL(
111 dataUrl: string,
112 options: { ratio?: number; width?: number; height?: number } = {},
113 callback?: (error?: string | Event) => void,
114 ): void {
115 const image = new Image();
116 const ratio = options.ratio || window.devicePixelRatio || 1;
117 const width = options.width || this.canvas.width / ratio;
118 const height = options.height || this.canvas.height / ratio;
119
120 this._reset();
121
122 image.onload = (): void => {
123 this._ctx.drawImage(image, 0, 0, width, height);
124 if (callback) {
125 callback();
126 }
127 };
128 image.onerror = (error): void => {
129 if (callback) {
130 callback(error);
131 }
132 };
133 image.src = dataUrl;
134
135 this._isEmpty = false;
136 }
137
138 public toDataURL(type = 'image/png', encoderOptions?: number): string {
139 switch (type) {
140 case 'image/svg+xml':
141 return this._toSVG();
142 default:
143 return this.canvas.toDataURL(type, encoderOptions);
144 }
145 }
146
147 public on(): void {
148 // Disable panning/zooming when touching canvas element
149 this.canvas.style.touchAction = 'none';
150 this.canvas.style.msTouchAction = 'none';
151
152 if (window.PointerEvent) {
153 this._handlePointerEvents();
154 } else {
155 this._handleMouseEvents();
156
157 if ('ontouchstart' in window) {
158 this._handleTouchEvents();
159 }
160 }
161 }
162
163 public off(): void {
164 // Enable panning/zooming when touching canvas element
165 this.canvas.style.touchAction = 'auto';
166 this.canvas.style.msTouchAction = 'auto';
167
168 this.canvas.removeEventListener('pointerdown', this._handleMouseDown);
169 this.canvas.removeEventListener('pointermove', this._handleMouseMove);
170 document.removeEventListener('pointerup', this._handleMouseUp);
171
172 this.canvas.removeEventListener('mousedown', this._handleMouseDown);
173 this.canvas.removeEventListener('mousemove', this._handleMouseMove);
174 document.removeEventListener('mouseup', this._handleMouseUp);
175
176 this.canvas.removeEventListener('touchstart', this._handleTouchStart);
177 this.canvas.removeEventListener('touchmove', this._handleTouchMove);
178 this.canvas.removeEventListener('touchend', this._handleTouchEnd);
179 }
180
181 public isEmpty(): boolean {
182 return this._isEmpty;
183 }
184
185 public fromData(pointGroups: PointGroup[]): void {
186 this.clear();
187
188 this._fromData(
189 pointGroups,
190 ({ color, curve }) => this._drawCurve({ color, curve }),
191 ({ color, point }) => this._drawDot({ color, point }),
192 );
193
194 this._data = pointGroups;
195 }
196
197 public toData(): PointGroup[] {
198 return this._data;
199 }
200
201 // Event handlers
202 private _handleMouseDown = (event: MouseEvent): void => {
203 if (event.which === 1) {
204 this._mouseButtonDown = true;
205 this._strokeBegin(event);
206 }
207 };
208
209 private _handleMouseMove = (event: MouseEvent): void => {
210 if (this._mouseButtonDown) {
211 this._strokeMoveUpdate(event);
212 }
213 };
214
215 private _handleMouseUp = (event: MouseEvent): void => {
216 if (event.which === 1 && this._mouseButtonDown) {
217 this._mouseButtonDown = false;
218 this._strokeEnd(event);
219 }
220 };
221
222 private _handleTouchStart = (event: TouchEvent): void => {
223 // Prevent scrolling.
224 event.preventDefault();
225
226 if (event.targetTouches.length === 1) {
227 const touch = event.changedTouches[0];
228 this._strokeBegin(touch);
229 }
230 };
231
232 private _handleTouchMove = (event: TouchEvent): void => {
233 // Prevent scrolling.
234 event.preventDefault();
235
236 const touch = event.targetTouches[0];
237 this._strokeMoveUpdate(touch);
238 };
239
240 private _handleTouchEnd = (event: TouchEvent): void => {
241 const wasCanvasTouched = event.target === this.canvas;
242 if (wasCanvasTouched) {
243 event.preventDefault();
244
245 const touch = event.changedTouches[0];
246 this._strokeEnd(touch);
247 }
248 };
249
250 // Private methods
251 private _strokeBegin(event: MouseEvent | Touch): void {
252 const newPointGroup = {
253 color: this.penColor,
254 points: [],
255 };
256
257 if (typeof this.onBegin === 'function') {
258 this.onBegin(event);
259 }
260
261 this._data.push(newPointGroup);
262 this._reset();
263 this._strokeUpdate(event);
264 }
265
266 private _strokeUpdate(event: MouseEvent | Touch): void {
267 if (this._data.length === 0) {
268 // This can happen if clear() was called while a signature is still in progress,
269 // or if there is a race condition between start/update events.
270 this._strokeBegin(event);
271 return;
272 }
273
274 const x = event.clientX;
275 const y = event.clientY;
276
277 const point = this._createPoint(x, y);
278 const lastPointGroup = this._data[this._data.length - 1];
279 const lastPoints = lastPointGroup.points;
280 const lastPoint =
281 lastPoints.length > 0 && lastPoints[lastPoints.length - 1];
282 const isLastPointTooClose = lastPoint
283 ? point.distanceTo(lastPoint) <= this.minDistance
284 : false;
285 const color = lastPointGroup.color;
286
287 // Skip this point if it's too close to the previous one
288 if (!lastPoint || !(lastPoint && isLastPointTooClose)) {
289 const curve = this._addPoint(point);
290
291 if (!lastPoint) {
292 this._drawDot({ color, point });
293 } else if (curve) {
294 this._drawCurve({ color, curve });
295 }
296
297 lastPoints.push({
298 time: point.time,
299 x: point.x,
300 y: point.y,
301 });
302 }
303 }
304
305 private _strokeEnd(event: MouseEvent | Touch): void {
306 this._strokeUpdate(event);
307
308 if (typeof this.onEnd === 'function') {
309 this.onEnd(event);
310 }
311 }
312
313 private _handlePointerEvents(): void {
314 this._mouseButtonDown = false;
315
316 this.canvas.addEventListener('pointerdown', this._handleMouseDown);
317 this.canvas.addEventListener('pointermove', this._handleMouseMove);
318 document.addEventListener('pointerup', this._handleMouseUp);
319 }
320
321 private _handleMouseEvents(): void {
322 this._mouseButtonDown = false;
323
324 this.canvas.addEventListener('mousedown', this._handleMouseDown);
325 this.canvas.addEventListener('mousemove', this._handleMouseMove);
326 document.addEventListener('mouseup', this._handleMouseUp);
327 }
328
329 private _handleTouchEvents(): void {
330 this.canvas.addEventListener('touchstart', this._handleTouchStart);
331 this.canvas.addEventListener('touchmove', this._handleTouchMove);
332 this.canvas.addEventListener('touchend', this._handleTouchEnd);
333 }
334
335 // Called when a new line is started
336 private _reset(): void {
337 this._lastPoints = [];
338 this._lastVelocity = 0;
339 this._lastWidth = (this.minWidth + this.maxWidth) / 2;
340 this._ctx.fillStyle = this.penColor;
341 }
342
343 private _createPoint(x: number, y: number): Point {
344 const rect = this.canvas.getBoundingClientRect();
345
346 return new Point(x - rect.left, y - rect.top, new Date().getTime());
347 }
348
349 // Add point to _lastPoints array and generate a new curve if there are enough points (i.e. 3)
350 private _addPoint(point: Point): Bezier | null {
351 const { _lastPoints } = this;
352
353 _lastPoints.push(point);
354
355 if (_lastPoints.length > 2) {
356 // To reduce the initial lag make it work with 3 points
357 // by copying the first point to the beginning.
358 if (_lastPoints.length === 3) {
359 _lastPoints.unshift(_lastPoints[0]);
360 }
361
362 // _points array will always have 4 points here.
363 const widths = this._calculateCurveWidths(_lastPoints[1], _lastPoints[2]);
364 const curve = Bezier.fromPoints(_lastPoints, widths);
365
366 // Remove the first element from the list, so that there are no more than 4 points at any time.
367 _lastPoints.shift();
368
369 return curve;
370 }
371
372 return null;
373 }
374
375 private _calculateCurveWidths(
376 startPoint: Point,
377 endPoint: Point,
378 ): { start: number; end: number } {
379 const velocity =
380 this.velocityFilterWeight * endPoint.velocityFrom(startPoint) +
381 (1 - this.velocityFilterWeight) * this._lastVelocity;
382
383 const newWidth = this._strokeWidth(velocity);
384
385 const widths = {
386 end: newWidth,
387 start: this._lastWidth,
388 };
389
390 this._lastVelocity = velocity;
391 this._lastWidth = newWidth;
392
393 return widths;
394 }
395
396 private _strokeWidth(velocity: number): number {
397 return Math.max(this.maxWidth / (velocity + 1), this.minWidth);
398 }
399
400 private _drawCurveSegment(x: number, y: number, width: number): void {
401 const ctx = this._ctx;
402
403 ctx.moveTo(x, y);
404 ctx.arc(x, y, width, 0, 2 * Math.PI, false);
405 this._isEmpty = false;
406 }
407
408 private _drawCurve({ color, curve }: { color: string; curve: Bezier }): void {
409 const ctx = this._ctx;
410 const widthDelta = curve.endWidth - curve.startWidth;
411 // '2' is just an arbitrary number here. If only lenght is used, then
412 // there are gaps between curve segments :/
413 const drawSteps = Math.floor(curve.length()) * 2;
414
415 ctx.beginPath();
416 ctx.fillStyle = color;
417
418 for (let i = 0; i < drawSteps; i += 1) {
419 // Calculate the Bezier (x, y) coordinate for this step.
420 const t = i / drawSteps;
421 const tt = t * t;
422 const ttt = tt * t;
423 const u = 1 - t;
424 const uu = u * u;
425 const uuu = uu * u;
426
427 let x = uuu * curve.startPoint.x;
428 x += 3 * uu * t * curve.control1.x;
429 x += 3 * u * tt * curve.control2.x;
430 x += ttt * curve.endPoint.x;
431
432 let y = uuu * curve.startPoint.y;
433 y += 3 * uu * t * curve.control1.y;
434 y += 3 * u * tt * curve.control2.y;
435 y += ttt * curve.endPoint.y;
436
437 const width = Math.min(
438 curve.startWidth + ttt * widthDelta,
439 this.maxWidth,
440 );
441 this._drawCurveSegment(x, y, width);
442 }
443
444 ctx.closePath();
445 ctx.fill();
446 }
447
448 private _drawDot({
449 color,
450 point,
451 }: {
452 color: string;
453 point: BasicPoint;
454 }): void {
455 const ctx = this._ctx;
456 const width =
457 typeof this.dotSize === 'function' ? this.dotSize() : this.dotSize;
458
459 ctx.beginPath();
460 this._drawCurveSegment(point.x, point.y, width);
461 ctx.closePath();
462 ctx.fillStyle = color;
463 ctx.fill();
464 }
465
466 private _fromData(
467 pointGroups: PointGroup[],
468 drawCurve: SignaturePad['_drawCurve'],
469 drawDot: SignaturePad['_drawDot'],
470 ): void {
471 for (const group of pointGroups) {
472 const { color, points } = group;
473
474 if (points.length > 1) {
475 for (let j = 0; j < points.length; j += 1) {
476 const basicPoint = points[j];
477 const point = new Point(basicPoint.x, basicPoint.y, basicPoint.time);
478
479 // All points in the group have the same color, so it's enough to set
480 // penColor just at the beginning.
481 this.penColor = color;
482
483 if (j === 0) {
484 this._reset();
485 }
486
487 const curve = this._addPoint(point);
488
489 if (curve) {
490 drawCurve({ color, curve });
491 }
492 }
493 } else {
494 this._reset();
495
496 drawDot({
497 color,
498 point: points[0],
499 });
500 }
501 }
502 }
503
504 private _toSVG(): string {
505 const pointGroups = this._data;
506 const ratio = Math.max(window.devicePixelRatio || 1, 1);
507 const minX = 0;
508 const minY = 0;
509 const maxX = this.canvas.width / ratio;
510 const maxY = this.canvas.height / ratio;
511 const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
512
513 svg.setAttribute('width', this.canvas.width.toString());
514 svg.setAttribute('height', this.canvas.height.toString());
515
516 this._fromData(
517 pointGroups,
518
519 ({ color, curve }: { color: string; curve: Bezier }) => {
520 const path = document.createElement('path');
521
522 // Need to check curve for NaN values, these pop up when drawing
523 // lines on the canvas that are not continuous. E.g. Sharp corners
524 // or stopping mid-stroke and than continuing without lifting mouse.
525 /* eslint-disable no-restricted-globals */
526 if (
527 !isNaN(curve.control1.x) &&
528 !isNaN(curve.control1.y) &&
529 !isNaN(curve.control2.x) &&
530 !isNaN(curve.control2.y)
531 ) {
532 const attr =
533 `M ${curve.startPoint.x.toFixed(3)},${curve.startPoint.y.toFixed(
534 3,
535 )} ` +
536 `C ${curve.control1.x.toFixed(3)},${curve.control1.y.toFixed(3)} ` +
537 `${curve.control2.x.toFixed(3)},${curve.control2.y.toFixed(3)} ` +
538 `${curve.endPoint.x.toFixed(3)},${curve.endPoint.y.toFixed(3)}`;
539 path.setAttribute('d', attr);
540 path.setAttribute('stroke-width', (curve.endWidth * 2.25).toFixed(3));
541 path.setAttribute('stroke', color);
542 path.setAttribute('fill', 'none');
543 path.setAttribute('stroke-linecap', 'round');
544
545 svg.appendChild(path);
546 }
547 /* eslint-enable no-restricted-globals */
548 },
549
550 ({ color, point }: { color: string; point: BasicPoint }) => {
551 const circle = document.createElement('circle');
552 const dotSize =
553 typeof this.dotSize === 'function' ? this.dotSize() : this.dotSize;
554 circle.setAttribute('r', dotSize.toString());
555 circle.setAttribute('cx', point.x.toString());
556 circle.setAttribute('cy', point.y.toString());
557 circle.setAttribute('fill', color);
558
559 svg.appendChild(circle);
560 },
561 );
562
563 const prefix = 'data:image/svg+xml;base64,';
564 const header =
565 '<svg' +
566 ' xmlns="http://www.w3.org/2000/svg"' +
567 ' xmlns:xlink="http://www.w3.org/1999/xlink"' +
568 ` viewBox="${minX} ${minY} ${maxX} ${maxY}"` +
569 ` width="${maxX}"` +
570 ` height="${maxY}"` +
571 '>';
572 let body = svg.innerHTML;
573
574 // IE hack for missing innerHTML property on SVGElement
575 if (body === undefined) {
576 const dummy = document.createElement('dummy');
577 const nodes = svg.childNodes;
578 dummy.innerHTML = '';
579
580 // tslint:disable-next-line: prefer-for-of
581 for (let i = 0; i < nodes.length; i += 1) {
582 dummy.appendChild(nodes[i].cloneNode(true));
583 }
584
585 body = dummy.innerHTML;
586 }
587
588 const footer = '</svg>';
589 const data = header + body + footer;
590
591 return prefix + btoa(data);
592 }
593}