Socket
Socket
Sign inDemoInstall

signature_pad

Package Overview
Dependencies
Maintainers
1
Versions
57
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

signature_pad - npm Package Compare versions

Comparing version 2.3.2 to 3.0.0-beta.1

dist/signature_pad.m.js

19

CHANGELOG.md
## Changelog
### 3.0.0-beta.1
#### Breaking changes
- Rewrite library using TypeScript. TypeScript declaration files are now provided by the library. Hopefully, it should be a bit easier to refactor now...
- Rename generated build files. The new files are:
```bash
dist/signature_pad.js # unminified CommonJS
dist/signature_pad.min.js # minified CommonJS
dist/signature_pad.umd.js # unminified UMD
dist/signature_pad.umd.min.js # minified UMD
dist/signature_pad.m.js # unminified ES module
dist/signature_pad.m.min.js # minified ES module
```
#### Bug Fixes
- Allow scrolling via touch after calling `SignaturePad#off`([felixhammerl](https://github.com/felixhammerl) and [patrickbussmann](https://github.com/patrickbussmann)).
#### Features
- Add very basic unit tests for Point and Bezier classes.
### 2.3.2

@@ -4,0 +23,0 @@ #### Bug Fixes

1074

dist/signature_pad.js
/*!
* Signature Pad v2.3.2
* https://github.com/szimek/signature_pad
*
* Copyright 2017 Szymon Nowak
* Released under the MIT license
*
* The main idea and some parts of the code (e.g. drawing variable width Bézier curve) are taken from:
* http://corner.squareup.com/2012/07/smoother-signatures.html
*
* Implementation of interpolation using cubic Bézier curves is taken from:
* http://benknowscode.wordpress.com/2012/09/14/path-interpolation-using-cubic-bezier-and-control-point-estimation-in-javascript
*
* Algorithm for approximated length of a Bézier curve is taken from:
* http://www.lemoda.net/maths/bezier-length/index.html
*
* Signature Pad v3.0.0-beta.1 | https://github.com/szimek/signature_pad
* (c) 2018 Szymon Nowak | Released under the MIT license
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.SignaturePad = factory());
}(this, (function () { 'use strict';
'use strict';
function Point(x, y, time) {
this.x = x;
this.y = y;
this.time = time || new Date().getTime();
}
var Point = (function () {
function Point(x, y, time) {
this.x = x;
this.y = y;
this.time = time || Date.now();
}
Point.prototype.distanceTo = function (start) {
return Math.sqrt(Math.pow(this.x - start.x, 2) + Math.pow(this.y - start.y, 2));
};
Point.prototype.equals = function (other) {
return this.x === other.x && this.y === other.y && this.time === other.time;
};
Point.prototype.velocityFrom = function (start) {
return (this.time !== start.time) ? this.distanceTo(start) / (this.time - start.time) : 0;
};
return Point;
}());
Point.prototype.velocityFrom = function (start) {
return this.time !== start.time ? this.distanceTo(start) / (this.time - start.time) : 1;
};
Point.prototype.distanceTo = function (start) {
return Math.sqrt(Math.pow(this.x - start.x, 2) + Math.pow(this.y - start.y, 2));
};
Point.prototype.equals = function (other) {
return this.x === other.x && this.y === other.y && this.time === other.time;
};
function Bezier(startPoint, control1, control2, endPoint) {
this.startPoint = startPoint;
this.control1 = control1;
this.control2 = control2;
this.endPoint = endPoint;
}
// Returns approximated length.
Bezier.prototype.length = function () {
var steps = 10;
var length = 0;
var px = void 0;
var py = void 0;
for (var i = 0; i <= steps; i += 1) {
var t = i / steps;
var cx = this._point(t, this.startPoint.x, this.control1.x, this.control2.x, this.endPoint.x);
var cy = this._point(t, this.startPoint.y, this.control1.y, this.control2.y, this.endPoint.y);
if (i > 0) {
var xdiff = cx - px;
var ydiff = cy - py;
length += Math.sqrt(xdiff * xdiff + ydiff * ydiff);
var Bezier = (function () {
function Bezier(startPoint, control2, control1, endPoint, startWidth, endWidth) {
this.startPoint = startPoint;
this.control2 = control2;
this.control1 = control1;
this.endPoint = endPoint;
this.startWidth = startWidth;
this.endWidth = endWidth;
}
px = cx;
py = cy;
}
Bezier.fromPoints = function (points, widths) {
var c2 = this.calculateControlPoints(points[0], points[1], points[2]).c2;
var c3 = this.calculateControlPoints(points[1], points[2], points[3]).c1;
return new Bezier(points[1], c2, c3, points[2], widths.start, widths.end);
};
Bezier.calculateControlPoints = function (s1, s2, s3) {
var dx1 = s1.x - s2.x;
var dy1 = s1.y - s2.y;
var dx2 = s2.x - s3.x;
var dy2 = s2.y - s3.y;
var m1 = { x: (s1.x + s2.x) / 2.0, y: (s1.y + s2.y) / 2.0 };
var m2 = { x: (s2.x + s3.x) / 2.0, y: (s2.y + s3.y) / 2.0 };
var l1 = Math.sqrt((dx1 * dx1) + (dy1 * dy1));
var l2 = Math.sqrt((dx2 * dx2) + (dy2 * dy2));
var dxm = (m1.x - m2.x);
var dym = (m1.y - m2.y);
var k = l2 / (l1 + l2);
var cm = { x: m2.x + (dxm * k), y: m2.y + (dym * k) };
var tx = s2.x - cm.x;
var ty = s2.y - cm.y;
return {
c1: new Point(m1.x + tx, m1.y + ty),
c2: new Point(m2.x + tx, m2.y + ty)
};
};
Bezier.prototype.length = function () {
var steps = 10;
var length = 0;
var px;
var py;
for (var i = 0; i <= steps; i += 1) {
var t = i / steps;
var cx = this.point(t, this.startPoint.x, this.control1.x, this.control2.x, this.endPoint.x);
var cy = this.point(t, this.startPoint.y, this.control1.y, this.control2.y, this.endPoint.y);
if (i > 0) {
var xdiff = cx - px;
var ydiff = cy - py;
length += Math.sqrt((xdiff * xdiff) + (ydiff * ydiff));
}
px = cx;
py = cy;
}
return length;
};
Bezier.prototype.point = function (t, start, c1, c2, end) {
return (start * (1.0 - t) * (1.0 - t) * (1.0 - t))
+ (3.0 * c1 * (1.0 - t) * (1.0 - t) * t)
+ (3.0 * c2 * (1.0 - t) * t * t)
+ (end * t * t * t);
};
return Bezier;
}());
return length;
};
/* eslint-disable no-multi-spaces, space-in-parens */
Bezier.prototype._point = function (t, start, c1, c2, end) {
return start * (1.0 - t) * (1.0 - t) * (1.0 - t) + 3.0 * c1 * (1.0 - t) * (1.0 - t) * t + 3.0 * c2 * (1.0 - t) * t * t + end * t * t * t;
};
/* eslint-disable */
// http://stackoverflow.com/a/27078401/815507
function throttle(func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
if (!options) options = {};
var later = function later() {
previous = options.leading === false ? 0 : Date.now();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
return function () {
var now = Date.now();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout);
function throttle(fn, wait) {
if (wait === void 0) { wait = 250; }
var previous = 0;
var timeout = null;
var result;
var storedContext;
var storedArgs;
var later = function () {
previous = Date.now();
timeout = null;
}
previous = now;
result = func.apply(context, args);
if (!timeout) context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
result = fn.apply(storedContext, storedArgs);
if (!timeout) {
storedContext = null;
storedArgs = [];
}
};
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var now = Date.now();
var remaining = wait - (now - previous);
storedContext = this;
storedArgs = args;
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
previous = now;
result = fn.apply(storedContext, storedArgs);
if (!timeout) {
storedContext = null;
storedArgs = [];
}
}
else if (!timeout) {
timeout = setTimeout(later, remaining);
}
return result;
};
}
function SignaturePad(canvas, options) {
var self = this;
var opts = options || {};
this.velocityFilterWeight = opts.velocityFilterWeight || 0.7;
this.minWidth = opts.minWidth || 0.5;
this.maxWidth = opts.maxWidth || 2.5;
this.throttle = 'throttle' in opts ? opts.throttle : 16; // in miliseconds
this.minDistance = 'minDistance' in opts ? opts.minDistance : 5;
if (this.throttle) {
this._strokeMoveUpdate = throttle(SignaturePad.prototype._strokeUpdate, this.throttle);
} else {
this._strokeMoveUpdate = SignaturePad.prototype._strokeUpdate;
}
this.dotSize = opts.dotSize || function () {
return (this.minWidth + this.maxWidth) / 2;
};
this.penColor = opts.penColor || 'black';
this.backgroundColor = opts.backgroundColor || 'rgba(0,0,0,0)';
this.onBegin = opts.onBegin;
this.onEnd = opts.onEnd;
this._canvas = canvas;
this._ctx = canvas.getContext('2d');
this.clear();
// We need add these inline so they are available to unbind while still having
// access to 'self' we could use _.bind but it's not worth adding a dependency.
this._handleMouseDown = function (event) {
if (event.which === 1) {
self._mouseButtonDown = true;
self._strokeBegin(event);
var SignaturePad = (function () {
function SignaturePad(canvas, options) {
if (options === void 0) { options = {}; }
var _this = this;
this.canvas = canvas;
this.options = options;
this.velocityFilterWeight = options.velocityFilterWeight || 0.7;
this.minWidth = options.minWidth || 0.5;
this.maxWidth = options.maxWidth || 2.5;
this.throttle = ("throttle" in options ? options.throttle : 16);
this.minDistance = ("minDistance" in options ? options.minDistance : 5);
if (this.throttle) {
this._strokeMoveUpdate = throttle(SignaturePad.prototype._strokeUpdate, this.throttle);
}
else {
this._strokeMoveUpdate = SignaturePad.prototype._strokeUpdate;
}
this.dotSize = options.dotSize || function () {
return (this.minWidth + this.maxWidth) / 2;
};
this.penColor = options.penColor || "black";
this.backgroundColor = options.backgroundColor || "rgba(0,0,0,0)";
this.onBegin = options.onBegin;
this.onEnd = options.onEnd;
this._ctx = canvas.getContext("2d");
this.clear();
this._handleMouseDown = function (event) {
if (event.which === 1) {
_this._mouseButtonDown = true;
_this._strokeBegin(event);
}
};
this._handleMouseMove = function (event) {
if (_this._mouseButtonDown) {
_this._strokeMoveUpdate(event);
}
};
this._handleMouseUp = function (event) {
if (event.which === 1 && _this._mouseButtonDown) {
_this._mouseButtonDown = false;
_this._strokeEnd(event);
}
};
this._handleTouchStart = function (event) {
event.preventDefault();
if (event.targetTouches.length === 1) {
var touch = event.changedTouches[0];
_this._strokeBegin(touch);
}
};
this._handleTouchMove = function (event) {
event.preventDefault();
var touch = event.targetTouches[0];
_this._strokeMoveUpdate(touch);
};
this._handleTouchEnd = function (event) {
var wasCanvasTouched = event.target === _this.canvas;
if (wasCanvasTouched) {
event.preventDefault();
var touch = event.targetTouches[0];
_this._strokeEnd(touch);
}
};
this.on();
}
};
this._handleMouseMove = function (event) {
if (self._mouseButtonDown) {
self._strokeMoveUpdate(event);
}
};
this._handleMouseUp = function (event) {
if (event.which === 1 && self._mouseButtonDown) {
self._mouseButtonDown = false;
self._strokeEnd(event);
}
};
this._handleTouchStart = function (event) {
if (event.targetTouches.length === 1) {
var touch = event.changedTouches[0];
self._strokeBegin(touch);
}
};
this._handleTouchMove = function (event) {
// Prevent scrolling.
event.preventDefault();
var touch = event.targetTouches[0];
self._strokeMoveUpdate(touch);
};
this._handleTouchEnd = function (event) {
var wasCanvasTouched = event.target === self._canvas;
if (wasCanvasTouched) {
event.preventDefault();
self._strokeEnd(event);
}
};
// Enable mouse and touch event handlers
this.on();
}
// Public methods
SignaturePad.prototype.clear = function () {
var ctx = this._ctx;
var canvas = this._canvas;
ctx.fillStyle = this.backgroundColor;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(0, 0, canvas.width, canvas.height);
this._data = [];
this._reset();
this._isEmpty = true;
};
SignaturePad.prototype.fromDataURL = function (dataUrl) {
var _this = this;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var image = new Image();
var ratio = options.ratio || window.devicePixelRatio || 1;
var width = options.width || this._canvas.width / ratio;
var height = options.height || this._canvas.height / ratio;
this._reset();
image.src = dataUrl;
image.onload = function () {
_this._ctx.drawImage(image, 0, 0, width, height);
};
this._isEmpty = false;
};
SignaturePad.prototype.toDataURL = function (type) {
var _canvas;
switch (type) {
case 'image/svg+xml':
return this._toSVG();
default:
for (var _len = arguments.length, options = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
options[_key - 1] = arguments[_key];
}
return (_canvas = this._canvas).toDataURL.apply(_canvas, [type].concat(options));
}
};
SignaturePad.prototype.on = function () {
this._handleMouseEvents();
this._handleTouchEvents();
};
SignaturePad.prototype.off = function () {
this._canvas.removeEventListener('mousedown', this._handleMouseDown);
this._canvas.removeEventListener('mousemove', this._handleMouseMove);
document.removeEventListener('mouseup', this._handleMouseUp);
this._canvas.removeEventListener('touchstart', this._handleTouchStart);
this._canvas.removeEventListener('touchmove', this._handleTouchMove);
this._canvas.removeEventListener('touchend', this._handleTouchEnd);
};
SignaturePad.prototype.isEmpty = function () {
return this._isEmpty;
};
// Private methods
SignaturePad.prototype._strokeBegin = function (event) {
this._data.push([]);
this._reset();
this._strokeUpdate(event);
if (typeof this.onBegin === 'function') {
this.onBegin(event);
}
};
SignaturePad.prototype._strokeUpdate = function (event) {
var x = event.clientX;
var y = event.clientY;
var point = this._createPoint(x, y);
var lastPointGroup = this._data[this._data.length - 1];
var lastPoint = lastPointGroup && lastPointGroup[lastPointGroup.length - 1];
var isLastPointTooClose = lastPoint && point.distanceTo(lastPoint) < this.minDistance;
// Skip this point if it's too close to the previous one
if (!(lastPoint && isLastPointTooClose)) {
var _addPoint = this._addPoint(point),
curve = _addPoint.curve,
widths = _addPoint.widths;
if (curve && widths) {
this._drawCurve(curve, widths.start, widths.end);
}
this._data[this._data.length - 1].push({
x: point.x,
y: point.y,
time: point.time,
color: this.penColor
});
}
};
SignaturePad.prototype._strokeEnd = function (event) {
var canDrawCurve = this.points.length > 2;
var point = this.points[0]; // Point instance
if (!canDrawCurve && point) {
this._drawDot(point);
}
if (point) {
var lastPointGroup = this._data[this._data.length - 1];
var lastPoint = lastPointGroup[lastPointGroup.length - 1]; // plain object
// When drawing a dot, there's only one point in a group, so without this check
// such group would end up with exactly the same 2 points.
if (!point.equals(lastPoint)) {
lastPointGroup.push({
x: point.x,
y: point.y,
time: point.time,
color: this.penColor
});
}
}
if (typeof this.onEnd === 'function') {
this.onEnd(event);
}
};
SignaturePad.prototype._handleMouseEvents = function () {
this._mouseButtonDown = false;
this._canvas.addEventListener('mousedown', this._handleMouseDown);
this._canvas.addEventListener('mousemove', this._handleMouseMove);
document.addEventListener('mouseup', this._handleMouseUp);
};
SignaturePad.prototype._handleTouchEvents = function () {
// Pass touch events to canvas element on mobile IE11 and Edge.
this._canvas.style.msTouchAction = 'none';
this._canvas.style.touchAction = 'none';
this._canvas.addEventListener('touchstart', this._handleTouchStart);
this._canvas.addEventListener('touchmove', this._handleTouchMove);
this._canvas.addEventListener('touchend', this._handleTouchEnd);
};
SignaturePad.prototype._reset = function () {
this.points = [];
this._lastVelocity = 0;
this._lastWidth = (this.minWidth + this.maxWidth) / 2;
this._ctx.fillStyle = this.penColor;
};
SignaturePad.prototype._createPoint = function (x, y, time) {
var rect = this._canvas.getBoundingClientRect();
return new Point(x - rect.left, y - rect.top, time || new Date().getTime());
};
SignaturePad.prototype._addPoint = function (point) {
var points = this.points;
var tmp = void 0;
points.push(point);
if (points.length > 2) {
// To reduce the initial lag make it work with 3 points
// by copying the first point to the beginning.
if (points.length === 3) points.unshift(points[0]);
tmp = this._calculateCurveControlPoints(points[0], points[1], points[2]);
var c2 = tmp.c2;
tmp = this._calculateCurveControlPoints(points[1], points[2], points[3]);
var c3 = tmp.c1;
var curve = new Bezier(points[1], c2, c3, points[2]);
var widths = this._calculateCurveWidths(curve);
// Remove the first element from the list,
// so that we always have no more than 4 points in points array.
points.shift();
return { curve: curve, widths: widths };
}
return {};
};
SignaturePad.prototype._calculateCurveControlPoints = function (s1, s2, s3) {
var dx1 = s1.x - s2.x;
var dy1 = s1.y - s2.y;
var dx2 = s2.x - s3.x;
var dy2 = s2.y - s3.y;
var m1 = { x: (s1.x + s2.x) / 2.0, y: (s1.y + s2.y) / 2.0 };
var m2 = { x: (s2.x + s3.x) / 2.0, y: (s2.y + s3.y) / 2.0 };
var l1 = Math.sqrt(dx1 * dx1 + dy1 * dy1);
var l2 = Math.sqrt(dx2 * dx2 + dy2 * dy2);
var dxm = m1.x - m2.x;
var dym = m1.y - m2.y;
var k = l2 / (l1 + l2);
var cm = { x: m2.x + dxm * k, y: m2.y + dym * k };
var tx = s2.x - cm.x;
var ty = s2.y - cm.y;
return {
c1: new Point(m1.x + tx, m1.y + ty),
c2: new Point(m2.x + tx, m2.y + ty)
};
};
SignaturePad.prototype._calculateCurveWidths = function (curve) {
var startPoint = curve.startPoint;
var endPoint = curve.endPoint;
var widths = { start: null, end: null };
var velocity = this.velocityFilterWeight * endPoint.velocityFrom(startPoint) + (1 - this.velocityFilterWeight) * this._lastVelocity;
var newWidth = this._strokeWidth(velocity);
widths.start = this._lastWidth;
widths.end = newWidth;
this._lastVelocity = velocity;
this._lastWidth = newWidth;
return widths;
};
SignaturePad.prototype._strokeWidth = function (velocity) {
return Math.max(this.maxWidth / (velocity + 1), this.minWidth);
};
SignaturePad.prototype._drawPoint = function (x, y, size) {
var ctx = this._ctx;
ctx.moveTo(x, y);
ctx.arc(x, y, size, 0, 2 * Math.PI, false);
this._isEmpty = false;
};
SignaturePad.prototype._drawCurve = function (curve, startWidth, endWidth) {
var ctx = this._ctx;
var widthDelta = endWidth - startWidth;
var drawSteps = Math.floor(curve.length());
ctx.beginPath();
for (var i = 0; i < drawSteps; i += 1) {
// Calculate the Bezier (x, y) coordinate for this step.
var t = i / drawSteps;
var tt = t * t;
var ttt = tt * t;
var u = 1 - t;
var uu = u * u;
var uuu = uu * u;
var x = uuu * curve.startPoint.x;
x += 3 * uu * t * curve.control1.x;
x += 3 * u * tt * curve.control2.x;
x += ttt * curve.endPoint.x;
var y = uuu * curve.startPoint.y;
y += 3 * uu * t * curve.control1.y;
y += 3 * u * tt * curve.control2.y;
y += ttt * curve.endPoint.y;
var width = startWidth + ttt * widthDelta;
this._drawPoint(x, y, width);
}
ctx.closePath();
ctx.fill();
};
SignaturePad.prototype._drawDot = function (point) {
var ctx = this._ctx;
var width = typeof this.dotSize === 'function' ? this.dotSize() : this.dotSize;
ctx.beginPath();
this._drawPoint(point.x, point.y, width);
ctx.closePath();
ctx.fill();
};
SignaturePad.prototype._fromData = function (pointGroups, drawCurve, drawDot) {
for (var i = 0; i < pointGroups.length; i += 1) {
var group = pointGroups[i];
if (group.length > 1) {
for (var j = 0; j < group.length; j += 1) {
var rawPoint = group[j];
var point = new Point(rawPoint.x, rawPoint.y, rawPoint.time);
var color = rawPoint.color;
if (j === 0) {
// First point in a group. Nothing to draw yet.
// All points in the group have the same color, so it's enough to set
// penColor just at the beginning.
this.penColor = color;
this._reset();
this._addPoint(point);
} else if (j !== group.length - 1) {
// Middle point in a group.
var _addPoint2 = this._addPoint(point),
curve = _addPoint2.curve,
widths = _addPoint2.widths;
if (curve && widths) {
drawCurve(curve, widths, color);
}
} else {
// Last point in a group. Do nothing.
SignaturePad.prototype.clear = function () {
var ctx = this._ctx;
var canvas = this.canvas;
ctx.fillStyle = this.backgroundColor;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(0, 0, canvas.width, canvas.height);
this._data = [];
this._reset();
this._isEmpty = true;
};
SignaturePad.prototype.fromDataURL = function (dataUrl, options) {
var _this = this;
if (options === void 0) { options = {}; }
var image = new Image();
var ratio = options.ratio || window.devicePixelRatio || 1;
var width = options.width || (this.canvas.width / ratio);
var height = options.height || (this.canvas.height / ratio);
this._reset();
image.src = dataUrl;
image.onload = function () {
_this._ctx.drawImage(image, 0, 0, width, height);
};
this._isEmpty = false;
};
SignaturePad.prototype.toDataURL = function (type, encoderOptions) {
switch (type) {
case "image/svg+xml":
return this._toSVG();
default:
return this.canvas.toDataURL(type, encoderOptions);
}
}
} else {
this._reset();
var _rawPoint = group[0];
drawDot(_rawPoint);
}
}
};
};
SignaturePad.prototype.on = function () {
this._handleMouseEvents();
this._handleTouchEvents();
};
SignaturePad.prototype.off = function () {
this.canvas.style.msTouchAction = "auto";
this.canvas.style.touchAction = "auto";
this.canvas.removeEventListener("mousedown", this._handleMouseDown);
this.canvas.removeEventListener("mousemove", this._handleMouseMove);
document.removeEventListener("mouseup", this._handleMouseUp);
this.canvas.removeEventListener("touchstart", this._handleTouchStart);
this.canvas.removeEventListener("touchmove", this._handleTouchMove);
this.canvas.removeEventListener("touchend", this._handleTouchEnd);
};
SignaturePad.prototype.isEmpty = function () {
return this._isEmpty;
};
SignaturePad.prototype.fromData = function (pointGroups) {
var _this = this;
this.clear();
this._fromData(pointGroups, function (_a) {
var color = _a.color, curve = _a.curve;
return _this._drawCurve({ color: color, curve: curve });
}, function (_a) {
var color = _a.color, point = _a.point;
return _this._drawDot({ color: color, point: point });
});
this._data = pointGroups;
};
SignaturePad.prototype.toData = function () {
return this._data;
};
SignaturePad.prototype._strokeBegin = function (event) {
var newPointGroup = {
color: this.penColor,
points: []
};
this._data.push(newPointGroup);
this._reset();
this._strokeUpdate(event);
if (typeof this.onBegin === "function") {
this.onBegin(event);
}
};
SignaturePad.prototype._strokeUpdate = function (event) {
var x = event.clientX;
var y = event.clientY;
var point = this._createPoint(x, y);
var lastPointGroup = this._data[this._data.length - 1];
var lastPoints = lastPointGroup.points;
var lastPoint = lastPoints.length > 0 && lastPoints[lastPoints.length - 1];
var isLastPointTooClose = lastPoint ? point.distanceTo(lastPoint) <= this.minDistance : false;
var color = lastPointGroup.color;
if (!lastPoint || !(lastPoint && isLastPointTooClose)) {
var curve = this._addPoint(point);
if (!lastPoint) {
this._drawDot({ color: color, point: point });
}
else if (curve) {
this._drawCurve({ color: color, curve: curve });
}
lastPoints.push({
time: point.time,
x: point.x,
y: point.y
});
}
};
SignaturePad.prototype._strokeEnd = function (event) {
this._strokeUpdate(event);
if (typeof this.onEnd === "function") {
this.onEnd(event);
}
};
SignaturePad.prototype._handleMouseEvents = function () {
this._mouseButtonDown = false;
this.canvas.addEventListener("mousedown", this._handleMouseDown);
this.canvas.addEventListener("mousemove", this._handleMouseMove);
document.addEventListener("mouseup", this._handleMouseUp);
};
SignaturePad.prototype._handleTouchEvents = function () {
this.canvas.style.msTouchAction = "none";
this.canvas.style.touchAction = "none";
this.canvas.addEventListener("touchstart", this._handleTouchStart);
this.canvas.addEventListener("touchmove", this._handleTouchMove);
this.canvas.addEventListener("touchend", this._handleTouchEnd);
};
SignaturePad.prototype._reset = function () {
this._points = [];
this._lastVelocity = 0;
this._lastWidth = (this.minWidth + this.maxWidth) / 2;
this._ctx.fillStyle = this.penColor;
};
SignaturePad.prototype._createPoint = function (x, y) {
var rect = this.canvas.getBoundingClientRect();
return new Point(x - rect.left, y - rect.top, new Date().getTime());
};
SignaturePad.prototype._addPoint = function (point) {
var _points = this._points;
_points.push(point);
if (_points.length > 2) {
if (_points.length === 3) {
_points.unshift(_points[0]);
}
var widths = this._calculateCurveWidths(_points[1], _points[2]);
var curve = Bezier.fromPoints(_points, widths);
_points.shift();
return curve;
}
return null;
};
SignaturePad.prototype._calculateCurveWidths = function (startPoint, endPoint) {
var velocity = (this.velocityFilterWeight * endPoint.velocityFrom(startPoint))
+ ((1 - this.velocityFilterWeight) * this._lastVelocity);
var newWidth = this._strokeWidth(velocity);
var widths = {
end: newWidth,
start: this._lastWidth
};
this._lastVelocity = velocity;
this._lastWidth = newWidth;
return widths;
};
SignaturePad.prototype._strokeWidth = function (velocity) {
return Math.max(this.maxWidth / (velocity + 1), this.minWidth);
};
SignaturePad.prototype._drawCurveSegment = function (x, y, width) {
var ctx = this._ctx;
ctx.moveTo(x, y);
ctx.arc(x, y, width, 0, 2 * Math.PI, false);
this._isEmpty = false;
};
SignaturePad.prototype._drawCurve = function (_a) {
var color = _a.color, curve = _a.curve;
var ctx = this._ctx;
var widthDelta = curve.endWidth - curve.startWidth;
var drawSteps = Math.floor(curve.length()) * 2;
ctx.beginPath();
ctx.fillStyle = color;
for (var i = 0; i < drawSteps; i += 1) {
var t = i / drawSteps;
var tt = t * t;
var ttt = tt * t;
var u = 1 - t;
var uu = u * u;
var uuu = uu * u;
var x = uuu * curve.startPoint.x;
x += 3 * uu * t * curve.control1.x;
x += 3 * u * tt * curve.control2.x;
x += ttt * curve.endPoint.x;
var y = uuu * curve.startPoint.y;
y += 3 * uu * t * curve.control1.y;
y += 3 * u * tt * curve.control2.y;
y += ttt * curve.endPoint.y;
var width = curve.startWidth + (ttt * widthDelta);
this._drawCurveSegment(x, y, width);
}
ctx.closePath();
ctx.fill();
};
SignaturePad.prototype._drawDot = function (_a) {
var color = _a.color, point = _a.point;
var ctx = this._ctx;
var width = typeof this.dotSize === "function" ? this.dotSize() : this.dotSize;
ctx.beginPath();
this._drawCurveSegment(point.x, point.y, width);
ctx.closePath();
ctx.fillStyle = color;
ctx.fill();
};
SignaturePad.prototype._fromData = function (pointGroups, drawCurve, drawDot) {
for (var _i = 0, pointGroups_1 = pointGroups; _i < pointGroups_1.length; _i++) {
var group = pointGroups_1[_i];
var color = group.color, points = group.points;
if (points.length > 1) {
for (var j = 0; j < points.length; j += 1) {
var basicPoint = points[j];
var point = new Point(basicPoint.x, basicPoint.y, basicPoint.time);
this.penColor = color;
if (j === 0) {
this._reset();
}
var curve = this._addPoint(point);
if (curve) {
drawCurve({ color: color, curve: curve });
}
}
}
else {
this._reset();
drawDot({
color: color,
point: points[0]
});
}
}
};
SignaturePad.prototype._toSVG = function () {
var _this = this;
var pointGroups = this._data;
var ratio = Math.max(window.devicePixelRatio || 1, 1);
var minX = 0;
var minY = 0;
var maxX = this.canvas.width / ratio;
var maxY = this.canvas.height / ratio;
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("width", this.canvas.width.toString());
svg.setAttribute("height", this.canvas.height.toString());
this._fromData(pointGroups, function (_a) {
var color = _a.color, curve = _a.curve;
var path = document.createElement("path");
if (!isNaN(curve.control1.x) &&
!isNaN(curve.control1.y) &&
!isNaN(curve.control2.x) &&
!isNaN(curve.control2.y)) {
var attr = "M " + curve.startPoint.x.toFixed(3) + "," + curve.startPoint.y.toFixed(3) + " "
+ ("C " + curve.control1.x.toFixed(3) + "," + curve.control1.y.toFixed(3) + " ")
+ (curve.control2.x.toFixed(3) + "," + curve.control2.y.toFixed(3) + " ")
+ (curve.endPoint.x.toFixed(3) + "," + curve.endPoint.y.toFixed(3));
path.setAttribute("d", attr);
path.setAttribute("stroke-width", (curve.endWidth * 2.25).toFixed(3));
path.setAttribute("stroke", color);
path.setAttribute("fill", "none");
path.setAttribute("stroke-linecap", "round");
svg.appendChild(path);
}
}, function (_a) {
var color = _a.color, point = _a.point;
var circle = document.createElement("circle");
var dotSize = typeof _this.dotSize === "function" ? _this.dotSize() : _this.dotSize;
circle.setAttribute("r", dotSize.toString());
circle.setAttribute("cx", point.x.toString());
circle.setAttribute("cy", point.y.toString());
circle.setAttribute("fill", color);
svg.appendChild(circle);
});
var prefix = "data:image/svg+xml;base64,";
var header = "<svg"
+ " xmlns=\"http://www.w3.org/2000/svg\""
+ " xmlns:xlink=\"http://www.w3.org/1999/xlink\""
+ (" viewBox=\"" + minX + " " + minY + " " + maxX + " " + maxY + "\"")
+ (" width=\"" + maxX + "\"")
+ (" height=\"" + maxY + "\"")
+ ">";
var body = svg.innerHTML;
if (body === undefined) {
var dummy = document.createElement("dummy");
var nodes = svg.childNodes;
dummy.innerHTML = "";
for (var i = 0; i < nodes.length; i += 1) {
dummy.appendChild(nodes[i].cloneNode(true));
}
body = dummy.innerHTML;
}
var footer = "</svg>";
var data = header + body + footer;
return prefix + btoa(data);
};
return SignaturePad;
}());
SignaturePad.prototype._toSVG = function () {
var _this2 = this;
var pointGroups = this._data;
var canvas = this._canvas;
var ratio = Math.max(window.devicePixelRatio || 1, 1);
var minX = 0;
var minY = 0;
var maxX = canvas.width / ratio;
var maxY = canvas.height / ratio;
var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttributeNS(null, 'width', canvas.width);
svg.setAttributeNS(null, 'height', canvas.height);
this._fromData(pointGroups, function (curve, widths, color) {
var path = document.createElement('path');
// Need to check curve for NaN values, these pop up when drawing
// lines on the canvas that are not continuous. E.g. Sharp corners
// or stopping mid-stroke and than continuing without lifting mouse.
if (!isNaN(curve.control1.x) && !isNaN(curve.control1.y) && !isNaN(curve.control2.x) && !isNaN(curve.control2.y)) {
var attr = 'M ' + curve.startPoint.x.toFixed(3) + ',' + curve.startPoint.y.toFixed(3) + ' ' + ('C ' + curve.control1.x.toFixed(3) + ',' + curve.control1.y.toFixed(3) + ' ') + (curve.control2.x.toFixed(3) + ',' + curve.control2.y.toFixed(3) + ' ') + (curve.endPoint.x.toFixed(3) + ',' + curve.endPoint.y.toFixed(3));
path.setAttribute('d', attr);
path.setAttribute('stroke-width', (widths.end * 2.25).toFixed(3));
path.setAttribute('stroke', color);
path.setAttribute('fill', 'none');
path.setAttribute('stroke-linecap', 'round');
svg.appendChild(path);
}
}, function (rawPoint) {
var circle = document.createElement('circle');
var dotSize = typeof _this2.dotSize === 'function' ? _this2.dotSize() : _this2.dotSize;
circle.setAttribute('r', dotSize);
circle.setAttribute('cx', rawPoint.x);
circle.setAttribute('cy', rawPoint.y);
circle.setAttribute('fill', rawPoint.color);
svg.appendChild(circle);
});
var prefix = 'data:image/svg+xml;base64,';
var header = '<svg' + ' xmlns="http://www.w3.org/2000/svg"' + ' xmlns:xlink="http://www.w3.org/1999/xlink"' + (' viewBox="' + minX + ' ' + minY + ' ' + maxX + ' ' + maxY + '"') + (' width="' + maxX + '"') + (' height="' + maxY + '"') + '>';
var body = svg.innerHTML;
// IE hack for missing innerHTML property on SVGElement
if (body === undefined) {
var dummy = document.createElement('dummy');
var nodes = svg.childNodes;
dummy.innerHTML = '';
for (var i = 0; i < nodes.length; i += 1) {
dummy.appendChild(nodes[i].cloneNode(true));
}
body = dummy.innerHTML;
}
var footer = '</svg>';
var data = header + body + footer;
return prefix + btoa(data);
};
SignaturePad.prototype.fromData = function (pointGroups) {
var _this3 = this;
this.clear();
this._fromData(pointGroups, function (curve, widths) {
return _this3._drawCurve(curve, widths.start, widths.end);
}, function (rawPoint) {
return _this3._drawDot(rawPoint);
});
this._data = pointGroups;
};
SignaturePad.prototype.toData = function () {
return this._data;
};
return SignaturePad;
})));
module.exports = SignaturePad;

@@ -1,1 +0,1 @@

!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):t.SignaturePad=e()}(this,function(){"use strict";function t(t,e,i){this.x=t,this.y=e,this.time=i||(new Date).getTime()}function e(t,e,i,o){this.startPoint=t,this.control1=e,this.control2=i,this.endPoint=o}function i(t,e,i){var o,n,s,r=null,h=0;i||(i={});var a=function(){h=!1===i.leading?0:Date.now(),r=null,s=t.apply(o,n),r||(o=n=null)};return function(){var c=Date.now();h||!1!==i.leading||(h=c);var d=e-(c-h);return o=this,n=arguments,d<=0||d>e?(r&&(clearTimeout(r),r=null),h=c,s=t.apply(o,n),r||(o=n=null)):r||!1===i.trailing||(r=setTimeout(a,d)),s}}function o(t,e){var n=this,s=e||{};this.velocityFilterWeight=s.velocityFilterWeight||.7,this.minWidth=s.minWidth||.5,this.maxWidth=s.maxWidth||2.5,this.throttle="throttle"in s?s.throttle:16,this.minDistance="minDistance"in s?s.minDistance:5,this.throttle?this._strokeMoveUpdate=i(o.prototype._strokeUpdate,this.throttle):this._strokeMoveUpdate=o.prototype._strokeUpdate,this.dotSize=s.dotSize||function(){return(this.minWidth+this.maxWidth)/2},this.penColor=s.penColor||"black",this.backgroundColor=s.backgroundColor||"rgba(0,0,0,0)",this.onBegin=s.onBegin,this.onEnd=s.onEnd,this._canvas=t,this._ctx=t.getContext("2d"),this.clear(),this._handleMouseDown=function(t){1===t.which&&(n._mouseButtonDown=!0,n._strokeBegin(t))},this._handleMouseMove=function(t){n._mouseButtonDown&&n._strokeMoveUpdate(t)},this._handleMouseUp=function(t){1===t.which&&n._mouseButtonDown&&(n._mouseButtonDown=!1,n._strokeEnd(t))},this._handleTouchStart=function(t){if(1===t.targetTouches.length){var e=t.changedTouches[0];n._strokeBegin(e)}},this._handleTouchMove=function(t){t.preventDefault();var e=t.targetTouches[0];n._strokeMoveUpdate(e)},this._handleTouchEnd=function(t){t.target===n._canvas&&(t.preventDefault(),n._strokeEnd(t))},this.on()}return t.prototype.velocityFrom=function(t){return this.time!==t.time?this.distanceTo(t)/(this.time-t.time):1},t.prototype.distanceTo=function(t){return Math.sqrt(Math.pow(this.x-t.x,2)+Math.pow(this.y-t.y,2))},t.prototype.equals=function(t){return this.x===t.x&&this.y===t.y&&this.time===t.time},e.prototype.length=function(){for(var t=0,e=void 0,i=void 0,o=0;o<=10;o+=1){var n=o/10,s=this._point(n,this.startPoint.x,this.control1.x,this.control2.x,this.endPoint.x),r=this._point(n,this.startPoint.y,this.control1.y,this.control2.y,this.endPoint.y);if(o>0){var h=s-e,a=r-i;t+=Math.sqrt(h*h+a*a)}e=s,i=r}return t},e.prototype._point=function(t,e,i,o,n){return e*(1-t)*(1-t)*(1-t)+3*i*(1-t)*(1-t)*t+3*o*(1-t)*t*t+n*t*t*t},o.prototype.clear=function(){var t=this._ctx,e=this._canvas;t.fillStyle=this.backgroundColor,t.clearRect(0,0,e.width,e.height),t.fillRect(0,0,e.width,e.height),this._data=[],this._reset(),this._isEmpty=!0},o.prototype.fromDataURL=function(t){var e=this,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=new Image,n=i.ratio||window.devicePixelRatio||1,s=i.width||this._canvas.width/n,r=i.height||this._canvas.height/n;this._reset(),o.src=t,o.onload=function(){e._ctx.drawImage(o,0,0,s,r)},this._isEmpty=!1},o.prototype.toDataURL=function(t){var e;switch(t){case"image/svg+xml":return this._toSVG();default:for(var i=arguments.length,o=Array(i>1?i-1:0),n=1;n<i;n++)o[n-1]=arguments[n];return(e=this._canvas).toDataURL.apply(e,[t].concat(o))}},o.prototype.on=function(){this._handleMouseEvents(),this._handleTouchEvents()},o.prototype.off=function(){this._canvas.removeEventListener("mousedown",this._handleMouseDown),this._canvas.removeEventListener("mousemove",this._handleMouseMove),document.removeEventListener("mouseup",this._handleMouseUp),this._canvas.removeEventListener("touchstart",this._handleTouchStart),this._canvas.removeEventListener("touchmove",this._handleTouchMove),this._canvas.removeEventListener("touchend",this._handleTouchEnd)},o.prototype.isEmpty=function(){return this._isEmpty},o.prototype._strokeBegin=function(t){this._data.push([]),this._reset(),this._strokeUpdate(t),"function"==typeof this.onBegin&&this.onBegin(t)},o.prototype._strokeUpdate=function(t){var e=t.clientX,i=t.clientY,o=this._createPoint(e,i),n=this._data[this._data.length-1],s=n&&n[n.length-1],r=s&&o.distanceTo(s)<this.minDistance;if(!s||!r){var h=this._addPoint(o),a=h.curve,c=h.widths;a&&c&&this._drawCurve(a,c.start,c.end),this._data[this._data.length-1].push({x:o.x,y:o.y,time:o.time,color:this.penColor})}},o.prototype._strokeEnd=function(t){var e=this.points.length>2,i=this.points[0];if(!e&&i&&this._drawDot(i),i){var o=this._data[this._data.length-1],n=o[o.length-1];i.equals(n)||o.push({x:i.x,y:i.y,time:i.time,color:this.penColor})}"function"==typeof this.onEnd&&this.onEnd(t)},o.prototype._handleMouseEvents=function(){this._mouseButtonDown=!1,this._canvas.addEventListener("mousedown",this._handleMouseDown),this._canvas.addEventListener("mousemove",this._handleMouseMove),document.addEventListener("mouseup",this._handleMouseUp)},o.prototype._handleTouchEvents=function(){this._canvas.style.msTouchAction="none",this._canvas.style.touchAction="none",this._canvas.addEventListener("touchstart",this._handleTouchStart),this._canvas.addEventListener("touchmove",this._handleTouchMove),this._canvas.addEventListener("touchend",this._handleTouchEnd)},o.prototype._reset=function(){this.points=[],this._lastVelocity=0,this._lastWidth=(this.minWidth+this.maxWidth)/2,this._ctx.fillStyle=this.penColor},o.prototype._createPoint=function(e,i,o){var n=this._canvas.getBoundingClientRect();return new t(e-n.left,i-n.top,o||(new Date).getTime())},o.prototype._addPoint=function(t){var i=this.points,o=void 0;if(i.push(t),i.length>2){3===i.length&&i.unshift(i[0]),o=this._calculateCurveControlPoints(i[0],i[1],i[2]);var n=o.c2;o=this._calculateCurveControlPoints(i[1],i[2],i[3]);var s=o.c1,r=new e(i[1],n,s,i[2]),h=this._calculateCurveWidths(r);return i.shift(),{curve:r,widths:h}}return{}},o.prototype._calculateCurveControlPoints=function(e,i,o){var n=e.x-i.x,s=e.y-i.y,r=i.x-o.x,h=i.y-o.y,a={x:(e.x+i.x)/2,y:(e.y+i.y)/2},c={x:(i.x+o.x)/2,y:(i.y+o.y)/2},d=Math.sqrt(n*n+s*s),l=Math.sqrt(r*r+h*h),u=a.x-c.x,v=a.y-c.y,p=l/(d+l),_={x:c.x+u*p,y:c.y+v*p},y=i.x-_.x,f=i.y-_.y;return{c1:new t(a.x+y,a.y+f),c2:new t(c.x+y,c.y+f)}},o.prototype._calculateCurveWidths=function(t){var e=t.startPoint,i=t.endPoint,o={start:null,end:null},n=this.velocityFilterWeight*i.velocityFrom(e)+(1-this.velocityFilterWeight)*this._lastVelocity,s=this._strokeWidth(n);return o.start=this._lastWidth,o.end=s,this._lastVelocity=n,this._lastWidth=s,o},o.prototype._strokeWidth=function(t){return Math.max(this.maxWidth/(t+1),this.minWidth)},o.prototype._drawPoint=function(t,e,i){var o=this._ctx;o.moveTo(t,e),o.arc(t,e,i,0,2*Math.PI,!1),this._isEmpty=!1},o.prototype._drawCurve=function(t,e,i){var o=this._ctx,n=i-e,s=Math.floor(t.length());o.beginPath();for(var r=0;r<s;r+=1){var h=r/s,a=h*h,c=a*h,d=1-h,l=d*d,u=l*d,v=u*t.startPoint.x;v+=3*l*h*t.control1.x,v+=3*d*a*t.control2.x,v+=c*t.endPoint.x;var p=u*t.startPoint.y;p+=3*l*h*t.control1.y,p+=3*d*a*t.control2.y,p+=c*t.endPoint.y;var _=e+c*n;this._drawPoint(v,p,_)}o.closePath(),o.fill()},o.prototype._drawDot=function(t){var e=this._ctx,i="function"==typeof this.dotSize?this.dotSize():this.dotSize;e.beginPath(),this._drawPoint(t.x,t.y,i),e.closePath(),e.fill()},o.prototype._fromData=function(e,i,o){for(var n=0;n<e.length;n+=1){var s=e[n];if(s.length>1)for(var r=0;r<s.length;r+=1){var h=s[r],a=new t(h.x,h.y,h.time),c=h.color;if(0===r)this.penColor=c,this._reset(),this._addPoint(a);else if(r!==s.length-1){var d=this._addPoint(a),l=d.curve,u=d.widths;l&&u&&i(l,u,c)}}else{this._reset();o(s[0])}}},o.prototype._toSVG=function(){var t=this,e=this._data,i=this._canvas,o=Math.max(window.devicePixelRatio||1,1),n=i.width/o,s=i.height/o,r=document.createElementNS("http://www.w3.org/2000/svg","svg");r.setAttributeNS(null,"width",i.width),r.setAttributeNS(null,"height",i.height),this._fromData(e,function(t,e,i){var o=document.createElement("path");if(!(isNaN(t.control1.x)||isNaN(t.control1.y)||isNaN(t.control2.x)||isNaN(t.control2.y))){var n="M "+t.startPoint.x.toFixed(3)+","+t.startPoint.y.toFixed(3)+" C "+t.control1.x.toFixed(3)+","+t.control1.y.toFixed(3)+" "+t.control2.x.toFixed(3)+","+t.control2.y.toFixed(3)+" "+t.endPoint.x.toFixed(3)+","+t.endPoint.y.toFixed(3);o.setAttribute("d",n),o.setAttribute("stroke-width",(2.25*e.end).toFixed(3)),o.setAttribute("stroke",i),o.setAttribute("fill","none"),o.setAttribute("stroke-linecap","round"),r.appendChild(o)}},function(e){var i=document.createElement("circle"),o="function"==typeof t.dotSize?t.dotSize():t.dotSize;i.setAttribute("r",o),i.setAttribute("cx",e.x),i.setAttribute("cy",e.y),i.setAttribute("fill",e.color),r.appendChild(i)});var h='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 '+n+" "+s+'" width="'+n+'" height="'+s+'">',a=r.innerHTML;if(void 0===a){var c=document.createElement("dummy"),d=r.childNodes;c.innerHTML="";for(var l=0;l<d.length;l+=1)c.appendChild(d[l].cloneNode(!0));a=c.innerHTML}var u=h+a+"</svg>";return"data:image/svg+xml;base64,"+btoa(u)},o.prototype.fromData=function(t){var e=this;this.clear(),this._fromData(t,function(t,i){return e._drawCurve(t,i.start,i.end)},function(t){return e._drawDot(t)}),this._data=t},o.prototype.toData=function(){return this._data},o});
"use strict";var Point=function(){function t(t,e,o){this.x=t,this.y=e,this.time=o||Date.now()}return t.prototype.distanceTo=function(t){return Math.sqrt(Math.pow(this.x-t.x,2)+Math.pow(this.y-t.y,2))},t.prototype.equals=function(t){return this.x===t.x&&this.y===t.y&&this.time===t.time},t.prototype.velocityFrom=function(t){return this.time!==t.time?this.distanceTo(t)/(this.time-t.time):0},t}(),Bezier=function(){function t(t,e,o,i,n,s){this.startPoint=t,this.control2=e,this.control1=o,this.endPoint=i,this.startWidth=n,this.endWidth=s}return t.fromPoints=function(e,o){var i=this.calculateControlPoints(e[0],e[1],e[2]).c2,n=this.calculateControlPoints(e[1],e[2],e[3]).c1;return new t(e[1],i,n,e[2],o.start,o.end)},t.calculateControlPoints=function(t,e,o){var i=t.x-e.x,n=t.y-e.y,s=e.x-o.x,r=e.y-o.y,h=(t.x+e.x)/2,a=(t.y+e.y)/2,c=(e.x+o.x)/2,u=(e.y+o.y)/2,l=Math.sqrt(i*i+n*n),d=Math.sqrt(s*s+r*r),v=d/(l+d),p=c+(h-c)*v,f=u+(a-u)*v,_=e.x-p,y=e.y-f;return{c1:new Point(h+_,a+y),c2:new Point(c+_,u+y)}},t.prototype.length=function(){for(var t,e,o=0,i=0;i<=10;i+=1){var n=i/10,s=this.point(n,this.startPoint.x,this.control1.x,this.control2.x,this.endPoint.x),r=this.point(n,this.startPoint.y,this.control1.y,this.control2.y,this.endPoint.y);if(i>0){var h=s-t,a=r-e;o+=Math.sqrt(h*h+a*a)}t=s,e=r}return o},t.prototype.point=function(t,e,o,i,n){return e*(1-t)*(1-t)*(1-t)+3*o*(1-t)*(1-t)*t+3*i*(1-t)*t*t+n*t*t*t},t}();function throttle(t,e){void 0===e&&(e=250);var o,i,n,s=0,r=null,h=function(){s=Date.now(),r=null,o=t.apply(i,n),r||(i=null,n=[])};return function(){for(var a=[],c=0;c<arguments.length;c++)a[c]=arguments[c];var u=Date.now(),l=e-(u-s);return i=this,n=a,l<=0||l>e?(r&&(clearTimeout(r),r=null),s=u,o=t.apply(i,n),r||(i=null,n=[])):r||(r=setTimeout(h,l)),o}}var SignaturePad=function(){function t(e,o){void 0===o&&(o={});var i=this;this.canvas=e,this.options=o,this.velocityFilterWeight=o.velocityFilterWeight||.7,this.minWidth=o.minWidth||.5,this.maxWidth=o.maxWidth||2.5,this.throttle="throttle"in o?o.throttle:16,this.minDistance="minDistance"in o?o.minDistance:5,this.throttle?this._strokeMoveUpdate=throttle(t.prototype._strokeUpdate,this.throttle):this._strokeMoveUpdate=t.prototype._strokeUpdate,this.dotSize=o.dotSize||function(){return(this.minWidth+this.maxWidth)/2},this.penColor=o.penColor||"black",this.backgroundColor=o.backgroundColor||"rgba(0,0,0,0)",this.onBegin=o.onBegin,this.onEnd=o.onEnd,this._ctx=e.getContext("2d"),this.clear(),this._handleMouseDown=function(t){1===t.which&&(i._mouseButtonDown=!0,i._strokeBegin(t))},this._handleMouseMove=function(t){i._mouseButtonDown&&i._strokeMoveUpdate(t)},this._handleMouseUp=function(t){1===t.which&&i._mouseButtonDown&&(i._mouseButtonDown=!1,i._strokeEnd(t))},this._handleTouchStart=function(t){if(t.preventDefault(),1===t.targetTouches.length){var e=t.changedTouches[0];i._strokeBegin(e)}},this._handleTouchMove=function(t){t.preventDefault();var e=t.targetTouches[0];i._strokeMoveUpdate(e)},this._handleTouchEnd=function(t){if(t.target===i.canvas){t.preventDefault();var e=t.targetTouches[0];i._strokeEnd(e)}},this.on()}return t.prototype.clear=function(){var t=this._ctx,e=this.canvas;t.fillStyle=this.backgroundColor,t.clearRect(0,0,e.width,e.height),t.fillRect(0,0,e.width,e.height),this._data=[],this._reset(),this._isEmpty=!0},t.prototype.fromDataURL=function(t,e){var o=this;void 0===e&&(e={});var i=new Image,n=e.ratio||window.devicePixelRatio||1,s=e.width||this.canvas.width/n,r=e.height||this.canvas.height/n;this._reset(),i.src=t,i.onload=function(){o._ctx.drawImage(i,0,0,s,r)},this._isEmpty=!1},t.prototype.toDataURL=function(t,e){switch(t){case"image/svg+xml":return this._toSVG();default:return this.canvas.toDataURL(t,e)}},t.prototype.on=function(){this._handleMouseEvents(),this._handleTouchEvents()},t.prototype.off=function(){this.canvas.style.msTouchAction="auto",this.canvas.style.touchAction="auto",this.canvas.removeEventListener("mousedown",this._handleMouseDown),this.canvas.removeEventListener("mousemove",this._handleMouseMove),document.removeEventListener("mouseup",this._handleMouseUp),this.canvas.removeEventListener("touchstart",this._handleTouchStart),this.canvas.removeEventListener("touchmove",this._handleTouchMove),this.canvas.removeEventListener("touchend",this._handleTouchEnd)},t.prototype.isEmpty=function(){return this._isEmpty},t.prototype.fromData=function(t){var e=this;this.clear(),this._fromData(t,function(t){var o=t.color,i=t.curve;return e._drawCurve({color:o,curve:i})},function(t){var o=t.color,i=t.point;return e._drawDot({color:o,point:i})}),this._data=t},t.prototype.toData=function(){return this._data},t.prototype._strokeBegin=function(t){var e={color:this.penColor,points:[]};this._data.push(e),this._reset(),this._strokeUpdate(t),"function"==typeof this.onBegin&&this.onBegin(t)},t.prototype._strokeUpdate=function(t){var e=t.clientX,o=t.clientY,i=this._createPoint(e,o),n=this._data[this._data.length-1],s=n.points,r=s.length>0&&s[s.length-1],h=!!r&&i.distanceTo(r)<=this.minDistance,a=n.color;if(!r||!r||!h){var c=this._addPoint(i);r?c&&this._drawCurve({color:a,curve:c}):this._drawDot({color:a,point:i}),s.push({time:i.time,x:i.x,y:i.y})}},t.prototype._strokeEnd=function(t){this._strokeUpdate(t),"function"==typeof this.onEnd&&this.onEnd(t)},t.prototype._handleMouseEvents=function(){this._mouseButtonDown=!1,this.canvas.addEventListener("mousedown",this._handleMouseDown),this.canvas.addEventListener("mousemove",this._handleMouseMove),document.addEventListener("mouseup",this._handleMouseUp)},t.prototype._handleTouchEvents=function(){this.canvas.style.msTouchAction="none",this.canvas.style.touchAction="none",this.canvas.addEventListener("touchstart",this._handleTouchStart),this.canvas.addEventListener("touchmove",this._handleTouchMove),this.canvas.addEventListener("touchend",this._handleTouchEnd)},t.prototype._reset=function(){this._points=[],this._lastVelocity=0,this._lastWidth=(this.minWidth+this.maxWidth)/2,this._ctx.fillStyle=this.penColor},t.prototype._createPoint=function(t,e){var o=this.canvas.getBoundingClientRect();return new Point(t-o.left,e-o.top,(new Date).getTime())},t.prototype._addPoint=function(t){var e=this._points;if(e.push(t),e.length>2){3===e.length&&e.unshift(e[0]);var o=this._calculateCurveWidths(e[1],e[2]),i=Bezier.fromPoints(e,o);return e.shift(),i}return null},t.prototype._calculateCurveWidths=function(t,e){var o=this.velocityFilterWeight*e.velocityFrom(t)+(1-this.velocityFilterWeight)*this._lastVelocity,i=this._strokeWidth(o),n={end:i,start:this._lastWidth};return this._lastVelocity=o,this._lastWidth=i,n},t.prototype._strokeWidth=function(t){return Math.max(this.maxWidth/(t+1),this.minWidth)},t.prototype._drawCurveSegment=function(t,e,o){var i=this._ctx;i.moveTo(t,e),i.arc(t,e,o,0,2*Math.PI,!1),this._isEmpty=!1},t.prototype._drawCurve=function(t){var e=t.color,o=t.curve,i=this._ctx,n=o.endWidth-o.startWidth,s=2*Math.floor(o.length());i.beginPath(),i.fillStyle=e;for(var r=0;r<s;r+=1){var h=r/s,a=h*h,c=a*h,u=1-h,l=u*u,d=l*u,v=d*o.startPoint.x;v+=3*l*h*o.control1.x,v+=3*u*a*o.control2.x,v+=c*o.endPoint.x;var p=d*o.startPoint.y;p+=3*l*h*o.control1.y,p+=3*u*a*o.control2.y,p+=c*o.endPoint.y;var f=o.startWidth+c*n;this._drawCurveSegment(v,p,f)}i.closePath(),i.fill()},t.prototype._drawDot=function(t){var e=t.color,o=t.point,i=this._ctx,n="function"==typeof this.dotSize?this.dotSize():this.dotSize;i.beginPath(),this._drawCurveSegment(o.x,o.y,n),i.closePath(),i.fillStyle=e,i.fill()},t.prototype._fromData=function(t,e,o){for(var i=0,n=t;i<n.length;i++){var s=n[i],r=s.color,h=s.points;if(h.length>1)for(var a=0;a<h.length;a+=1){var c=h[a],u=new Point(c.x,c.y,c.time);this.penColor=r,0===a&&this._reset();var l=this._addPoint(u);l&&e({color:r,curve:l})}else this._reset(),o({color:r,point:h[0]})}},t.prototype._toSVG=function(){var t=this,e=this._data,o=Math.max(window.devicePixelRatio||1,1),i=this.canvas.width/o,n=this.canvas.height/o,s=document.createElementNS("http://www.w3.org/2000/svg","svg");s.setAttribute("width",this.canvas.width.toString()),s.setAttribute("height",this.canvas.height.toString()),this._fromData(e,function(t){var e=t.color,o=t.curve,i=document.createElement("path");if(!(isNaN(o.control1.x)||isNaN(o.control1.y)||isNaN(o.control2.x)||isNaN(o.control2.y))){var n="M "+o.startPoint.x.toFixed(3)+","+o.startPoint.y.toFixed(3)+" C "+o.control1.x.toFixed(3)+","+o.control1.y.toFixed(3)+" "+o.control2.x.toFixed(3)+","+o.control2.y.toFixed(3)+" "+o.endPoint.x.toFixed(3)+","+o.endPoint.y.toFixed(3);i.setAttribute("d",n),i.setAttribute("stroke-width",(2.25*o.endWidth).toFixed(3)),i.setAttribute("stroke",e),i.setAttribute("fill","none"),i.setAttribute("stroke-linecap","round"),s.appendChild(i)}},function(e){var o=e.color,i=e.point,n=document.createElement("circle"),r="function"==typeof t.dotSize?t.dotSize():t.dotSize;n.setAttribute("r",r.toString()),n.setAttribute("cx",i.x.toString()),n.setAttribute("cy",i.y.toString()),n.setAttribute("fill",o),s.appendChild(n)});var r='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 '+i+" "+n+'" width="'+i+'" height="'+n+'">',h=s.innerHTML;if(void 0===h){var a=document.createElement("dummy"),c=s.childNodes;a.innerHTML="";for(var u=0;u<c.length;u+=1)a.appendChild(c[u].cloneNode(!0));h=a.innerHTML}return"data:image/svg+xml;base64,"+btoa(r+h+"</svg>")},t}();module.exports=SignaturePad;
{
"name": "signature_pad",
"description": "Library for drawing smooth signatures.",
"version": "2.3.2",
"version": "3.0.0-beta.1",
"homepage": "https://github.com/szimek/signature_pad",

@@ -12,8 +12,12 @@ "author": {

"license": "MIT",
"main": "dist/signature_pad.js",
"module": "dist/signature_pad.mjs",
"source": "src/signature_pad.ts",
"dev:main": "dist/signature_pad.js",
"main": "dist/signature_pad.min.js",
"module": "dist/signature_pad.m.js",
"umd:main": "dist/signature_pad.umd.js",
"types": "dist/types/signature_pad.d.ts",
"scripts": {
"build": "gulp",
"watch": "gulp watch",
"prepublishOnly": "npm run build"
"build": "del dist && rollup --config && mv dist/src dist/types && cp dist/signature_pad.umd.js docs/js/",
"prepublishOnly": "yarn run build",
"test": "jest --coverage"
},

@@ -27,17 +31,28 @@ "repository": {

"dist",
"example"
"docs"
],
"devDependencies": {
"babel-plugin-transform-es2015-modules-umd": "^6.18.0",
"babel-preset-es2015": "^6.18.0",
"del": "^2.2.2",
"eslint": "^3.13.1",
"eslint-config-airbnb-base": "^11.0.1",
"eslint-plugin-import": "^2.2.0",
"gulp": "^3.9.1",
"rollup": "^0.41.4",
"rollup-plugin-babel": "^2.7.1",
"rollup-plugin-eslint": "^3.0.0",
"rollup-plugin-uglify": "^1.0.1"
"del": "^3.0.0",
"del-cli": "^1.1.0",
"rollup": "^0.56.5",
"rollup-plugin-tslint": "^0.1.34",
"rollup-plugin-typescript2": "^0.12.0",
"rollup-plugin-uglify": "^3.0.0",
"typescript": "^2.7.2",
"@types/jest": "22.2.0",
"jest": "22.4.2",
"ts-jest": "22.4.1"
},
"jest": {
"transform": {
"^.+\\.tsx?$": "ts-jest"
},
"testMatch": [
"<rootDir>/tests/**/*.ts"
],
"moduleFileExtensions": [
"ts",
"js"
]
}
}

@@ -12,4 +12,4 @@ # Signature Pad [![npm](https://badge.fury.io/js/signature_pad.svg)](https://www.npmjs.com/package/signature_pad) [![Code Climate](https://codeclimate.com/github/szimek/signature_pad.png)](https://codeclimate.com/github/szimek/signature_pad)

### Other demos
* Erase feature: https://jsfiddle.net/szimek/jq9cyzuc/
* Undo feature: https://jsfiddle.net/szimek/osenxvjc/
- Erase feature: <https://jsfiddle.net/szimek/jq9cyzuc/>
- Undo feature: <https://jsfiddle.net/szimek/osenxvjc/>

@@ -34,8 +34,2 @@ ## Installation

**NOTE** When importing this library in TypeScript, one needs to use the following syntax:
```js
import * as SignaturePad from 'signature_pad';
```
For more info why it's needed, check these 2 issues: [TypeScript#13017](https://github.com/Microsoft/TypeScript/issues/13017) and [rollup#1156](https://github.com/rollup/rollup/issues/1156).
## Usage

@@ -86,2 +80,4 @@ ### API

<dd>(integer) Draw the next point at most once per every <code>x</code> milliseconds. Set it to <code>0</code> to turn off throttling. Defaults to <code>16</code>.</dd>
<dt>minDistance</dt>
<dd>(integer) Add the next point only if the previous one is farther than <code>x</code> pixels. Defaults to <code>5</code>.
<dt>backgroundColor</dt>

@@ -88,0 +84,0 @@ <dd>(string) Color used to clear the background. Can be any color format accepted by <code>context.fillStyle</code>. Defaults to <code>"rgba(0,0,0,0)"</code> (transparent black). Use a non-transparent color e.g. <code>"rgb(255,255,255)"</code> (opaque white) if you'd like to save signatures as JPEG images.</dd>

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc