diff --git a/src/signature_pad.js b/src/signature_pad.js index 274de503..ccfff038 100644 --- a/src/signature_pad.js +++ b/src/signature_pad.js @@ -1,5 +1,6 @@ import Point from './point'; import Bezier from './bezier'; +import throttle from './throttle'; function SignaturePad(canvas, options) { const self = this; @@ -8,6 +9,14 @@ function SignaturePad(canvas, options) { this.velocityFilterWeight = opts.velocityFilterWeight || 0.7; this.minWidth = opts.minWidth || 0.5; this.maxWidth = opts.maxWidth || 2.5; + this.throttle = opts.throttle || 0; + + 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; }; @@ -31,7 +40,7 @@ function SignaturePad(canvas, options) { this._handleMouseMove = function (event) { if (self._mouseButtonDown) { - self._strokeUpdate(event); + self._strokeMoveUpdate(event); } }; @@ -54,7 +63,7 @@ function SignaturePad(canvas, options) { event.preventDefault(); const touch = event.targetTouches[0]; - self._strokeUpdate(touch); + self._strokeMoveUpdate(touch); }; this._handleTouchEnd = function (event) { diff --git a/src/throttle.js b/src/throttle.js new file mode 100644 index 00000000..a49aee86 --- /dev/null +++ b/src/throttle.js @@ -0,0 +1,34 @@ +/* eslint-disable */ + +// http://stackoverflow.com/a/27078401/815507 +export default function throttle(func, wait, options) { + var context, args, result; + var timeout = null; + var previous = 0; + if (!options) options = {}; + var later = function () { + 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); + 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; + }; +}