2 * Signature Pad v3.0.0-beta.3 | https://github.com/szimek/signature_pad
3 * (c) 2018 Szymon Nowak | Released under the MIT license
6 (function (global, factory) {
7 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
8 typeof define === 'function' && define.amd ? define(factory) :
9 (global.SignaturePad = factory());
10 }(this, (function () { 'use strict';
12 var Point = (function () {
13 function Point(x, y, time) {
16 this.time = time || Date.now();
18 Point.prototype.distanceTo = function (start) {
19 return Math.sqrt(Math.pow(this.x - start.x, 2) + Math.pow(this.y - start.y, 2));
21 Point.prototype.equals = function (other) {
22 return this.x === other.x && this.y === other.y && this.time === other.time;
24 Point.prototype.velocityFrom = function (start) {
25 return (this.time !== start.time) ? this.distanceTo(start) / (this.time - start.time) : 0;
30 var Bezier = (function () {
31 function Bezier(startPoint, control2, control1, endPoint, startWidth, endWidth) {
32 this.startPoint = startPoint;
33 this.control2 = control2;
34 this.control1 = control1;
35 this.endPoint = endPoint;
36 this.startWidth = startWidth;
37 this.endWidth = endWidth;
39 Bezier.fromPoints = function (points, widths) {
40 var c2 = this.calculateControlPoints(points[0], points[1], points[2]).c2;
41 var c3 = this.calculateControlPoints(points[1], points[2], points[3]).c1;
42 return new Bezier(points[1], c2, c3, points[2], widths.start, widths.end);
44 Bezier.calculateControlPoints = function (s1, s2, s3) {
45 var dx1 = s1.x - s2.x;
46 var dy1 = s1.y - s2.y;
47 var dx2 = s2.x - s3.x;
48 var dy2 = s2.y - s3.y;
49 var m1 = { x: (s1.x + s2.x) / 2.0, y: (s1.y + s2.y) / 2.0 };
50 var m2 = { x: (s2.x + s3.x) / 2.0, y: (s2.y + s3.y) / 2.0 };
51 var l1 = Math.sqrt((dx1 * dx1) + (dy1 * dy1));
52 var l2 = Math.sqrt((dx2 * dx2) + (dy2 * dy2));
53 var dxm = (m1.x - m2.x);
54 var dym = (m1.y - m2.y);
55 var k = l2 / (l1 + l2);
56 var cm = { x: m2.x + (dxm * k), y: m2.y + (dym * k) };
60 c1: new Point(m1.x + tx, m1.y + ty),
61 c2: new Point(m2.x + tx, m2.y + ty)
64 Bezier.prototype.length = function () {
69 for (var i = 0; i <= steps; i += 1) {
71 var cx = this.point(t, this.startPoint.x, this.control1.x, this.control2.x, this.endPoint.x);
72 var cy = this.point(t, this.startPoint.y, this.control1.y, this.control2.y, this.endPoint.y);
76 length += Math.sqrt((xdiff * xdiff) + (ydiff * ydiff));
83 Bezier.prototype.point = function (t, start, c1, c2, end) {
84 return (start * (1.0 - t) * (1.0 - t) * (1.0 - t))
85 + (3.0 * c1 * (1.0 - t) * (1.0 - t) * t)
86 + (3.0 * c2 * (1.0 - t) * t * t)
92 function throttle(fn, wait) {
93 if (wait === void 0) { wait = 250; }
99 var later = function () {
100 previous = Date.now();
102 result = fn.apply(storedContext, storedArgs);
104 storedContext = null;
110 for (var _i = 0; _i < arguments.length; _i++) {
111 args[_i] = arguments[_i];
113 var now = Date.now();
114 var remaining = wait - (now - previous);
115 storedContext = this;
117 if (remaining <= 0 || remaining > wait) {
119 clearTimeout(timeout);
123 result = fn.apply(storedContext, storedArgs);
125 storedContext = null;
130 timeout = window.setTimeout(later, remaining);
136 var SignaturePad = (function () {
137 function SignaturePad(canvas, options) {
138 if (options === void 0) { options = {}; }
140 this.canvas = canvas;
141 this.options = options;
142 this._handleMouseDown = function (event) {
143 if (event.which === 1) {
144 _this._mouseButtonDown = true;
145 _this._strokeBegin(event);
148 this._handleMouseMove = function (event) {
149 if (_this._mouseButtonDown) {
150 _this._strokeMoveUpdate(event);
153 this._handleMouseUp = function (event) {
154 if (event.which === 1 && _this._mouseButtonDown) {
155 _this._mouseButtonDown = false;
156 _this._strokeEnd(event);
159 this._handleTouchStart = function (event) {
160 event.preventDefault();
161 if (event.targetTouches.length === 1) {
162 var touch = event.changedTouches[0];
163 _this._strokeBegin(touch);
166 this._handleTouchMove = function (event) {
167 event.preventDefault();
168 var touch = event.targetTouches[0];
169 _this._strokeMoveUpdate(touch);
171 this._handleTouchEnd = function (event) {
172 var wasCanvasTouched = event.target === _this.canvas;
173 if (wasCanvasTouched) {
174 event.preventDefault();
175 var touch = event.changedTouches[0];
176 _this._strokeEnd(touch);
179 this.velocityFilterWeight = options.velocityFilterWeight || 0.7;
180 this.minWidth = options.minWidth || 0.5;
181 this.maxWidth = options.maxWidth || 2.5;
182 this.throttle = ('throttle' in options ? options.throttle : 16);
183 this.minDistance = ('minDistance' in options ? options.minDistance : 5);
185 this._strokeMoveUpdate = throttle(SignaturePad.prototype._strokeUpdate, this.throttle);
188 this._strokeMoveUpdate = SignaturePad.prototype._strokeUpdate;
190 this.dotSize = options.dotSize || function () {
191 return (this.minWidth + this.maxWidth) / 2;
193 this.penColor = options.penColor || 'black';
194 this.backgroundColor = options.backgroundColor || 'rgba(0,0,0,0)';
195 this.onBegin = options.onBegin;
196 this.onEnd = options.onEnd;
197 this._ctx = canvas.getContext('2d');
201 SignaturePad.prototype.clear = function () {
203 var canvas = this.canvas;
204 ctx.fillStyle = this.backgroundColor;
205 ctx.clearRect(0, 0, canvas.width, canvas.height);
206 ctx.fillRect(0, 0, canvas.width, canvas.height);
209 this._isEmpty = true;
211 SignaturePad.prototype.fromDataURL = function (dataUrl, options, callback) {
213 if (options === void 0) { options = {}; }
214 var image = new Image();
215 var ratio = options.ratio || window.devicePixelRatio || 1;
216 var width = options.width || (this.canvas.width / ratio);
217 var height = options.height || (this.canvas.height / ratio);
219 image.onload = function () {
220 _this._ctx.drawImage(image, 0, 0, width, height);
225 image.onerror = function (error) {
231 this._isEmpty = false;
233 SignaturePad.prototype.toDataURL = function (type, encoderOptions) {
234 if (type === void 0) { type = 'image/png'; }
236 case 'image/svg+xml':
237 return this._toSVG();
239 return this.canvas.toDataURL(type, encoderOptions);
242 SignaturePad.prototype.on = function () {
243 this.canvas.style.touchAction = 'none';
244 this.canvas.style.msTouchAction = 'none';
245 if (window.PointerEvent) {
246 this._handlePointerEvents();
249 this._handleMouseEvents();
250 if ('ontouchstart' in window) {
251 this._handleTouchEvents();
255 SignaturePad.prototype.off = function () {
256 this.canvas.style.touchAction = 'auto';
257 this.canvas.style.msTouchAction = 'auto';
258 this.canvas.removeEventListener('pointerdown', this._handleMouseDown);
259 this.canvas.removeEventListener('pointermove', this._handleMouseMove);
260 document.removeEventListener('pointerup', this._handleMouseUp);
261 this.canvas.removeEventListener('mousedown', this._handleMouseDown);
262 this.canvas.removeEventListener('mousemove', this._handleMouseMove);
263 document.removeEventListener('mouseup', this._handleMouseUp);
264 this.canvas.removeEventListener('touchstart', this._handleTouchStart);
265 this.canvas.removeEventListener('touchmove', this._handleTouchMove);
266 this.canvas.removeEventListener('touchend', this._handleTouchEnd);
268 SignaturePad.prototype.isEmpty = function () {
269 return this._isEmpty;
271 SignaturePad.prototype.fromData = function (pointGroups) {
274 this._fromData(pointGroups, function (_a) {
275 var color = _a.color, curve = _a.curve;
276 return _this._drawCurve({ color: color, curve: curve });
278 var color = _a.color, point = _a.point;
279 return _this._drawDot({ color: color, point: point });
281 this._data = pointGroups;
283 SignaturePad.prototype.toData = function () {
286 SignaturePad.prototype._strokeBegin = function (event) {
287 var newPointGroup = {
288 color: this.penColor,
291 this._data.push(newPointGroup);
293 this._strokeUpdate(event);
294 if (typeof this.onBegin === 'function') {
298 SignaturePad.prototype._strokeUpdate = function (event) {
299 var x = event.clientX;
300 var y = event.clientY;
301 var point = this._createPoint(x, y);
302 var lastPointGroup = this._data[this._data.length - 1];
303 var lastPoints = lastPointGroup.points;
304 var lastPoint = lastPoints.length > 0 && lastPoints[lastPoints.length - 1];
305 var isLastPointTooClose = lastPoint ? point.distanceTo(lastPoint) <= this.minDistance : false;
306 var color = lastPointGroup.color;
307 if (!lastPoint || !(lastPoint && isLastPointTooClose)) {
308 var curve = this._addPoint(point);
310 this._drawDot({ color: color, point: point });
313 this._drawCurve({ color: color, curve: curve });
322 SignaturePad.prototype._strokeEnd = function (event) {
323 this._strokeUpdate(event);
324 if (typeof this.onEnd === 'function') {
328 SignaturePad.prototype._handlePointerEvents = function () {
329 this._mouseButtonDown = false;
330 this.canvas.addEventListener('pointerdown', this._handleMouseDown);
331 this.canvas.addEventListener('pointermove', this._handleMouseMove);
332 document.addEventListener('pointerup', this._handleMouseUp);
334 SignaturePad.prototype._handleMouseEvents = function () {
335 this._mouseButtonDown = false;
336 this.canvas.addEventListener('mousedown', this._handleMouseDown);
337 this.canvas.addEventListener('mousemove', this._handleMouseMove);
338 document.addEventListener('mouseup', this._handleMouseUp);
340 SignaturePad.prototype._handleTouchEvents = function () {
341 this.canvas.addEventListener('touchstart', this._handleTouchStart);
342 this.canvas.addEventListener('touchmove', this._handleTouchMove);
343 this.canvas.addEventListener('touchend', this._handleTouchEnd);
345 SignaturePad.prototype._reset = function () {
346 this._lastPoints = [];
347 this._lastVelocity = 0;
348 this._lastWidth = (this.minWidth + this.maxWidth) / 2;
349 this._ctx.fillStyle = this.penColor;
351 SignaturePad.prototype._createPoint = function (x, y) {
352 var rect = this.canvas.getBoundingClientRect();
353 return new Point(x - rect.left, y - rect.top, new Date().getTime());
355 SignaturePad.prototype._addPoint = function (point) {
356 var _lastPoints = this._lastPoints;
357 _lastPoints.push(point);
358 if (_lastPoints.length > 2) {
359 if (_lastPoints.length === 3) {
360 _lastPoints.unshift(_lastPoints[0]);
362 var widths = this._calculateCurveWidths(_lastPoints[1], _lastPoints[2]);
363 var curve = Bezier.fromPoints(_lastPoints, widths);
369 SignaturePad.prototype._calculateCurveWidths = function (startPoint, endPoint) {
370 var velocity = (this.velocityFilterWeight * endPoint.velocityFrom(startPoint))
371 + ((1 - this.velocityFilterWeight) * this._lastVelocity);
372 var newWidth = this._strokeWidth(velocity);
375 start: this._lastWidth
377 this._lastVelocity = velocity;
378 this._lastWidth = newWidth;
381 SignaturePad.prototype._strokeWidth = function (velocity) {
382 return Math.max(this.maxWidth / (velocity + 1), this.minWidth);
384 SignaturePad.prototype._drawCurveSegment = function (x, y, width) {
387 ctx.arc(x, y, width, 0, 2 * Math.PI, false);
388 this._isEmpty = false;
390 SignaturePad.prototype._drawCurve = function (_a) {
391 var color = _a.color, curve = _a.curve;
393 var widthDelta = curve.endWidth - curve.startWidth;
394 var drawSteps = Math.floor(curve.length()) * 2;
396 ctx.fillStyle = color;
397 for (var i = 0; i < drawSteps; i += 1) {
398 var t = i / drawSteps;
404 var x = uuu * curve.startPoint.x;
405 x += 3 * uu * t * curve.control1.x;
406 x += 3 * u * tt * curve.control2.x;
407 x += ttt * curve.endPoint.x;
408 var y = uuu * curve.startPoint.y;
409 y += 3 * uu * t * curve.control1.y;
410 y += 3 * u * tt * curve.control2.y;
411 y += ttt * curve.endPoint.y;
412 var width = curve.startWidth + (ttt * widthDelta);
413 this._drawCurveSegment(x, y, width);
418 SignaturePad.prototype._drawDot = function (_a) {
419 var color = _a.color, point = _a.point;
421 var width = typeof this.dotSize === 'function' ? this.dotSize() : this.dotSize;
423 this._drawCurveSegment(point.x, point.y, width);
425 ctx.fillStyle = color;
428 SignaturePad.prototype._fromData = function (pointGroups, drawCurve, drawDot) {
429 for (var _i = 0, pointGroups_1 = pointGroups; _i < pointGroups_1.length; _i++) {
430 var group = pointGroups_1[_i];
431 var color = group.color, points = group.points;
432 if (points.length > 1) {
433 for (var j = 0; j < points.length; j += 1) {
434 var basicPoint = points[j];
435 var point = new Point(basicPoint.x, basicPoint.y, basicPoint.time);
436 this.penColor = color;
440 var curve = this._addPoint(point);
442 drawCurve({ color: color, curve: curve });
455 SignaturePad.prototype._toSVG = function () {
457 var pointGroups = this._data;
458 var ratio = Math.max(window.devicePixelRatio || 1, 1);
461 var maxX = this.canvas.width / ratio;
462 var maxY = this.canvas.height / ratio;
463 var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
464 svg.setAttribute('width', this.canvas.width.toString());
465 svg.setAttribute('height', this.canvas.height.toString());
466 this._fromData(pointGroups, function (_a) {
467 var color = _a.color, curve = _a.curve;
468 var path = document.createElement('path');
469 if (!isNaN(curve.control1.x) &&
470 !isNaN(curve.control1.y) &&
471 !isNaN(curve.control2.x) &&
472 !isNaN(curve.control2.y)) {
473 var attr = "M " + curve.startPoint.x.toFixed(3) + "," + curve.startPoint.y.toFixed(3) + " "
474 + ("C " + curve.control1.x.toFixed(3) + "," + curve.control1.y.toFixed(3) + " ")
475 + (curve.control2.x.toFixed(3) + "," + curve.control2.y.toFixed(3) + " ")
476 + (curve.endPoint.x.toFixed(3) + "," + curve.endPoint.y.toFixed(3));
477 path.setAttribute('d', attr);
478 path.setAttribute('stroke-width', (curve.endWidth * 2.25).toFixed(3));
479 path.setAttribute('stroke', color);
480 path.setAttribute('fill', 'none');
481 path.setAttribute('stroke-linecap', 'round');
482 svg.appendChild(path);
485 var color = _a.color, point = _a.point;
486 var circle = document.createElement('circle');
487 var dotSize = typeof _this.dotSize === 'function' ? _this.dotSize() : _this.dotSize;
488 circle.setAttribute('r', dotSize.toString());
489 circle.setAttribute('cx', point.x.toString());
490 circle.setAttribute('cy', point.y.toString());
491 circle.setAttribute('fill', color);
492 svg.appendChild(circle);
494 var prefix = 'data:image/svg+xml;base64,';
496 + ' xmlns="http://www.w3.org/2000/svg"'
497 + ' xmlns:xlink="http://www.w3.org/1999/xlink"'
498 + (" viewBox=\"" + minX + " " + minY + " " + maxX + " " + maxY + "\"")
499 + (" width=\"" + maxX + "\"")
500 + (" height=\"" + maxY + "\"")
502 var body = svg.innerHTML;
503 if (body === undefined) {
504 var dummy = document.createElement('dummy');
505 var nodes = svg.childNodes;
506 dummy.innerHTML = '';
507 for (var i = 0; i < nodes.length; i += 1) {
508 dummy.appendChild(nodes[i].cloneNode(true));
510 body = dummy.innerHTML;
512 var footer = '</svg>';
513 var data = header + body + footer;
514 return prefix + btoa(data);