From 956450cae2b8706db96fe8ba10dae85f5c82979b Mon Sep 17 00:00:00 2001 From: Tony Brix Date: Thu, 17 Oct 2024 00:13:09 -0600 Subject: [PATCH] fix: prevent non-primary for pointer events (#796) --- docs/js/signature_pad.umd.min.js | 2 +- docs/js/signature_pad.umd.min.js.map | 2 +- src/signature_pad.ts | 7 ++- .../__snapshots__/signature_pad.test.ts.snap | 2 + tests/signature_pad.test.ts | 57 +++++++++++++++++++ 5 files changed, 66 insertions(+), 4 deletions(-) diff --git a/docs/js/signature_pad.umd.min.js b/docs/js/signature_pad.umd.min.js index 17bc1d51..5794790a 100644 --- a/docs/js/signature_pad.umd.min.js +++ b/docs/js/signature_pad.umd.min.js @@ -2,5 +2,5 @@ * Signature Pad v5.0.3 | https://github.com/szimek/signature_pad * (c) 2024 Szymon Nowak | Released under the MIT license */ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).SignaturePad=e()}(this,(function(){"use strict";class t{constructor(t,e,i,n){if(isNaN(t)||isNaN(e))throw new Error(`Point is invalid: (${t}, ${e})`);this.x=+t,this.y=+e,this.pressure=i||0,this.time=n||Date.now()}distanceTo(t){return Math.sqrt(Math.pow(this.x-t.x,2)+Math.pow(this.y-t.y,2))}equals(t){return this.x===t.x&&this.y===t.y&&this.pressure===t.pressure&&this.time===t.time}velocityFrom(t){return this.time!==t.time?this.distanceTo(t)/(this.time-t.time):0}}class e{static fromPoints(t,i){const n=this.calculateControlPoints(t[0],t[1],t[2]).c2,s=this.calculateControlPoints(t[1],t[2],t[3]).c1;return new e(t[1],n,s,t[2],i.start,i.end)}static calculateControlPoints(e,i,n){const s=e.x-i.x,o=e.y-i.y,r=i.x-n.x,h=i.y-n.y,a=(e.x+i.x)/2,c=(e.y+i.y)/2,d=(i.x+n.x)/2,l=(i.y+n.y)/2,u=Math.sqrt(s*s+o*o),v=Math.sqrt(r*r+h*h),_=u+v==0?0:v/(u+v),p=d+(a-d)*_,m=l+(c-l)*_,g=i.x-p,w=i.y-m;return{c1:new t(a+g,c+w),c2:new t(d+g,l+w)}}constructor(t,e,i,n,s,o){this.startPoint=t,this.control2=e,this.control1=i,this.endPoint=n,this.startWidth=s,this.endWidth=o}length(){let t,e,i=0;for(let n=0;n<=10;n+=1){const s=n/10,o=this.point(s,this.startPoint.x,this.control1.x,this.control2.x,this.endPoint.x),r=this.point(s,this.startPoint.y,this.control1.y,this.control2.y,this.endPoint.y);if(n>0){const n=o-t,s=r-e;i+=Math.sqrt(n*n+s*s)}t=o,e=r}return i}point(t,e,i,n,s){return e*(1-t)*(1-t)*(1-t)+3*i*(1-t)*(1-t)*t+3*n*(1-t)*t*t+s*t*t*t}}class i{constructor(){try{this._et=new EventTarget}catch(t){this._et=document}}addEventListener(t,e,i){this._et.addEventListener(t,e,i)}dispatchEvent(t){return this._et.dispatchEvent(t)}removeEventListener(t,e,i){this._et.removeEventListener(t,e,i)}}class n extends i{constructor(t,e={}){var i,s,o;super(),this.canvas=t,this._drawingStroke=!1,this._isEmpty=!0,this._lastPoints=[],this._data=[],this._lastVelocity=0,this._lastWidth=0,this._handleMouseDown=t=>{this._isLeftButtonPressed(t,!0)&&!this._drawingStroke&&this._strokeBegin(this._pointerEventToSignatureEvent(t))},this._handleMouseMove=t=>{this._isLeftButtonPressed(t,!0)&&this._drawingStroke?this._strokeMoveUpdate(this._pointerEventToSignatureEvent(t)):this._strokeEnd(this._pointerEventToSignatureEvent(t),!1)},this._handleMouseUp=t=>{this._isLeftButtonPressed(t)||this._strokeEnd(this._pointerEventToSignatureEvent(t))},this._handleTouchStart=t=>{1!==t.targetTouches.length||this._drawingStroke||(t.cancelable&&t.preventDefault(),this._strokeBegin(this._touchEventToSignatureEvent(t)))},this._handleTouchMove=t=>{1===t.targetTouches.length&&(t.cancelable&&t.preventDefault(),this._drawingStroke?this._strokeMoveUpdate(this._touchEventToSignatureEvent(t)):this._strokeEnd(this._touchEventToSignatureEvent(t),!1))},this._handleTouchEnd=t=>{0===t.targetTouches.length&&(t.cancelable&&t.preventDefault(),this.canvas.removeEventListener("touchmove",this._handleTouchMove),this._strokeEnd(this._touchEventToSignatureEvent(t)))},this._handlePointerDown=t=>{this._isLeftButtonPressed(t)&&!this._drawingStroke&&(t.preventDefault(),this._strokeBegin(this._pointerEventToSignatureEvent(t)))},this._handlePointerMove=t=>{this._isLeftButtonPressed(t,!0)&&this._drawingStroke?(t.preventDefault(),this._strokeMoveUpdate(this._pointerEventToSignatureEvent(t))):this._strokeEnd(this._pointerEventToSignatureEvent(t),!1)},this._handlePointerUp=t=>{this._isLeftButtonPressed(t)||(t.preventDefault(),this._strokeEnd(this._pointerEventToSignatureEvent(t)))},this.velocityFilterWeight=e.velocityFilterWeight||.7,this.minWidth=e.minWidth||.5,this.maxWidth=e.maxWidth||2.5,this.throttle=null!==(i=e.throttle)&&void 0!==i?i:16,this.minDistance=null!==(s=e.minDistance)&&void 0!==s?s:5,this.dotSize=e.dotSize||0,this.penColor=e.penColor||"black",this.backgroundColor=e.backgroundColor||"rgba(0,0,0,0)",this.compositeOperation=e.compositeOperation||"source-over",this.canvasContextOptions=null!==(o=e.canvasContextOptions)&&void 0!==o?o:{},this._strokeMoveUpdate=this.throttle?function(t,e=250){let i,n,s,o=0,r=null;const h=()=>{o=Date.now(),r=null,i=t.apply(n,s),r||(n=null,s=[])};return function(...a){const c=Date.now(),d=e-(c-o);return n=this,s=a,d<=0||d>e?(r&&(clearTimeout(r),r=null),o=c,i=t.apply(n,s),r||(n=null,s=[])):r||(r=window.setTimeout(h,d)),i}}(n.prototype._strokeUpdate,this.throttle):n.prototype._strokeUpdate,this._ctx=t.getContext("2d",this.canvasContextOptions),this.clear(),this.on()}clear(){const{_ctx:t,canvas:e}=this;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._getPointGroupOptions()),this._isEmpty=!0}fromDataURL(t,e={}){return new Promise(((i,n)=>{const s=new Image,o=e.ratio||window.devicePixelRatio||1,r=e.width||this.canvas.width/o,h=e.height||this.canvas.height/o,a=e.xOffset||0,c=e.yOffset||0;this._reset(this._getPointGroupOptions()),s.onload=()=>{this._ctx.drawImage(s,a,c,r,h),i()},s.onerror=t=>{n(t)},s.crossOrigin="anonymous",s.src=t,this._isEmpty=!1}))}toDataURL(t="image/png",e){return"image/svg+xml"===t?("object"!=typeof e&&(e=void 0),`data:image/svg+xml;base64,${btoa(this.toSVG(e))}`):("number"!=typeof e&&(e=void 0),this.canvas.toDataURL(t,e))}on(){this.canvas.style.touchAction="none",this.canvas.style.msTouchAction="none",this.canvas.style.userSelect="none";const t=/Macintosh/.test(navigator.userAgent)&&"ontouchstart"in document;window.PointerEvent&&!t?this._handlePointerEvents():(this._handleMouseEvents(),"ontouchstart"in window&&this._handleTouchEvents())}off(){this.canvas.style.touchAction="auto",this.canvas.style.msTouchAction="auto",this.canvas.style.userSelect="auto",this.canvas.removeEventListener("pointerdown",this._handlePointerDown),this.canvas.removeEventListener("mousedown",this._handleMouseDown),this.canvas.removeEventListener("touchstart",this._handleTouchStart),this._removeMoveUpEventListeners()}_getListenerFunctions(){var t;const e=window.document===this.canvas.ownerDocument?window:null!==(t=this.canvas.ownerDocument.defaultView)&&void 0!==t?t:this.canvas.ownerDocument;return{addEventListener:e.addEventListener.bind(e),removeEventListener:e.removeEventListener.bind(e)}}_removeMoveUpEventListeners(){const{removeEventListener:t}=this._getListenerFunctions();t("pointermove",this._handlePointerMove),t("pointerup",this._handlePointerUp),t("mousemove",this._handleMouseMove),t("mouseup",this._handleMouseUp),t("touchmove",this._handleTouchMove),t("touchend",this._handleTouchEnd)}isEmpty(){return this._isEmpty}fromData(t,{clear:e=!0}={}){e&&this.clear(),this._fromData(t,this._drawCurve.bind(this),this._drawDot.bind(this)),this._data=this._data.concat(t)}toData(){return this._data}_isLeftButtonPressed(t,e){return e?1===t.buttons:!(1&~t.buttons)}_pointerEventToSignatureEvent(t){return{event:t,type:t.type,x:t.clientX,y:t.clientY,pressure:"pressure"in t?t.pressure:0}}_touchEventToSignatureEvent(t){const e=t.changedTouches[0];return{event:t,type:t.type,x:e.clientX,y:e.clientY,pressure:e.force}}_getPointGroupOptions(t){return{penColor:t&&"penColor"in t?t.penColor:this.penColor,dotSize:t&&"dotSize"in t?t.dotSize:this.dotSize,minWidth:t&&"minWidth"in t?t.minWidth:this.minWidth,maxWidth:t&&"maxWidth"in t?t.maxWidth:this.maxWidth,velocityFilterWeight:t&&"velocityFilterWeight"in t?t.velocityFilterWeight:this.velocityFilterWeight,compositeOperation:t&&"compositeOperation"in t?t.compositeOperation:this.compositeOperation}}_strokeBegin(t){if(!this.dispatchEvent(new CustomEvent("beginStroke",{detail:t,cancelable:!0})))return;const{addEventListener:e}=this._getListenerFunctions();switch(t.event.type){case"mousedown":e("mousemove",this._handleMouseMove),e("mouseup",this._handleMouseUp);break;case"touchstart":e("touchmove",this._handleTouchMove),e("touchend",this._handleTouchEnd);break;case"pointerdown":e("pointermove",this._handlePointerMove),e("pointerup",this._handlePointerUp)}this._drawingStroke=!0;const i=this._getPointGroupOptions(),n=Object.assign(Object.assign({},i),{points:[]});this._data.push(n),this._reset(i),this._strokeUpdate(t)}_strokeUpdate(t){if(!this._drawingStroke)return;if(0===this._data.length)return void this._strokeBegin(t);this.dispatchEvent(new CustomEvent("beforeUpdateStroke",{detail:t}));const e=this._createPoint(t.x,t.y,t.pressure),i=this._data[this._data.length-1],n=i.points,s=n.length>0&&n[n.length-1],o=!!s&&e.distanceTo(s)<=this.minDistance,r=this._getPointGroupOptions(i);if(!s||!s||!o){const t=this._addPoint(e,r);s?t&&this._drawCurve(t,r):this._drawDot(e,r),n.push({time:e.time,x:e.x,y:e.y,pressure:e.pressure})}this.dispatchEvent(new CustomEvent("afterUpdateStroke",{detail:t}))}_strokeEnd(t,e=!0){this._removeMoveUpEventListeners(),this._drawingStroke&&(e&&this._strokeUpdate(t),this._drawingStroke=!1,this.dispatchEvent(new CustomEvent("endStroke",{detail:t})))}_handlePointerEvents(){this._drawingStroke=!1,this.canvas.addEventListener("pointerdown",this._handlePointerDown)}_handleMouseEvents(){this._drawingStroke=!1,this.canvas.addEventListener("mousedown",this._handleMouseDown)}_handleTouchEvents(){this.canvas.addEventListener("touchstart",this._handleTouchStart)}_reset(t){this._lastPoints=[],this._lastVelocity=0,this._lastWidth=(t.minWidth+t.maxWidth)/2,this._ctx.fillStyle=t.penColor,this._ctx.globalCompositeOperation=t.compositeOperation}_createPoint(e,i,n){const s=this.canvas.getBoundingClientRect();return new t(e-s.left,i-s.top,n,(new Date).getTime())}_addPoint(t,i){const{_lastPoints:n}=this;if(n.push(t),n.length>2){3===n.length&&n.unshift(n[0]);const t=this._calculateCurveWidths(n[1],n[2],i),s=e.fromPoints(n,t);return n.shift(),s}return null}_calculateCurveWidths(t,e,i){const n=i.velocityFilterWeight*e.velocityFrom(t)+(1-i.velocityFilterWeight)*this._lastVelocity,s=this._strokeWidth(n,i),o={end:s,start:this._lastWidth};return this._lastVelocity=n,this._lastWidth=s,o}_strokeWidth(t,e){return Math.max(e.maxWidth/(t+1),e.minWidth)}_drawCurveSegment(t,e,i){const n=this._ctx;n.moveTo(t,e),n.arc(t,e,i,0,2*Math.PI,!1),this._isEmpty=!1}_drawCurve(t,e){const i=this._ctx,n=t.endWidth-t.startWidth,s=2*Math.ceil(t.length());i.beginPath(),i.fillStyle=e.penColor;for(let i=0;i0?e.dotSize:(e.minWidth+e.maxWidth)/2;i.beginPath(),this._drawCurveSegment(t.x,t.y,n),i.closePath(),i.fillStyle=e.penColor,i.fill()}_fromData(e,i,n){for(const s of e){const{points:e}=s,o=this._getPointGroupOptions(s);if(e.length>1)for(let n=0;n{const i=document.createElement("path");if(!(isNaN(t.control1.x)||isNaN(t.control1.y)||isNaN(t.control2.x)||isNaN(t.control2.y))){const 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)}`;i.setAttribute("d",n),i.setAttribute("stroke-width",(2.25*t.endWidth).toFixed(3)),i.setAttribute("stroke",e),i.setAttribute("fill","none"),i.setAttribute("stroke-linecap","round"),o.appendChild(i)}}),((t,{penColor:e,dotSize:i,minWidth:n,maxWidth:s})=>{const r=document.createElement("circle"),h=i>0?i:(n+s)/2;r.setAttribute("r",h.toString()),r.setAttribute("cx",t.x.toString()),r.setAttribute("cy",t.y.toString()),r.setAttribute("fill",e),o.appendChild(r)})),o.outerHTML}}return n})); +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).SignaturePad=e()}(this,(function(){"use strict";class t{constructor(t,e,i,n){if(isNaN(t)||isNaN(e))throw new Error(`Point is invalid: (${t}, ${e})`);this.x=+t,this.y=+e,this.pressure=i||0,this.time=n||Date.now()}distanceTo(t){return Math.sqrt(Math.pow(this.x-t.x,2)+Math.pow(this.y-t.y,2))}equals(t){return this.x===t.x&&this.y===t.y&&this.pressure===t.pressure&&this.time===t.time}velocityFrom(t){return this.time!==t.time?this.distanceTo(t)/(this.time-t.time):0}}class e{static fromPoints(t,i){const n=this.calculateControlPoints(t[0],t[1],t[2]).c2,s=this.calculateControlPoints(t[1],t[2],t[3]).c1;return new e(t[1],n,s,t[2],i.start,i.end)}static calculateControlPoints(e,i,n){const s=e.x-i.x,o=e.y-i.y,r=i.x-n.x,h=i.y-n.y,a=(e.x+i.x)/2,c=(e.y+i.y)/2,d=(i.x+n.x)/2,l=(i.y+n.y)/2,u=Math.sqrt(s*s+o*o),v=Math.sqrt(r*r+h*h),_=u+v==0?0:v/(u+v),p=d+(a-d)*_,m=l+(c-l)*_,g=i.x-p,w=i.y-m;return{c1:new t(a+g,c+w),c2:new t(d+g,l+w)}}constructor(t,e,i,n,s,o){this.startPoint=t,this.control2=e,this.control1=i,this.endPoint=n,this.startWidth=s,this.endWidth=o}length(){let t,e,i=0;for(let n=0;n<=10;n+=1){const s=n/10,o=this.point(s,this.startPoint.x,this.control1.x,this.control2.x,this.endPoint.x),r=this.point(s,this.startPoint.y,this.control1.y,this.control2.y,this.endPoint.y);if(n>0){const n=o-t,s=r-e;i+=Math.sqrt(n*n+s*s)}t=o,e=r}return i}point(t,e,i,n,s){return e*(1-t)*(1-t)*(1-t)+3*i*(1-t)*(1-t)*t+3*n*(1-t)*t*t+s*t*t*t}}class i{constructor(){try{this._et=new EventTarget}catch(t){this._et=document}}addEventListener(t,e,i){this._et.addEventListener(t,e,i)}dispatchEvent(t){return this._et.dispatchEvent(t)}removeEventListener(t,e,i){this._et.removeEventListener(t,e,i)}}class n extends i{constructor(t,e={}){var i,s,o;super(),this.canvas=t,this._drawingStroke=!1,this._isEmpty=!0,this._lastPoints=[],this._data=[],this._lastVelocity=0,this._lastWidth=0,this._handleMouseDown=t=>{this._isLeftButtonPressed(t,!0)&&!this._drawingStroke&&this._strokeBegin(this._pointerEventToSignatureEvent(t))},this._handleMouseMove=t=>{this._isLeftButtonPressed(t,!0)&&this._drawingStroke?this._strokeMoveUpdate(this._pointerEventToSignatureEvent(t)):this._strokeEnd(this._pointerEventToSignatureEvent(t),!1)},this._handleMouseUp=t=>{this._isLeftButtonPressed(t)||this._strokeEnd(this._pointerEventToSignatureEvent(t))},this._handleTouchStart=t=>{1!==t.targetTouches.length||this._drawingStroke||(t.cancelable&&t.preventDefault(),this._strokeBegin(this._touchEventToSignatureEvent(t)))},this._handleTouchMove=t=>{1===t.targetTouches.length&&(t.cancelable&&t.preventDefault(),this._drawingStroke?this._strokeMoveUpdate(this._touchEventToSignatureEvent(t)):this._strokeEnd(this._touchEventToSignatureEvent(t),!1))},this._handleTouchEnd=t=>{0===t.targetTouches.length&&(t.cancelable&&t.preventDefault(),this.canvas.removeEventListener("touchmove",this._handleTouchMove),this._strokeEnd(this._touchEventToSignatureEvent(t)))},this._handlePointerDown=t=>{t.isPrimary&&this._isLeftButtonPressed(t)&&!this._drawingStroke&&(t.preventDefault(),this._strokeBegin(this._pointerEventToSignatureEvent(t)))},this._handlePointerMove=t=>{t.isPrimary&&(this._isLeftButtonPressed(t,!0)&&this._drawingStroke?(t.preventDefault(),this._strokeMoveUpdate(this._pointerEventToSignatureEvent(t))):this._strokeEnd(this._pointerEventToSignatureEvent(t),!1))},this._handlePointerUp=t=>{t.isPrimary&&!this._isLeftButtonPressed(t)&&(t.preventDefault(),this._strokeEnd(this._pointerEventToSignatureEvent(t)))},this.velocityFilterWeight=e.velocityFilterWeight||.7,this.minWidth=e.minWidth||.5,this.maxWidth=e.maxWidth||2.5,this.throttle=null!==(i=e.throttle)&&void 0!==i?i:16,this.minDistance=null!==(s=e.minDistance)&&void 0!==s?s:5,this.dotSize=e.dotSize||0,this.penColor=e.penColor||"black",this.backgroundColor=e.backgroundColor||"rgba(0,0,0,0)",this.compositeOperation=e.compositeOperation||"source-over",this.canvasContextOptions=null!==(o=e.canvasContextOptions)&&void 0!==o?o:{},this._strokeMoveUpdate=this.throttle?function(t,e=250){let i,n,s,o=0,r=null;const h=()=>{o=Date.now(),r=null,i=t.apply(n,s),r||(n=null,s=[])};return function(...a){const c=Date.now(),d=e-(c-o);return n=this,s=a,d<=0||d>e?(r&&(clearTimeout(r),r=null),o=c,i=t.apply(n,s),r||(n=null,s=[])):r||(r=window.setTimeout(h,d)),i}}(n.prototype._strokeUpdate,this.throttle):n.prototype._strokeUpdate,this._ctx=t.getContext("2d",this.canvasContextOptions),this.clear(),this.on()}clear(){const{_ctx:t,canvas:e}=this;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._getPointGroupOptions()),this._isEmpty=!0}fromDataURL(t,e={}){return new Promise(((i,n)=>{const s=new Image,o=e.ratio||window.devicePixelRatio||1,r=e.width||this.canvas.width/o,h=e.height||this.canvas.height/o,a=e.xOffset||0,c=e.yOffset||0;this._reset(this._getPointGroupOptions()),s.onload=()=>{this._ctx.drawImage(s,a,c,r,h),i()},s.onerror=t=>{n(t)},s.crossOrigin="anonymous",s.src=t,this._isEmpty=!1}))}toDataURL(t="image/png",e){return"image/svg+xml"===t?("object"!=typeof e&&(e=void 0),`data:image/svg+xml;base64,${btoa(this.toSVG(e))}`):("number"!=typeof e&&(e=void 0),this.canvas.toDataURL(t,e))}on(){this.canvas.style.touchAction="none",this.canvas.style.msTouchAction="none",this.canvas.style.userSelect="none";const t=/Macintosh/.test(navigator.userAgent)&&"ontouchstart"in document;window.PointerEvent&&!t?this._handlePointerEvents():(this._handleMouseEvents(),"ontouchstart"in window&&this._handleTouchEvents())}off(){this.canvas.style.touchAction="auto",this.canvas.style.msTouchAction="auto",this.canvas.style.userSelect="auto",this.canvas.removeEventListener("pointerdown",this._handlePointerDown),this.canvas.removeEventListener("mousedown",this._handleMouseDown),this.canvas.removeEventListener("touchstart",this._handleTouchStart),this._removeMoveUpEventListeners()}_getListenerFunctions(){var t;const e=window.document===this.canvas.ownerDocument?window:null!==(t=this.canvas.ownerDocument.defaultView)&&void 0!==t?t:this.canvas.ownerDocument;return{addEventListener:e.addEventListener.bind(e),removeEventListener:e.removeEventListener.bind(e)}}_removeMoveUpEventListeners(){const{removeEventListener:t}=this._getListenerFunctions();t("pointermove",this._handlePointerMove),t("pointerup",this._handlePointerUp),t("mousemove",this._handleMouseMove),t("mouseup",this._handleMouseUp),t("touchmove",this._handleTouchMove),t("touchend",this._handleTouchEnd)}isEmpty(){return this._isEmpty}fromData(t,{clear:e=!0}={}){e&&this.clear(),this._fromData(t,this._drawCurve.bind(this),this._drawDot.bind(this)),this._data=this._data.concat(t)}toData(){return this._data}_isLeftButtonPressed(t,e){return e?1===t.buttons:!(1&~t.buttons)}_pointerEventToSignatureEvent(t){return{event:t,type:t.type,x:t.clientX,y:t.clientY,pressure:"pressure"in t?t.pressure:0}}_touchEventToSignatureEvent(t){const e=t.changedTouches[0];return{event:t,type:t.type,x:e.clientX,y:e.clientY,pressure:e.force}}_getPointGroupOptions(t){return{penColor:t&&"penColor"in t?t.penColor:this.penColor,dotSize:t&&"dotSize"in t?t.dotSize:this.dotSize,minWidth:t&&"minWidth"in t?t.minWidth:this.minWidth,maxWidth:t&&"maxWidth"in t?t.maxWidth:this.maxWidth,velocityFilterWeight:t&&"velocityFilterWeight"in t?t.velocityFilterWeight:this.velocityFilterWeight,compositeOperation:t&&"compositeOperation"in t?t.compositeOperation:this.compositeOperation}}_strokeBegin(t){if(!this.dispatchEvent(new CustomEvent("beginStroke",{detail:t,cancelable:!0})))return;const{addEventListener:e}=this._getListenerFunctions();switch(t.event.type){case"mousedown":e("mousemove",this._handleMouseMove),e("mouseup",this._handleMouseUp);break;case"touchstart":e("touchmove",this._handleTouchMove),e("touchend",this._handleTouchEnd);break;case"pointerdown":e("pointermove",this._handlePointerMove),e("pointerup",this._handlePointerUp)}this._drawingStroke=!0;const i=this._getPointGroupOptions(),n=Object.assign(Object.assign({},i),{points:[]});this._data.push(n),this._reset(i),this._strokeUpdate(t)}_strokeUpdate(t){if(!this._drawingStroke)return;if(0===this._data.length)return void this._strokeBegin(t);this.dispatchEvent(new CustomEvent("beforeUpdateStroke",{detail:t}));const e=this._createPoint(t.x,t.y,t.pressure),i=this._data[this._data.length-1],n=i.points,s=n.length>0&&n[n.length-1],o=!!s&&e.distanceTo(s)<=this.minDistance,r=this._getPointGroupOptions(i);if(!s||!s||!o){const t=this._addPoint(e,r);s?t&&this._drawCurve(t,r):this._drawDot(e,r),n.push({time:e.time,x:e.x,y:e.y,pressure:e.pressure})}this.dispatchEvent(new CustomEvent("afterUpdateStroke",{detail:t}))}_strokeEnd(t,e=!0){this._removeMoveUpEventListeners(),this._drawingStroke&&(e&&this._strokeUpdate(t),this._drawingStroke=!1,this.dispatchEvent(new CustomEvent("endStroke",{detail:t})))}_handlePointerEvents(){this._drawingStroke=!1,this.canvas.addEventListener("pointerdown",this._handlePointerDown)}_handleMouseEvents(){this._drawingStroke=!1,this.canvas.addEventListener("mousedown",this._handleMouseDown)}_handleTouchEvents(){this.canvas.addEventListener("touchstart",this._handleTouchStart)}_reset(t){this._lastPoints=[],this._lastVelocity=0,this._lastWidth=(t.minWidth+t.maxWidth)/2,this._ctx.fillStyle=t.penColor,this._ctx.globalCompositeOperation=t.compositeOperation}_createPoint(e,i,n){const s=this.canvas.getBoundingClientRect();return new t(e-s.left,i-s.top,n,(new Date).getTime())}_addPoint(t,i){const{_lastPoints:n}=this;if(n.push(t),n.length>2){3===n.length&&n.unshift(n[0]);const t=this._calculateCurveWidths(n[1],n[2],i),s=e.fromPoints(n,t);return n.shift(),s}return null}_calculateCurveWidths(t,e,i){const n=i.velocityFilterWeight*e.velocityFrom(t)+(1-i.velocityFilterWeight)*this._lastVelocity,s=this._strokeWidth(n,i),o={end:s,start:this._lastWidth};return this._lastVelocity=n,this._lastWidth=s,o}_strokeWidth(t,e){return Math.max(e.maxWidth/(t+1),e.minWidth)}_drawCurveSegment(t,e,i){const n=this._ctx;n.moveTo(t,e),n.arc(t,e,i,0,2*Math.PI,!1),this._isEmpty=!1}_drawCurve(t,e){const i=this._ctx,n=t.endWidth-t.startWidth,s=2*Math.ceil(t.length());i.beginPath(),i.fillStyle=e.penColor;for(let i=0;i0?e.dotSize:(e.minWidth+e.maxWidth)/2;i.beginPath(),this._drawCurveSegment(t.x,t.y,n),i.closePath(),i.fillStyle=e.penColor,i.fill()}_fromData(e,i,n){for(const s of e){const{points:e}=s,o=this._getPointGroupOptions(s);if(e.length>1)for(let n=0;n{const i=document.createElement("path");if(!(isNaN(t.control1.x)||isNaN(t.control1.y)||isNaN(t.control2.x)||isNaN(t.control2.y))){const 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)}`;i.setAttribute("d",n),i.setAttribute("stroke-width",(2.25*t.endWidth).toFixed(3)),i.setAttribute("stroke",e),i.setAttribute("fill","none"),i.setAttribute("stroke-linecap","round"),o.appendChild(i)}}),((t,{penColor:e,dotSize:i,minWidth:n,maxWidth:s})=>{const r=document.createElement("circle"),h=i>0?i:(n+s)/2;r.setAttribute("r",h.toString()),r.setAttribute("cx",t.x.toString()),r.setAttribute("cy",t.y.toString()),r.setAttribute("fill",e),o.appendChild(r)})),o.outerHTML}}return n})); //# sourceMappingURL=signature_pad.umd.min.js.map diff --git a/docs/js/signature_pad.umd.min.js.map b/docs/js/signature_pad.umd.min.js.map index cb0b736f..cff16035 100644 --- a/docs/js/signature_pad.umd.min.js.map +++ b/docs/js/signature_pad.umd.min.js.map @@ -1 +1 @@ -{"version":3,"file":"signature_pad.umd.min.js","sources":["../src/point.ts","../src/bezier.ts","../src/signature_event_target.ts","../src/signature_pad.ts","../src/throttle.ts"],"sourcesContent":["// Interface for point data structure used e.g. in SignaturePad#fromData method\nexport interface BasicPoint {\n x: number;\n y: number;\n pressure: number;\n time: number;\n}\n\nexport class Point implements BasicPoint {\n public x: number;\n public y: number;\n public pressure: number;\n public time: number;\n\n constructor(x: number, y: number, pressure?: number, time?: number) {\n if (isNaN(x) || isNaN(y)) {\n throw new Error(`Point is invalid: (${x}, ${y})`);\n }\n this.x = +x;\n this.y = +y;\n this.pressure = pressure || 0;\n this.time = time || Date.now();\n }\n\n public distanceTo(start: BasicPoint): number {\n return Math.sqrt(\n Math.pow(this.x - start.x, 2) + Math.pow(this.y - start.y, 2),\n );\n }\n\n public equals(other: BasicPoint): boolean {\n return (\n this.x === other.x &&\n this.y === other.y &&\n this.pressure === other.pressure &&\n this.time === other.time\n );\n }\n\n public velocityFrom(start: BasicPoint): number {\n return this.time !== start.time\n ? this.distanceTo(start) / (this.time - start.time)\n : 0;\n }\n}\n","import { BasicPoint, Point } from './point';\n\nexport class Bezier {\n public static fromPoints(\n points: Point[],\n widths: { start: number; end: number },\n ): Bezier {\n const c2 = this.calculateControlPoints(points[0], points[1], points[2]).c2;\n const c3 = this.calculateControlPoints(points[1], points[2], points[3]).c1;\n\n return new Bezier(points[1], c2, c3, points[2], widths.start, widths.end);\n }\n\n private static calculateControlPoints(\n s1: BasicPoint,\n s2: BasicPoint,\n s3: BasicPoint,\n ): {\n c1: BasicPoint;\n c2: BasicPoint;\n } {\n const dx1 = s1.x - s2.x;\n const dy1 = s1.y - s2.y;\n const dx2 = s2.x - s3.x;\n const dy2 = s2.y - s3.y;\n\n const m1 = { x: (s1.x + s2.x) / 2.0, y: (s1.y + s2.y) / 2.0 };\n const m2 = { x: (s2.x + s3.x) / 2.0, y: (s2.y + s3.y) / 2.0 };\n\n const l1 = Math.sqrt(dx1 * dx1 + dy1 * dy1);\n const l2 = Math.sqrt(dx2 * dx2 + dy2 * dy2);\n\n const dxm = m1.x - m2.x;\n const dym = m1.y - m2.y;\n\n const k = l1 + l2 == 0 ? 0 : l2 / (l1 + l2);\n const cm = { x: m2.x + dxm * k, y: m2.y + dym * k };\n\n const tx = s2.x - cm.x;\n const ty = s2.y - cm.y;\n\n return {\n c1: new Point(m1.x + tx, m1.y + ty),\n c2: new Point(m2.x + tx, m2.y + ty),\n };\n }\n\n constructor(\n public startPoint: Point,\n public control2: BasicPoint,\n public control1: BasicPoint,\n public endPoint: Point,\n public startWidth: number,\n public endWidth: number,\n ) {}\n\n // Returns approximated length. Code taken from https://www.lemoda.net/maths/bezier-length/index.html.\n public length(): number {\n const steps = 10;\n let length = 0;\n let px;\n let py;\n\n for (let i = 0; i <= steps; i += 1) {\n const t = i / steps;\n const cx = this.point(\n t,\n this.startPoint.x,\n this.control1.x,\n this.control2.x,\n this.endPoint.x,\n );\n const cy = this.point(\n t,\n this.startPoint.y,\n this.control1.y,\n this.control2.y,\n this.endPoint.y,\n );\n\n if (i > 0) {\n const xdiff = cx - (px as number);\n const ydiff = cy - (py as number);\n\n length += Math.sqrt(xdiff * xdiff + ydiff * ydiff);\n }\n\n px = cx;\n py = cy;\n }\n\n return length;\n }\n\n // Calculate parametric value of x or y given t and the four point coordinates of a cubic bezier curve.\n private point(\n t: number,\n start: number,\n c1: number,\n c2: number,\n end: number,\n ): number {\n // prettier-ignore\n return ( start * (1.0 - t) * (1.0 - t) * (1.0 - t))\n + (3.0 * c1 * (1.0 - t) * (1.0 - t) * t)\n + (3.0 * c2 * (1.0 - t) * t * t)\n + ( end * t * t * t);\n }\n}\n","export class SignatureEventTarget {\n /* tslint:disable: variable-name */\n private _et: EventTarget;\n /* tslint:enable: variable-name */\n\n constructor() {\n try {\n this._et = new EventTarget();\n } catch {\n // Using document as EventTarget to support iOS 13 and older.\n // Because EventTarget constructor just exists at iOS 14 and later.\n this._et = document;\n }\n }\n\n addEventListener(\n type: string,\n listener: EventListenerOrEventListenerObject | null,\n options?: boolean | AddEventListenerOptions,\n ): void {\n this._et.addEventListener(type, listener, options);\n }\n\n dispatchEvent(event: Event): boolean {\n return this._et.dispatchEvent(event);\n }\n\n removeEventListener(\n type: string,\n callback: EventListenerOrEventListenerObject | null,\n options?: boolean | EventListenerOptions,\n ): void {\n this._et.removeEventListener(type, callback, options);\n }\n}\n","/**\n * The main idea and some parts of the code (e.g. drawing variable width Bézier curve) are taken from:\n * http://corner.squareup.com/2012/07/smoother-signatures.html\n *\n * Implementation of interpolation using cubic Bézier curves is taken from:\n * https://web.archive.org/web/20160323213433/http://www.benknowscode.com/2012/09/path-interpolation-using-cubic-bezier_9742.html\n *\n * Algorithm for approximated length of a Bézier curve is taken from:\n * http://www.lemoda.net/maths/bezier-length/index.html\n */\n\nimport { Bezier } from './bezier';\nimport { BasicPoint, Point } from './point';\nimport { SignatureEventTarget } from './signature_event_target';\nimport { throttle } from './throttle';\n\nexport interface SignatureEvent {\n event: MouseEvent | TouchEvent | PointerEvent;\n type: string;\n x: number;\n y: number;\n pressure: number;\n}\n\nexport interface FromDataOptions {\n clear?: boolean;\n}\n\nexport interface ToSVGOptions {\n includeBackgroundColor?: boolean;\n}\n\nexport interface PointGroupOptions {\n dotSize: number;\n minWidth: number;\n maxWidth: number;\n penColor: string;\n velocityFilterWeight: number;\n /**\n * This is the globalCompositeOperation for the line.\n * *default: 'source-over'*\n * @see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation\n */\n compositeOperation: GlobalCompositeOperation;\n}\n\nexport interface Options extends Partial {\n minDistance?: number;\n backgroundColor?: string;\n throttle?: number;\n canvasContextOptions?: CanvasRenderingContext2DSettings;\n}\n\nexport interface PointGroup extends PointGroupOptions {\n points: BasicPoint[];\n}\n\nexport default class SignaturePad extends SignatureEventTarget {\n // Public stuff\n public dotSize: number;\n public minWidth: number;\n public maxWidth: number;\n public penColor: string;\n public minDistance: number;\n public velocityFilterWeight: number;\n public compositeOperation: GlobalCompositeOperation;\n public backgroundColor: string;\n public throttle: number;\n public canvasContextOptions: CanvasRenderingContext2DSettings;\n\n // Private stuff\n /* tslint:disable: variable-name */\n private _ctx: CanvasRenderingContext2D;\n private _drawingStroke = false;\n private _isEmpty = true;\n private _lastPoints: Point[] = []; // Stores up to 4 most recent points; used to generate a new curve\n private _data: PointGroup[] = []; // Stores all points in groups (one group per line or dot)\n private _lastVelocity = 0;\n private _lastWidth = 0;\n private _strokeMoveUpdate: (event: SignatureEvent) => void;\n /* tslint:enable: variable-name */\n\n constructor(\n private canvas: HTMLCanvasElement,\n options: Options = {},\n ) {\n super();\n this.velocityFilterWeight = options.velocityFilterWeight || 0.7;\n this.minWidth = options.minWidth || 0.5;\n this.maxWidth = options.maxWidth || 2.5;\n\n // We need to handle 0 value, so use `??` instead of `||`\n this.throttle = options.throttle ?? 16; // in milliseconds\n this.minDistance = options.minDistance ?? 5; // in pixels\n this.dotSize = options.dotSize || 0;\n this.penColor = options.penColor || 'black';\n this.backgroundColor = options.backgroundColor || 'rgba(0,0,0,0)';\n this.compositeOperation = options.compositeOperation || 'source-over';\n this.canvasContextOptions = options.canvasContextOptions ?? {};\n\n this._strokeMoveUpdate = this.throttle\n ? throttle(SignaturePad.prototype._strokeUpdate, this.throttle)\n : SignaturePad.prototype._strokeUpdate;\n this._ctx = canvas.getContext(\n '2d',\n this.canvasContextOptions,\n ) as CanvasRenderingContext2D;\n\n this.clear();\n\n // Enable mouse and touch event handlers\n this.on();\n }\n\n public clear(): void {\n const { _ctx: ctx, canvas } = this;\n\n // Clear canvas using background color\n ctx.fillStyle = this.backgroundColor;\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n ctx.fillRect(0, 0, canvas.width, canvas.height);\n\n this._data = [];\n this._reset(this._getPointGroupOptions());\n this._isEmpty = true;\n }\n\n public fromDataURL(\n dataUrl: string,\n options: {\n ratio?: number;\n width?: number;\n height?: number;\n xOffset?: number;\n yOffset?: number;\n } = {},\n ): Promise {\n return new Promise((resolve, reject) => {\n const image = new Image();\n const ratio = options.ratio || window.devicePixelRatio || 1;\n const width = options.width || this.canvas.width / ratio;\n const height = options.height || this.canvas.height / ratio;\n const xOffset = options.xOffset || 0;\n const yOffset = options.yOffset || 0;\n\n this._reset(this._getPointGroupOptions());\n\n image.onload = (): void => {\n this._ctx.drawImage(image, xOffset, yOffset, width, height);\n resolve();\n };\n image.onerror = (error): void => {\n reject(error);\n };\n image.crossOrigin = 'anonymous';\n image.src = dataUrl;\n\n this._isEmpty = false;\n });\n }\n\n public toDataURL(\n type: 'image/svg+xml',\n encoderOptions?: ToSVGOptions,\n ): string;\n public toDataURL(type?: string, encoderOptions?: number): string;\n public toDataURL(\n type = 'image/png',\n encoderOptions?: number | ToSVGOptions | undefined,\n ): string {\n switch (type) {\n case 'image/svg+xml':\n if (typeof encoderOptions !== 'object') {\n encoderOptions = undefined;\n }\n return `data:image/svg+xml;base64,${btoa(\n this.toSVG(encoderOptions as ToSVGOptions),\n )}`;\n default:\n if (typeof encoderOptions !== 'number') {\n encoderOptions = undefined;\n }\n return this.canvas.toDataURL(type, encoderOptions);\n }\n }\n\n public on(): void {\n // Disable panning/zooming when touching canvas element\n this.canvas.style.touchAction = 'none';\n (this.canvas.style as CSSStyleDeclaration & { msTouchAction: string | null }).msTouchAction = 'none';\n this.canvas.style.userSelect = 'none';\n\n const isIOS =\n /Macintosh/.test(navigator.userAgent) && 'ontouchstart' in document;\n\n // The \"Scribble\" feature of iOS intercepts point events. So that we can\n // lose some of them when tapping rapidly. Use touch events for iOS\n // platforms to prevent it. See\n // https://developer.apple.com/forums/thread/664108 for more information.\n if (window.PointerEvent && !isIOS) {\n this._handlePointerEvents();\n } else {\n this._handleMouseEvents();\n\n if ('ontouchstart' in window) {\n this._handleTouchEvents();\n }\n }\n }\n\n public off(): void {\n // Enable panning/zooming when touching canvas element\n this.canvas.style.touchAction = 'auto';\n (this.canvas.style as CSSStyleDeclaration & { msTouchAction: string | null }).msTouchAction = 'auto';\n this.canvas.style.userSelect = 'auto';\n\n this.canvas.removeEventListener('pointerdown', this._handlePointerDown);\n this.canvas.removeEventListener('mousedown', this._handleMouseDown);\n this.canvas.removeEventListener('touchstart', this._handleTouchStart);\n\n this._removeMoveUpEventListeners();\n }\n\n private _getListenerFunctions() {\n const canvasWindow =\n window.document === this.canvas.ownerDocument\n ? window\n : this.canvas.ownerDocument.defaultView ?? this.canvas.ownerDocument;\n\n return {\n addEventListener: canvasWindow.addEventListener.bind(\n canvasWindow,\n ) as typeof window.addEventListener,\n removeEventListener: canvasWindow.removeEventListener.bind(\n canvasWindow,\n ) as typeof window.removeEventListener,\n };\n }\n\n private _removeMoveUpEventListeners(): void {\n const { removeEventListener } = this._getListenerFunctions();\n removeEventListener('pointermove', this._handlePointerMove);\n removeEventListener('pointerup', this._handlePointerUp);\n\n removeEventListener('mousemove', this._handleMouseMove);\n removeEventListener('mouseup', this._handleMouseUp);\n\n removeEventListener('touchmove', this._handleTouchMove);\n removeEventListener('touchend', this._handleTouchEnd);\n }\n\n public isEmpty(): boolean {\n return this._isEmpty;\n }\n\n public fromData(\n pointGroups: PointGroup[],\n { clear = true }: FromDataOptions = {},\n ): void {\n if (clear) {\n this.clear();\n }\n\n this._fromData(\n pointGroups,\n this._drawCurve.bind(this),\n this._drawDot.bind(this),\n );\n\n this._data = this._data.concat(pointGroups);\n }\n\n public toData(): PointGroup[] {\n return this._data;\n }\n\n public _isLeftButtonPressed(event: MouseEvent, only?: boolean): boolean {\n if (only) {\n return event.buttons === 1;\n }\n\n return (event.buttons & 1) === 1;\n }\n private _pointerEventToSignatureEvent(\n event: MouseEvent | PointerEvent,\n ): SignatureEvent {\n return {\n event: event,\n type: event.type,\n x: event.clientX,\n y: event.clientY,\n pressure: 'pressure' in event ? event.pressure : 0,\n };\n }\n\n private _touchEventToSignatureEvent(event: TouchEvent): SignatureEvent {\n const touch = event.changedTouches[0];\n return {\n event: event,\n type: event.type,\n x: touch.clientX,\n y: touch.clientY,\n pressure: touch.force,\n };\n }\n\n // Event handlers\n private _handleMouseDown = (event: MouseEvent): void => {\n if (!this._isLeftButtonPressed(event, true) || this._drawingStroke) {\n return;\n }\n this._strokeBegin(this._pointerEventToSignatureEvent(event));\n };\n\n private _handleMouseMove = (event: MouseEvent): void => {\n if (!this._isLeftButtonPressed(event, true) || !this._drawingStroke) {\n // Stop when not pressing primary button or pressing multiple buttons\n this._strokeEnd(this._pointerEventToSignatureEvent(event), false);\n return;\n }\n\n this._strokeMoveUpdate(this._pointerEventToSignatureEvent(event));\n };\n\n private _handleMouseUp = (event: MouseEvent): void => {\n if (this._isLeftButtonPressed(event)) {\n return;\n }\n\n this._strokeEnd(this._pointerEventToSignatureEvent(event));\n };\n\n private _handleTouchStart = (event: TouchEvent): void => {\n if (event.targetTouches.length !== 1 || this._drawingStroke) {\n return;\n }\n\n // Prevent scrolling.\n if (event.cancelable) {\n event.preventDefault();\n }\n\n this._strokeBegin(this._touchEventToSignatureEvent(event));\n };\n\n private _handleTouchMove = (event: TouchEvent): void => {\n if (event.targetTouches.length !== 1) {\n return;\n }\n\n // Prevent scrolling.\n if (event.cancelable) {\n event.preventDefault();\n }\n\n if (!this._drawingStroke) {\n this._strokeEnd(this._touchEventToSignatureEvent(event), false);\n return;\n }\n\n this._strokeMoveUpdate(this._touchEventToSignatureEvent(event));\n };\n\n private _handleTouchEnd = (event: TouchEvent): void => {\n if (event.targetTouches.length !== 0) {\n return;\n }\n\n if (event.cancelable) {\n event.preventDefault();\n }\n\n this.canvas.removeEventListener('touchmove', this._handleTouchMove);\n\n this._strokeEnd(this._touchEventToSignatureEvent(event));\n };\n\n private _handlePointerDown = (event: PointerEvent): void => {\n if (!this._isLeftButtonPressed(event) || this._drawingStroke) {\n return;\n }\n\n event.preventDefault();\n\n this._strokeBegin(this._pointerEventToSignatureEvent(event));\n };\n\n private _handlePointerMove = (event: PointerEvent): void => {\n if (!this._isLeftButtonPressed(event, true) || !this._drawingStroke) {\n // Stop when primary button not pressed or multiple buttons pressed\n this._strokeEnd(this._pointerEventToSignatureEvent(event), false);\n return;\n }\n\n event.preventDefault();\n this._strokeMoveUpdate(this._pointerEventToSignatureEvent(event));\n };\n\n private _handlePointerUp = (event: PointerEvent): void => {\n if (this._isLeftButtonPressed(event)) {\n return;\n }\n\n event.preventDefault();\n this._strokeEnd(this._pointerEventToSignatureEvent(event));\n };\n\n private _getPointGroupOptions(group?: PointGroup): PointGroupOptions {\n return {\n penColor: group && 'penColor' in group ? group.penColor : this.penColor,\n dotSize: group && 'dotSize' in group ? group.dotSize : this.dotSize,\n minWidth: group && 'minWidth' in group ? group.minWidth : this.minWidth,\n maxWidth: group && 'maxWidth' in group ? group.maxWidth : this.maxWidth,\n velocityFilterWeight:\n group && 'velocityFilterWeight' in group\n ? group.velocityFilterWeight\n : this.velocityFilterWeight,\n compositeOperation:\n group && 'compositeOperation' in group\n ? group.compositeOperation\n : this.compositeOperation,\n };\n }\n\n // Private methods\n private _strokeBegin(event: SignatureEvent): void {\n const cancelled = !this.dispatchEvent(\n new CustomEvent('beginStroke', { detail: event, cancelable: true }),\n );\n if (cancelled) {\n return;\n }\n\n const { addEventListener } = this._getListenerFunctions();\n switch (event.event.type) {\n case 'mousedown':\n addEventListener('mousemove', this._handleMouseMove);\n addEventListener('mouseup', this._handleMouseUp);\n break;\n case 'touchstart':\n addEventListener('touchmove', this._handleTouchMove);\n addEventListener('touchend', this._handleTouchEnd);\n break;\n case 'pointerdown':\n addEventListener('pointermove', this._handlePointerMove);\n addEventListener('pointerup', this._handlePointerUp);\n break;\n default:\n // do nothing\n }\n\n this._drawingStroke = true;\n\n const pointGroupOptions = this._getPointGroupOptions();\n\n const newPointGroup: PointGroup = {\n ...pointGroupOptions,\n points: [],\n };\n\n this._data.push(newPointGroup);\n this._reset(pointGroupOptions);\n this._strokeUpdate(event);\n }\n\n private _strokeUpdate(event: SignatureEvent): void {\n if (!this._drawingStroke) {\n return;\n }\n\n if (this._data.length === 0) {\n // This can happen if clear() was called while a signature is still in progress,\n // or if there is a race condition between start/update events.\n this._strokeBegin(event);\n return;\n }\n\n this.dispatchEvent(\n new CustomEvent('beforeUpdateStroke', { detail: event }),\n );\n\n const point = this._createPoint(event.x, event.y, event.pressure);\n const lastPointGroup = this._data[this._data.length - 1];\n const lastPoints = lastPointGroup.points;\n const lastPoint =\n lastPoints.length > 0 && lastPoints[lastPoints.length - 1];\n const isLastPointTooClose = lastPoint\n ? point.distanceTo(lastPoint) <= this.minDistance\n : false;\n const pointGroupOptions = this._getPointGroupOptions(lastPointGroup);\n\n // Skip this point if it's too close to the previous one\n if (!lastPoint || !(lastPoint && isLastPointTooClose)) {\n const curve = this._addPoint(point, pointGroupOptions);\n\n if (!lastPoint) {\n this._drawDot(point, pointGroupOptions);\n } else if (curve) {\n this._drawCurve(curve, pointGroupOptions);\n }\n\n lastPoints.push({\n time: point.time,\n x: point.x,\n y: point.y,\n pressure: point.pressure,\n });\n }\n\n this.dispatchEvent(new CustomEvent('afterUpdateStroke', { detail: event }));\n }\n\n private _strokeEnd(event: SignatureEvent, shouldUpdate = true): void {\n this._removeMoveUpEventListeners();\n\n if (!this._drawingStroke) {\n return;\n }\n\n if (shouldUpdate) {\n this._strokeUpdate(event);\n }\n\n this._drawingStroke = false;\n this.dispatchEvent(new CustomEvent('endStroke', { detail: event }));\n }\n\n private _handlePointerEvents(): void {\n this._drawingStroke = false;\n\n this.canvas.addEventListener('pointerdown', this._handlePointerDown);\n }\n\n private _handleMouseEvents(): void {\n this._drawingStroke = false;\n\n this.canvas.addEventListener('mousedown', this._handleMouseDown);\n }\n\n private _handleTouchEvents(): void {\n this.canvas.addEventListener('touchstart', this._handleTouchStart);\n }\n\n // Called when a new line is started\n private _reset(options: PointGroupOptions): void {\n this._lastPoints = [];\n this._lastVelocity = 0;\n this._lastWidth = (options.minWidth + options.maxWidth) / 2;\n this._ctx.fillStyle = options.penColor;\n this._ctx.globalCompositeOperation = options.compositeOperation;\n }\n\n private _createPoint(x: number, y: number, pressure: number): Point {\n const rect = this.canvas.getBoundingClientRect();\n\n return new Point(\n x - rect.left,\n y - rect.top,\n pressure,\n new Date().getTime(),\n );\n }\n\n // Add point to _lastPoints array and generate a new curve if there are enough points (i.e. 3)\n private _addPoint(point: Point, options: PointGroupOptions): Bezier | null {\n const { _lastPoints } = this;\n\n _lastPoints.push(point);\n\n if (_lastPoints.length > 2) {\n // To reduce the initial lag make it work with 3 points\n // by copying the first point to the beginning.\n if (_lastPoints.length === 3) {\n _lastPoints.unshift(_lastPoints[0]);\n }\n\n // _points array will always have 4 points here.\n const widths = this._calculateCurveWidths(\n _lastPoints[1],\n _lastPoints[2],\n options,\n );\n const curve = Bezier.fromPoints(_lastPoints, widths);\n\n // Remove the first element from the list, so that there are no more than 4 points at any time.\n _lastPoints.shift();\n\n return curve;\n }\n\n return null;\n }\n\n private _calculateCurveWidths(\n startPoint: Point,\n endPoint: Point,\n options: PointGroupOptions,\n ): { start: number; end: number } {\n const velocity =\n options.velocityFilterWeight * endPoint.velocityFrom(startPoint) +\n (1 - options.velocityFilterWeight) * this._lastVelocity;\n\n const newWidth = this._strokeWidth(velocity, options);\n\n const widths = {\n end: newWidth,\n start: this._lastWidth,\n };\n\n this._lastVelocity = velocity;\n this._lastWidth = newWidth;\n\n return widths;\n }\n\n private _strokeWidth(velocity: number, options: PointGroupOptions): number {\n return Math.max(options.maxWidth / (velocity + 1), options.minWidth);\n }\n\n private _drawCurveSegment(x: number, y: number, width: number): void {\n const ctx = this._ctx;\n\n ctx.moveTo(x, y);\n ctx.arc(x, y, width, 0, 2 * Math.PI, false);\n this._isEmpty = false;\n }\n\n private _drawCurve(curve: Bezier, options: PointGroupOptions): void {\n const ctx = this._ctx;\n const widthDelta = curve.endWidth - curve.startWidth;\n // '2' is just an arbitrary number here. If only length is used, then\n // there are gaps between curve segments :/\n const drawSteps = Math.ceil(curve.length()) * 2;\n\n ctx.beginPath();\n ctx.fillStyle = options.penColor;\n\n for (let i = 0; i < drawSteps; i += 1) {\n // Calculate the Bezier (x, y) coordinate for this step.\n const t = i / drawSteps;\n const tt = t * t;\n const ttt = tt * t;\n const u = 1 - t;\n const uu = u * u;\n const uuu = uu * u;\n\n let x = uuu * curve.startPoint.x;\n x += 3 * uu * t * curve.control1.x;\n x += 3 * u * tt * curve.control2.x;\n x += ttt * curve.endPoint.x;\n\n let y = uuu * curve.startPoint.y;\n y += 3 * uu * t * curve.control1.y;\n y += 3 * u * tt * curve.control2.y;\n y += ttt * curve.endPoint.y;\n\n const width = Math.min(\n curve.startWidth + ttt * widthDelta,\n options.maxWidth,\n );\n this._drawCurveSegment(x, y, width);\n }\n\n ctx.closePath();\n ctx.fill();\n }\n\n private _drawDot(point: BasicPoint, options: PointGroupOptions): void {\n const ctx = this._ctx;\n const width =\n options.dotSize > 0\n ? options.dotSize\n : (options.minWidth + options.maxWidth) / 2;\n\n ctx.beginPath();\n this._drawCurveSegment(point.x, point.y, width);\n ctx.closePath();\n ctx.fillStyle = options.penColor;\n ctx.fill();\n }\n\n private _fromData(\n pointGroups: PointGroup[],\n drawCurve: SignaturePad['_drawCurve'],\n drawDot: SignaturePad['_drawDot'],\n ): void {\n for (const group of pointGroups) {\n const { points } = group;\n const pointGroupOptions = this._getPointGroupOptions(group);\n\n if (points.length > 1) {\n for (let j = 0; j < points.length; j += 1) {\n const basicPoint = points[j];\n const point = new Point(\n basicPoint.x,\n basicPoint.y,\n basicPoint.pressure,\n basicPoint.time,\n );\n\n if (j === 0) {\n this._reset(pointGroupOptions);\n }\n\n const curve = this._addPoint(point, pointGroupOptions);\n\n if (curve) {\n drawCurve(curve, pointGroupOptions);\n }\n }\n } else {\n this._reset(pointGroupOptions);\n\n drawDot(points[0], pointGroupOptions);\n }\n }\n }\n\n public toSVG({ includeBackgroundColor = false }: ToSVGOptions = {}): string {\n const pointGroups = this._data;\n const ratio = Math.max(window.devicePixelRatio || 1, 1);\n const minX = 0;\n const minY = 0;\n const maxX = this.canvas.width / ratio;\n const maxY = this.canvas.height / ratio;\n const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');\n\n svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');\n svg.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');\n svg.setAttribute('viewBox', `${minX} ${minY} ${maxX} ${maxY}`);\n svg.setAttribute('width', maxX.toString());\n svg.setAttribute('height', maxY.toString());\n\n if (includeBackgroundColor && this.backgroundColor) {\n const rect = document.createElement('rect');\n rect.setAttribute('width', '100%');\n rect.setAttribute('height', '100%');\n rect.setAttribute('fill', this.backgroundColor);\n\n svg.appendChild(rect);\n }\n\n this._fromData(\n pointGroups,\n\n (curve, { penColor }) => {\n const path = document.createElement('path');\n\n // Need to check curve for NaN values, these pop up when drawing\n // lines on the canvas that are not continuous. E.g. Sharp corners\n // or stopping mid-stroke and than continuing without lifting mouse.\n if (\n !isNaN(curve.control1.x) &&\n !isNaN(curve.control1.y) &&\n !isNaN(curve.control2.x) &&\n !isNaN(curve.control2.y)\n ) {\n const attr =\n `M ${curve.startPoint.x.toFixed(3)},${curve.startPoint.y.toFixed(\n 3,\n )} ` +\n `C ${curve.control1.x.toFixed(3)},${curve.control1.y.toFixed(3)} ` +\n `${curve.control2.x.toFixed(3)},${curve.control2.y.toFixed(3)} ` +\n `${curve.endPoint.x.toFixed(3)},${curve.endPoint.y.toFixed(3)}`;\n path.setAttribute('d', attr);\n path.setAttribute('stroke-width', (curve.endWidth * 2.25).toFixed(3));\n path.setAttribute('stroke', penColor);\n path.setAttribute('fill', 'none');\n path.setAttribute('stroke-linecap', 'round');\n\n svg.appendChild(path);\n }\n },\n\n (point, { penColor, dotSize, minWidth, maxWidth }) => {\n const circle = document.createElement('circle');\n const size = dotSize > 0 ? dotSize : (minWidth + maxWidth) / 2;\n circle.setAttribute('r', size.toString());\n circle.setAttribute('cx', point.x.toString());\n circle.setAttribute('cy', point.y.toString());\n circle.setAttribute('fill', penColor);\n\n svg.appendChild(circle);\n },\n );\n\n return svg.outerHTML;\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-this-alias */\n// Slightly simplified version of http://stackoverflow.com/a/27078401/815507\n\nexport function throttle(\n fn: (...args: any[]) => any,\n wait = 250,\n): (this: any, ...args: any[]) => any {\n let previous = 0;\n let timeout: number | null = null;\n let result: any;\n let storedContext: any;\n let storedArgs: any[];\n\n const later = (): void => {\n previous = Date.now();\n timeout = null;\n result = fn.apply(storedContext, storedArgs);\n\n if (!timeout) {\n storedContext = null;\n storedArgs = [];\n }\n };\n\n return function wrapper(this: any, ...args: any[]): any {\n const now = Date.now();\n const remaining = wait - (now - previous);\n\n storedContext = this;\n storedArgs = args;\n\n if (remaining <= 0 || remaining > wait) {\n if (timeout) {\n clearTimeout(timeout);\n timeout = null;\n }\n\n previous = now;\n result = fn.apply(storedContext, storedArgs);\n\n if (!timeout) {\n storedContext = null;\n storedArgs = [];\n }\n } else if (!timeout) {\n timeout = window.setTimeout(later, remaining);\n }\n\n return result;\n };\n}\n"],"names":["Point","constructor","x","y","pressure","time","isNaN","Error","this","Date","now","distanceTo","start","Math","sqrt","pow","equals","other","velocityFrom","Bezier","fromPoints","points","widths","c2","calculateControlPoints","c3","c1","end","s1","s2","s3","dx1","dy1","dx2","dy2","m1","m2","l1","l2","k","cm","tx","ty","startPoint","control2","control1","endPoint","startWidth","endWidth","length","px","py","i","t","cx","point","cy","xdiff","ydiff","SignatureEventTarget","_et","EventTarget","_a","document","addEventListener","type","listener","options","dispatchEvent","event","removeEventListener","callback","SignaturePad","canvas","super","_drawingStroke","_isEmpty","_lastPoints","_data","_lastVelocity","_lastWidth","_handleMouseDown","_isLeftButtonPressed","_strokeBegin","_pointerEventToSignatureEvent","_handleMouseMove","_strokeMoveUpdate","_strokeEnd","_handleMouseUp","_handleTouchStart","targetTouches","cancelable","preventDefault","_touchEventToSignatureEvent","_handleTouchMove","_handleTouchEnd","_handlePointerDown","_handlePointerMove","_handlePointerUp","velocityFilterWeight","minWidth","maxWidth","throttle","minDistance","_b","dotSize","penColor","backgroundColor","compositeOperation","canvasContextOptions","_c","fn","wait","result","storedContext","storedArgs","previous","timeout","later","apply","args","remaining","clearTimeout","window","setTimeout","prototype","_strokeUpdate","_ctx","getContext","clear","on","ctx","fillStyle","clearRect","width","height","fillRect","_reset","_getPointGroupOptions","fromDataURL","dataUrl","Promise","resolve","reject","image","Image","ratio","devicePixelRatio","xOffset","yOffset","onload","drawImage","onerror","error","crossOrigin","src","toDataURL","encoderOptions","undefined","btoa","toSVG","style","touchAction","msTouchAction","userSelect","isIOS","test","navigator","userAgent","PointerEvent","_handlePointerEvents","_handleMouseEvents","_handleTouchEvents","off","_removeMoveUpEventListeners","_getListenerFunctions","canvasWindow","ownerDocument","defaultView","bind","isEmpty","fromData","pointGroups","_fromData","_drawCurve","_drawDot","concat","toData","only","buttons","clientX","clientY","touch","changedTouches","force","group","CustomEvent","detail","pointGroupOptions","newPointGroup","push","_createPoint","lastPointGroup","lastPoints","lastPoint","isLastPointTooClose","curve","_addPoint","shouldUpdate","globalCompositeOperation","rect","getBoundingClientRect","left","top","getTime","unshift","_calculateCurveWidths","shift","velocity","newWidth","_strokeWidth","max","_drawCurveSegment","moveTo","arc","PI","widthDelta","drawSteps","ceil","beginPath","tt","ttt","u","uu","uuu","min","closePath","fill","drawCurve","drawDot","j","basicPoint","includeBackgroundColor","maxX","maxY","svg","createElementNS","setAttribute","toString","createElement","appendChild","path","attr","toFixed","circle","size","outerHTML"],"mappings":";;;;mPAQaA,EAMX,WAAAC,CAAYC,EAAWC,EAAWC,EAAmBC,GACnD,GAAIC,MAAMJ,IAAMI,MAAMH,GACpB,MAAM,IAAII,MAAM,sBAAsBL,MAAMC,MAE9CK,KAAKN,GAAKA,EACVM,KAAKL,GAAKA,EACVK,KAAKJ,SAAWA,GAAY,EAC5BI,KAAKH,KAAOA,GAAQI,KAAKC,KAC1B,CAEM,UAAAC,CAAWC,GAChB,OAAOC,KAAKC,KACVD,KAAKE,IAAIP,KAAKN,EAAIU,EAAMV,EAAG,GAAKW,KAAKE,IAAIP,KAAKL,EAAIS,EAAMT,EAAG,GAE9D,CAEM,MAAAa,CAAOC,GACZ,OACET,KAAKN,IAAMe,EAAMf,GACjBM,KAAKL,IAAMc,EAAMd,GACjBK,KAAKJ,WAAaa,EAAMb,UACxBI,KAAKH,OAASY,EAAMZ,IAEvB,CAEM,YAAAa,CAAaN,GAClB,OAAOJ,KAAKH,OAASO,EAAMP,KACvBG,KAAKG,WAAWC,IAAUJ,KAAKH,KAAOO,EAAMP,MAC5C,CACL,QCzCUc,EACJ,iBAAOC,CACZC,EACAC,GAEA,MAAMC,EAAKf,KAAKgB,uBAAuBH,EAAO,GAAIA,EAAO,GAAIA,EAAO,IAAIE,GAClEE,EAAKjB,KAAKgB,uBAAuBH,EAAO,GAAIA,EAAO,GAAIA,EAAO,IAAIK,GAExE,OAAO,IAAIP,EAAOE,EAAO,GAAIE,EAAIE,EAAIJ,EAAO,GAAIC,EAAOV,MAAOU,EAAOK,IACtE,CAEO,6BAAOH,CACbI,EACAC,EACAC,GAKA,MAAMC,EAAMH,EAAG1B,EAAI2B,EAAG3B,EAChB8B,EAAMJ,EAAGzB,EAAI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,IAClEF,EAAKJ,aAAa,SAAU7I,GAC5BiJ,EAAKJ,aAAa,OAAQ,QAC1BI,EAAKJ,aAAa,iBAAkB,SAEpCF,EAAIK,YAAYC,EACjB,KAGH,CAACpM,GAASmD,WAAUD,UAASL,WAAUC,eACrC,MAAMyJ,EAAS/L,SAAS0L,cAAc,UAChCM,EAAOtJ,EAAU,EAAIA,GAAWL,EAAWC,GAAY,EAC7DyJ,EAAOP,aAAa,IAAKQ,EAAKP,YAC9BM,EAAOP,aAAa,KAAMhM,EAAMrD,EAAEsP,YAClCM,EAAOP,aAAa,KAAMhM,EAAMpD,EAAEqP,YAClCM,EAAOP,aAAa,OAAQ7I,GAE5B2I,EAAIK,YAAYI,EAAO,IAIpBT,EAAIW,SACZ"} \ No newline at end of file +{"version":3,"file":"signature_pad.umd.min.js","sources":["../src/point.ts","../src/bezier.ts","../src/signature_event_target.ts","../src/signature_pad.ts","../src/throttle.ts"],"sourcesContent":["// Interface for point data structure used e.g. in SignaturePad#fromData method\nexport interface BasicPoint {\n x: number;\n y: number;\n pressure: number;\n time: number;\n}\n\nexport class Point implements BasicPoint {\n public x: number;\n public y: number;\n public pressure: number;\n public time: number;\n\n constructor(x: number, y: number, pressure?: number, time?: number) {\n if (isNaN(x) || isNaN(y)) {\n throw new Error(`Point is invalid: (${x}, ${y})`);\n }\n this.x = +x;\n this.y = +y;\n this.pressure = pressure || 0;\n this.time = time || Date.now();\n }\n\n public distanceTo(start: BasicPoint): number {\n return Math.sqrt(\n Math.pow(this.x - start.x, 2) + Math.pow(this.y - start.y, 2),\n );\n }\n\n public equals(other: BasicPoint): boolean {\n return (\n this.x === other.x &&\n this.y === other.y &&\n this.pressure === other.pressure &&\n this.time === other.time\n );\n }\n\n public velocityFrom(start: BasicPoint): number {\n return this.time !== start.time\n ? this.distanceTo(start) / (this.time - start.time)\n : 0;\n }\n}\n","import { BasicPoint, Point } from './point';\n\nexport class Bezier {\n public static fromPoints(\n points: Point[],\n widths: { start: number; end: number },\n ): Bezier {\n const c2 = this.calculateControlPoints(points[0], points[1], points[2]).c2;\n const c3 = this.calculateControlPoints(points[1], points[2], points[3]).c1;\n\n return new Bezier(points[1], c2, c3, points[2], widths.start, widths.end);\n }\n\n private static calculateControlPoints(\n s1: BasicPoint,\n s2: BasicPoint,\n s3: BasicPoint,\n ): {\n c1: BasicPoint;\n c2: BasicPoint;\n } {\n const dx1 = s1.x - s2.x;\n const dy1 = s1.y - s2.y;\n const dx2 = s2.x - s3.x;\n const dy2 = s2.y - s3.y;\n\n const m1 = { x: (s1.x + s2.x) / 2.0, y: (s1.y + s2.y) / 2.0 };\n const m2 = { x: (s2.x + s3.x) / 2.0, y: (s2.y + s3.y) / 2.0 };\n\n const l1 = Math.sqrt(dx1 * dx1 + dy1 * dy1);\n const l2 = Math.sqrt(dx2 * dx2 + dy2 * dy2);\n\n const dxm = m1.x - m2.x;\n const dym = m1.y - m2.y;\n\n const k = l1 + l2 == 0 ? 0 : l2 / (l1 + l2);\n const cm = { x: m2.x + dxm * k, y: m2.y + dym * k };\n\n const tx = s2.x - cm.x;\n const ty = s2.y - cm.y;\n\n return {\n c1: new Point(m1.x + tx, m1.y + ty),\n c2: new Point(m2.x + tx, m2.y + ty),\n };\n }\n\n constructor(\n public startPoint: Point,\n public control2: BasicPoint,\n public control1: BasicPoint,\n public endPoint: Point,\n public startWidth: number,\n public endWidth: number,\n ) {}\n\n // Returns approximated length. Code taken from https://www.lemoda.net/maths/bezier-length/index.html.\n public length(): number {\n const steps = 10;\n let length = 0;\n let px;\n let py;\n\n for (let i = 0; i <= steps; i += 1) {\n const t = i / steps;\n const cx = this.point(\n t,\n this.startPoint.x,\n this.control1.x,\n this.control2.x,\n this.endPoint.x,\n );\n const cy = this.point(\n t,\n this.startPoint.y,\n this.control1.y,\n this.control2.y,\n this.endPoint.y,\n );\n\n if (i > 0) {\n const xdiff = cx - (px as number);\n const ydiff = cy - (py as number);\n\n length += Math.sqrt(xdiff * xdiff + ydiff * ydiff);\n }\n\n px = cx;\n py = cy;\n }\n\n return length;\n }\n\n // Calculate parametric value of x or y given t and the four point coordinates of a cubic bezier curve.\n private point(\n t: number,\n start: number,\n c1: number,\n c2: number,\n end: number,\n ): number {\n // prettier-ignore\n return ( start * (1.0 - t) * (1.0 - t) * (1.0 - t))\n + (3.0 * c1 * (1.0 - t) * (1.0 - t) * t)\n + (3.0 * c2 * (1.0 - t) * t * t)\n + ( end * t * t * t);\n }\n}\n","export class SignatureEventTarget {\n /* tslint:disable: variable-name */\n private _et: EventTarget;\n /* tslint:enable: variable-name */\n\n constructor() {\n try {\n this._et = new EventTarget();\n } catch {\n // Using document as EventTarget to support iOS 13 and older.\n // Because EventTarget constructor just exists at iOS 14 and later.\n this._et = document;\n }\n }\n\n addEventListener(\n type: string,\n listener: EventListenerOrEventListenerObject | null,\n options?: boolean | AddEventListenerOptions,\n ): void {\n this._et.addEventListener(type, listener, options);\n }\n\n dispatchEvent(event: Event): boolean {\n return this._et.dispatchEvent(event);\n }\n\n removeEventListener(\n type: string,\n callback: EventListenerOrEventListenerObject | null,\n options?: boolean | EventListenerOptions,\n ): void {\n this._et.removeEventListener(type, callback, options);\n }\n}\n","/**\n * The main idea and some parts of the code (e.g. drawing variable width Bézier curve) are taken from:\n * http://corner.squareup.com/2012/07/smoother-signatures.html\n *\n * Implementation of interpolation using cubic Bézier curves is taken from:\n * https://web.archive.org/web/20160323213433/http://www.benknowscode.com/2012/09/path-interpolation-using-cubic-bezier_9742.html\n *\n * Algorithm for approximated length of a Bézier curve is taken from:\n * http://www.lemoda.net/maths/bezier-length/index.html\n */\n\nimport { Bezier } from './bezier';\nimport { BasicPoint, Point } from './point';\nimport { SignatureEventTarget } from './signature_event_target';\nimport { throttle } from './throttle';\n\nexport interface SignatureEvent {\n event: MouseEvent | TouchEvent | PointerEvent;\n type: string;\n x: number;\n y: number;\n pressure: number;\n}\n\nexport interface FromDataOptions {\n clear?: boolean;\n}\n\nexport interface ToSVGOptions {\n includeBackgroundColor?: boolean;\n}\n\nexport interface PointGroupOptions {\n dotSize: number;\n minWidth: number;\n maxWidth: number;\n penColor: string;\n velocityFilterWeight: number;\n /**\n * This is the globalCompositeOperation for the line.\n * *default: 'source-over'*\n * @see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation\n */\n compositeOperation: GlobalCompositeOperation;\n}\n\nexport interface Options extends Partial {\n minDistance?: number;\n backgroundColor?: string;\n throttle?: number;\n canvasContextOptions?: CanvasRenderingContext2DSettings;\n}\n\nexport interface PointGroup extends PointGroupOptions {\n points: BasicPoint[];\n}\n\nexport default class SignaturePad extends SignatureEventTarget {\n // Public stuff\n public dotSize: number;\n public minWidth: number;\n public maxWidth: number;\n public penColor: string;\n public minDistance: number;\n public velocityFilterWeight: number;\n public compositeOperation: GlobalCompositeOperation;\n public backgroundColor: string;\n public throttle: number;\n public canvasContextOptions: CanvasRenderingContext2DSettings;\n\n // Private stuff\n /* tslint:disable: variable-name */\n private _ctx: CanvasRenderingContext2D;\n private _drawingStroke = false;\n private _isEmpty = true;\n private _lastPoints: Point[] = []; // Stores up to 4 most recent points; used to generate a new curve\n private _data: PointGroup[] = []; // Stores all points in groups (one group per line or dot)\n private _lastVelocity = 0;\n private _lastWidth = 0;\n private _strokeMoveUpdate: (event: SignatureEvent) => void;\n /* tslint:enable: variable-name */\n\n constructor(\n private canvas: HTMLCanvasElement,\n options: Options = {},\n ) {\n super();\n this.velocityFilterWeight = options.velocityFilterWeight || 0.7;\n this.minWidth = options.minWidth || 0.5;\n this.maxWidth = options.maxWidth || 2.5;\n\n // We need to handle 0 value, so use `??` instead of `||`\n this.throttle = options.throttle ?? 16; // in milliseconds\n this.minDistance = options.minDistance ?? 5; // in pixels\n this.dotSize = options.dotSize || 0;\n this.penColor = options.penColor || 'black';\n this.backgroundColor = options.backgroundColor || 'rgba(0,0,0,0)';\n this.compositeOperation = options.compositeOperation || 'source-over';\n this.canvasContextOptions = options.canvasContextOptions ?? {};\n\n this._strokeMoveUpdate = this.throttle\n ? throttle(SignaturePad.prototype._strokeUpdate, this.throttle)\n : SignaturePad.prototype._strokeUpdate;\n this._ctx = canvas.getContext(\n '2d',\n this.canvasContextOptions,\n ) as CanvasRenderingContext2D;\n\n this.clear();\n\n // Enable mouse and touch event handlers\n this.on();\n }\n\n public clear(): void {\n const { _ctx: ctx, canvas } = this;\n\n // Clear canvas using background color\n ctx.fillStyle = this.backgroundColor;\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n ctx.fillRect(0, 0, canvas.width, canvas.height);\n\n this._data = [];\n this._reset(this._getPointGroupOptions());\n this._isEmpty = true;\n }\n\n public fromDataURL(\n dataUrl: string,\n options: {\n ratio?: number;\n width?: number;\n height?: number;\n xOffset?: number;\n yOffset?: number;\n } = {},\n ): Promise {\n return new Promise((resolve, reject) => {\n const image = new Image();\n const ratio = options.ratio || window.devicePixelRatio || 1;\n const width = options.width || this.canvas.width / ratio;\n const height = options.height || this.canvas.height / ratio;\n const xOffset = options.xOffset || 0;\n const yOffset = options.yOffset || 0;\n\n this._reset(this._getPointGroupOptions());\n\n image.onload = (): void => {\n this._ctx.drawImage(image, xOffset, yOffset, width, height);\n resolve();\n };\n image.onerror = (error): void => {\n reject(error);\n };\n image.crossOrigin = 'anonymous';\n image.src = dataUrl;\n\n this._isEmpty = false;\n });\n }\n\n public toDataURL(\n type: 'image/svg+xml',\n encoderOptions?: ToSVGOptions,\n ): string;\n public toDataURL(type?: string, encoderOptions?: number): string;\n public toDataURL(\n type = 'image/png',\n encoderOptions?: number | ToSVGOptions | undefined,\n ): string {\n switch (type) {\n case 'image/svg+xml':\n if (typeof encoderOptions !== 'object') {\n encoderOptions = undefined;\n }\n return `data:image/svg+xml;base64,${btoa(\n this.toSVG(encoderOptions as ToSVGOptions),\n )}`;\n default:\n if (typeof encoderOptions !== 'number') {\n encoderOptions = undefined;\n }\n return this.canvas.toDataURL(type, encoderOptions);\n }\n }\n\n public on(): void {\n // Disable panning/zooming when touching canvas element\n this.canvas.style.touchAction = 'none';\n (this.canvas.style as CSSStyleDeclaration & { msTouchAction: string | null }).msTouchAction = 'none';\n this.canvas.style.userSelect = 'none';\n\n const isIOS =\n /Macintosh/.test(navigator.userAgent) && 'ontouchstart' in document;\n\n // The \"Scribble\" feature of iOS intercepts point events. So that we can\n // lose some of them when tapping rapidly. Use touch events for iOS\n // platforms to prevent it. See\n // https://developer.apple.com/forums/thread/664108 for more information.\n if (window.PointerEvent && !isIOS) {\n this._handlePointerEvents();\n } else {\n this._handleMouseEvents();\n\n if ('ontouchstart' in window) {\n this._handleTouchEvents();\n }\n }\n }\n\n public off(): void {\n // Enable panning/zooming when touching canvas element\n this.canvas.style.touchAction = 'auto';\n (this.canvas.style as CSSStyleDeclaration & { msTouchAction: string | null }).msTouchAction = 'auto';\n this.canvas.style.userSelect = 'auto';\n\n this.canvas.removeEventListener('pointerdown', this._handlePointerDown);\n this.canvas.removeEventListener('mousedown', this._handleMouseDown);\n this.canvas.removeEventListener('touchstart', this._handleTouchStart);\n\n this._removeMoveUpEventListeners();\n }\n\n private _getListenerFunctions() {\n const canvasWindow =\n window.document === this.canvas.ownerDocument\n ? window\n : this.canvas.ownerDocument.defaultView ?? this.canvas.ownerDocument;\n\n return {\n addEventListener: canvasWindow.addEventListener.bind(\n canvasWindow,\n ) as typeof window.addEventListener,\n removeEventListener: canvasWindow.removeEventListener.bind(\n canvasWindow,\n ) as typeof window.removeEventListener,\n };\n }\n\n private _removeMoveUpEventListeners(): void {\n const { removeEventListener } = this._getListenerFunctions();\n removeEventListener('pointermove', this._handlePointerMove);\n removeEventListener('pointerup', this._handlePointerUp);\n\n removeEventListener('mousemove', this._handleMouseMove);\n removeEventListener('mouseup', this._handleMouseUp);\n\n removeEventListener('touchmove', this._handleTouchMove);\n removeEventListener('touchend', this._handleTouchEnd);\n }\n\n public isEmpty(): boolean {\n return this._isEmpty;\n }\n\n public fromData(\n pointGroups: PointGroup[],\n { clear = true }: FromDataOptions = {},\n ): void {\n if (clear) {\n this.clear();\n }\n\n this._fromData(\n pointGroups,\n this._drawCurve.bind(this),\n this._drawDot.bind(this),\n );\n\n this._data = this._data.concat(pointGroups);\n }\n\n public toData(): PointGroup[] {\n return this._data;\n }\n\n public _isLeftButtonPressed(event: MouseEvent, only?: boolean): boolean {\n if (only) {\n return event.buttons === 1;\n }\n\n return (event.buttons & 1) === 1;\n }\n private _pointerEventToSignatureEvent(\n event: MouseEvent | PointerEvent,\n ): SignatureEvent {\n return {\n event: event,\n type: event.type,\n x: event.clientX,\n y: event.clientY,\n pressure: 'pressure' in event ? event.pressure : 0,\n };\n }\n\n private _touchEventToSignatureEvent(event: TouchEvent): SignatureEvent {\n const touch = event.changedTouches[0];\n return {\n event: event,\n type: event.type,\n x: touch.clientX,\n y: touch.clientY,\n pressure: touch.force,\n };\n }\n\n // Event handlers\n private _handleMouseDown = (event: MouseEvent): void => {\n if (!this._isLeftButtonPressed(event, true) || this._drawingStroke) {\n return;\n }\n this._strokeBegin(this._pointerEventToSignatureEvent(event));\n };\n\n private _handleMouseMove = (event: MouseEvent): void => {\n if (!this._isLeftButtonPressed(event, true) || !this._drawingStroke) {\n // Stop when not pressing primary button or pressing multiple buttons\n this._strokeEnd(this._pointerEventToSignatureEvent(event), false);\n return;\n }\n\n this._strokeMoveUpdate(this._pointerEventToSignatureEvent(event));\n };\n\n private _handleMouseUp = (event: MouseEvent): void => {\n if (this._isLeftButtonPressed(event)) {\n return;\n }\n\n this._strokeEnd(this._pointerEventToSignatureEvent(event));\n };\n\n private _handleTouchStart = (event: TouchEvent): void => {\n if (event.targetTouches.length !== 1 || this._drawingStroke) {\n return;\n }\n\n // Prevent scrolling.\n if (event.cancelable) {\n event.preventDefault();\n }\n\n this._strokeBegin(this._touchEventToSignatureEvent(event));\n };\n\n private _handleTouchMove = (event: TouchEvent): void => {\n if (event.targetTouches.length !== 1) {\n return;\n }\n\n // Prevent scrolling.\n if (event.cancelable) {\n event.preventDefault();\n }\n\n if (!this._drawingStroke) {\n this._strokeEnd(this._touchEventToSignatureEvent(event), false);\n return;\n }\n\n this._strokeMoveUpdate(this._touchEventToSignatureEvent(event));\n };\n\n private _handleTouchEnd = (event: TouchEvent): void => {\n if (event.targetTouches.length !== 0) {\n return;\n }\n\n if (event.cancelable) {\n event.preventDefault();\n }\n\n this.canvas.removeEventListener('touchmove', this._handleTouchMove);\n\n this._strokeEnd(this._touchEventToSignatureEvent(event));\n };\n\n private _handlePointerDown = (event: PointerEvent): void => {\n if (!event.isPrimary || !this._isLeftButtonPressed(event) || this._drawingStroke) {\n return;\n }\n\n event.preventDefault();\n\n this._strokeBegin(this._pointerEventToSignatureEvent(event));\n };\n\n private _handlePointerMove = (event: PointerEvent): void => {\n if (!event.isPrimary) {\n return;\n }\n if (!this._isLeftButtonPressed(event, true) || !this._drawingStroke) {\n // Stop when primary button not pressed or multiple buttons pressed\n this._strokeEnd(this._pointerEventToSignatureEvent(event), false);\n return;\n }\n\n event.preventDefault();\n this._strokeMoveUpdate(this._pointerEventToSignatureEvent(event));\n };\n\n private _handlePointerUp = (event: PointerEvent): void => {\n if (!event.isPrimary || this._isLeftButtonPressed(event)) {\n return;\n }\n\n event.preventDefault();\n this._strokeEnd(this._pointerEventToSignatureEvent(event));\n };\n\n private _getPointGroupOptions(group?: PointGroup): PointGroupOptions {\n return {\n penColor: group && 'penColor' in group ? group.penColor : this.penColor,\n dotSize: group && 'dotSize' in group ? group.dotSize : this.dotSize,\n minWidth: group && 'minWidth' in group ? group.minWidth : this.minWidth,\n maxWidth: group && 'maxWidth' in group ? group.maxWidth : this.maxWidth,\n velocityFilterWeight:\n group && 'velocityFilterWeight' in group\n ? group.velocityFilterWeight\n : this.velocityFilterWeight,\n compositeOperation:\n group && 'compositeOperation' in group\n ? group.compositeOperation\n : this.compositeOperation,\n };\n }\n\n // Private methods\n private _strokeBegin(event: SignatureEvent): void {\n const cancelled = !this.dispatchEvent(\n new CustomEvent('beginStroke', { detail: event, cancelable: true }),\n );\n if (cancelled) {\n return;\n }\n\n const { addEventListener } = this._getListenerFunctions();\n switch (event.event.type) {\n case 'mousedown':\n addEventListener('mousemove', this._handleMouseMove);\n addEventListener('mouseup', this._handleMouseUp);\n break;\n case 'touchstart':\n addEventListener('touchmove', this._handleTouchMove);\n addEventListener('touchend', this._handleTouchEnd);\n break;\n case 'pointerdown':\n addEventListener('pointermove', this._handlePointerMove);\n addEventListener('pointerup', this._handlePointerUp);\n break;\n default:\n // do nothing\n }\n\n this._drawingStroke = true;\n\n const pointGroupOptions = this._getPointGroupOptions();\n\n const newPointGroup: PointGroup = {\n ...pointGroupOptions,\n points: [],\n };\n\n this._data.push(newPointGroup);\n this._reset(pointGroupOptions);\n this._strokeUpdate(event);\n }\n\n private _strokeUpdate(event: SignatureEvent): void {\n if (!this._drawingStroke) {\n return;\n }\n\n if (this._data.length === 0) {\n // This can happen if clear() was called while a signature is still in progress,\n // or if there is a race condition between start/update events.\n this._strokeBegin(event);\n return;\n }\n\n this.dispatchEvent(\n new CustomEvent('beforeUpdateStroke', { detail: event }),\n );\n\n const point = this._createPoint(event.x, event.y, event.pressure);\n const lastPointGroup = this._data[this._data.length - 1];\n const lastPoints = lastPointGroup.points;\n const lastPoint =\n lastPoints.length > 0 && lastPoints[lastPoints.length - 1];\n const isLastPointTooClose = lastPoint\n ? point.distanceTo(lastPoint) <= this.minDistance\n : false;\n const pointGroupOptions = this._getPointGroupOptions(lastPointGroup);\n\n // Skip this point if it's too close to the previous one\n if (!lastPoint || !(lastPoint && isLastPointTooClose)) {\n const curve = this._addPoint(point, pointGroupOptions);\n\n if (!lastPoint) {\n this._drawDot(point, pointGroupOptions);\n } else if (curve) {\n this._drawCurve(curve, pointGroupOptions);\n }\n\n lastPoints.push({\n time: point.time,\n x: point.x,\n y: point.y,\n pressure: point.pressure,\n });\n }\n\n this.dispatchEvent(new CustomEvent('afterUpdateStroke', { detail: event }));\n }\n\n private _strokeEnd(event: SignatureEvent, shouldUpdate = true): void {\n this._removeMoveUpEventListeners();\n\n if (!this._drawingStroke) {\n return;\n }\n\n if (shouldUpdate) {\n this._strokeUpdate(event);\n }\n\n this._drawingStroke = false;\n this.dispatchEvent(new CustomEvent('endStroke', { detail: event }));\n }\n\n private _handlePointerEvents(): void {\n this._drawingStroke = false;\n\n this.canvas.addEventListener('pointerdown', this._handlePointerDown);\n }\n\n private _handleMouseEvents(): void {\n this._drawingStroke = false;\n\n this.canvas.addEventListener('mousedown', this._handleMouseDown);\n }\n\n private _handleTouchEvents(): void {\n this.canvas.addEventListener('touchstart', this._handleTouchStart);\n }\n\n // Called when a new line is started\n private _reset(options: PointGroupOptions): void {\n this._lastPoints = [];\n this._lastVelocity = 0;\n this._lastWidth = (options.minWidth + options.maxWidth) / 2;\n this._ctx.fillStyle = options.penColor;\n this._ctx.globalCompositeOperation = options.compositeOperation;\n }\n\n private _createPoint(x: number, y: number, pressure: number): Point {\n const rect = this.canvas.getBoundingClientRect();\n\n return new Point(\n x - rect.left,\n y - rect.top,\n pressure,\n new Date().getTime(),\n );\n }\n\n // Add point to _lastPoints array and generate a new curve if there are enough points (i.e. 3)\n private _addPoint(point: Point, options: PointGroupOptions): Bezier | null {\n const { _lastPoints } = this;\n\n _lastPoints.push(point);\n\n if (_lastPoints.length > 2) {\n // To reduce the initial lag make it work with 3 points\n // by copying the first point to the beginning.\n if (_lastPoints.length === 3) {\n _lastPoints.unshift(_lastPoints[0]);\n }\n\n // _points array will always have 4 points here.\n const widths = this._calculateCurveWidths(\n _lastPoints[1],\n _lastPoints[2],\n options,\n );\n const curve = Bezier.fromPoints(_lastPoints, widths);\n\n // Remove the first element from the list, so that there are no more than 4 points at any time.\n _lastPoints.shift();\n\n return curve;\n }\n\n return null;\n }\n\n private _calculateCurveWidths(\n startPoint: Point,\n endPoint: Point,\n options: PointGroupOptions,\n ): { start: number; end: number } {\n const velocity =\n options.velocityFilterWeight * endPoint.velocityFrom(startPoint) +\n (1 - options.velocityFilterWeight) * this._lastVelocity;\n\n const newWidth = this._strokeWidth(velocity, options);\n\n const widths = {\n end: newWidth,\n start: this._lastWidth,\n };\n\n this._lastVelocity = velocity;\n this._lastWidth = newWidth;\n\n return widths;\n }\n\n private _strokeWidth(velocity: number, options: PointGroupOptions): number {\n return Math.max(options.maxWidth / (velocity + 1), options.minWidth);\n }\n\n private _drawCurveSegment(x: number, y: number, width: number): void {\n const ctx = this._ctx;\n\n ctx.moveTo(x, y);\n ctx.arc(x, y, width, 0, 2 * Math.PI, false);\n this._isEmpty = false;\n }\n\n private _drawCurve(curve: Bezier, options: PointGroupOptions): void {\n const ctx = this._ctx;\n const widthDelta = curve.endWidth - curve.startWidth;\n // '2' is just an arbitrary number here. If only length is used, then\n // there are gaps between curve segments :/\n const drawSteps = Math.ceil(curve.length()) * 2;\n\n ctx.beginPath();\n ctx.fillStyle = options.penColor;\n\n for (let i = 0; i < drawSteps; i += 1) {\n // Calculate the Bezier (x, y) coordinate for this step.\n const t = i / drawSteps;\n const tt = t * t;\n const ttt = tt * t;\n const u = 1 - t;\n const uu = u * u;\n const uuu = uu * u;\n\n let x = uuu * curve.startPoint.x;\n x += 3 * uu * t * curve.control1.x;\n x += 3 * u * tt * curve.control2.x;\n x += ttt * curve.endPoint.x;\n\n let y = uuu * curve.startPoint.y;\n y += 3 * uu * t * curve.control1.y;\n y += 3 * u * tt * curve.control2.y;\n y += ttt * curve.endPoint.y;\n\n const width = Math.min(\n curve.startWidth + ttt * widthDelta,\n options.maxWidth,\n );\n this._drawCurveSegment(x, y, width);\n }\n\n ctx.closePath();\n ctx.fill();\n }\n\n private _drawDot(point: BasicPoint, options: PointGroupOptions): void {\n const ctx = this._ctx;\n const width =\n options.dotSize > 0\n ? options.dotSize\n : (options.minWidth + options.maxWidth) / 2;\n\n ctx.beginPath();\n this._drawCurveSegment(point.x, point.y, width);\n ctx.closePath();\n ctx.fillStyle = options.penColor;\n ctx.fill();\n }\n\n private _fromData(\n pointGroups: PointGroup[],\n drawCurve: SignaturePad['_drawCurve'],\n drawDot: SignaturePad['_drawDot'],\n ): void {\n for (const group of pointGroups) {\n const { points } = group;\n const pointGroupOptions = this._getPointGroupOptions(group);\n\n if (points.length > 1) {\n for (let j = 0; j < points.length; j += 1) {\n const basicPoint = points[j];\n const point = new Point(\n basicPoint.x,\n basicPoint.y,\n basicPoint.pressure,\n basicPoint.time,\n );\n\n if (j === 0) {\n this._reset(pointGroupOptions);\n }\n\n const curve = this._addPoint(point, pointGroupOptions);\n\n if (curve) {\n drawCurve(curve, pointGroupOptions);\n }\n }\n } else {\n this._reset(pointGroupOptions);\n\n drawDot(points[0], pointGroupOptions);\n }\n }\n }\n\n public toSVG({ includeBackgroundColor = false }: ToSVGOptions = {}): string {\n const pointGroups = this._data;\n const ratio = Math.max(window.devicePixelRatio || 1, 1);\n const minX = 0;\n const minY = 0;\n const maxX = this.canvas.width / ratio;\n const maxY = this.canvas.height / ratio;\n const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');\n\n svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');\n svg.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');\n svg.setAttribute('viewBox', `${minX} ${minY} ${maxX} ${maxY}`);\n svg.setAttribute('width', maxX.toString());\n svg.setAttribute('height', maxY.toString());\n\n if (includeBackgroundColor && this.backgroundColor) {\n const rect = document.createElement('rect');\n rect.setAttribute('width', '100%');\n rect.setAttribute('height', '100%');\n rect.setAttribute('fill', this.backgroundColor);\n\n svg.appendChild(rect);\n }\n\n this._fromData(\n pointGroups,\n\n (curve, { penColor }) => {\n const path = document.createElement('path');\n\n // Need to check curve for NaN values, these pop up when drawing\n // lines on the canvas that are not continuous. E.g. Sharp corners\n // or stopping mid-stroke and than continuing without lifting mouse.\n if (\n !isNaN(curve.control1.x) &&\n !isNaN(curve.control1.y) &&\n !isNaN(curve.control2.x) &&\n !isNaN(curve.control2.y)\n ) {\n const attr =\n `M ${curve.startPoint.x.toFixed(3)},${curve.startPoint.y.toFixed(\n 3,\n )} ` +\n `C ${curve.control1.x.toFixed(3)},${curve.control1.y.toFixed(3)} ` +\n `${curve.control2.x.toFixed(3)},${curve.control2.y.toFixed(3)} ` +\n `${curve.endPoint.x.toFixed(3)},${curve.endPoint.y.toFixed(3)}`;\n path.setAttribute('d', attr);\n path.setAttribute('stroke-width', (curve.endWidth * 2.25).toFixed(3));\n path.setAttribute('stroke', penColor);\n path.setAttribute('fill', 'none');\n path.setAttribute('stroke-linecap', 'round');\n\n svg.appendChild(path);\n }\n },\n\n (point, { penColor, dotSize, minWidth, maxWidth }) => {\n const circle = document.createElement('circle');\n const size = dotSize > 0 ? dotSize : (minWidth + maxWidth) / 2;\n circle.setAttribute('r', size.toString());\n circle.setAttribute('cx', point.x.toString());\n circle.setAttribute('cy', point.y.toString());\n circle.setAttribute('fill', penColor);\n\n svg.appendChild(circle);\n },\n );\n\n return svg.outerHTML;\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-this-alias */\n// Slightly simplified version of http://stackoverflow.com/a/27078401/815507\n\nexport function throttle(\n fn: (...args: any[]) => any,\n wait = 250,\n): (this: any, ...args: any[]) => any {\n let previous = 0;\n let timeout: number | null = null;\n let result: any;\n let storedContext: any;\n let storedArgs: any[];\n\n const later = (): void => {\n previous = Date.now();\n timeout = null;\n result = fn.apply(storedContext, storedArgs);\n\n if (!timeout) {\n storedContext = null;\n storedArgs = [];\n }\n };\n\n return function wrapper(this: any, ...args: any[]): any {\n const now = Date.now();\n const remaining = wait - (now - previous);\n\n storedContext = this;\n storedArgs = args;\n\n if (remaining <= 0 || remaining > wait) {\n if (timeout) {\n clearTimeout(timeout);\n timeout = null;\n }\n\n previous = now;\n result = fn.apply(storedContext, storedArgs);\n\n if (!timeout) {\n storedContext = null;\n storedArgs = [];\n }\n } else if (!timeout) {\n timeout = window.setTimeout(later, remaining);\n }\n\n return result;\n };\n}\n"],"names":["Point","constructor","x","y","pressure","time","isNaN","Error","this","Date","now","distanceTo","start","Math","sqrt","pow","equals","other","velocityFrom","Bezier","fromPoints","points","widths","c2","calculateControlPoints","c3","c1","end","s1","s2","s3","dx1","dy1","dx2","dy2","m1","m2","l1","l2","k","cm","tx","ty","startPoint","control2","control1","endPoint","startWidth","endWidth","length","px","py","i","t","cx","point","cy","xdiff","ydiff","SignatureEventTarget","_et","EventTarget","_a","document","addEventListener","type","listener","options","dispatchEvent","event","removeEventListener","callback","SignaturePad","canvas","super","_drawingStroke","_isEmpty","_lastPoints","_data","_lastVelocity","_lastWidth","_handleMouseDown","_isLeftButtonPressed","_strokeBegin","_pointerEventToSignatureEvent","_handleMouseMove","_strokeMoveUpdate","_strokeEnd","_handleMouseUp","_handleTouchStart","targetTouches","cancelable","preventDefault","_touchEventToSignatureEvent","_handleTouchMove","_handleTouchEnd","_handlePointerDown","isPrimary","_handlePointerMove","_handlePointerUp","velocityFilterWeight","minWidth","maxWidth","throttle","minDistance","_b","dotSize","penColor","backgroundColor","compositeOperation","canvasContextOptions","_c","fn","wait","result","storedContext","storedArgs","previous","timeout","later","apply","args","remaining","clearTimeout","window","setTimeout","prototype","_strokeUpdate","_ctx","getContext","clear","on","ctx","fillStyle","clearRect","width","height","fillRect","_reset","_getPointGroupOptions","fromDataURL","dataUrl","Promise","resolve","reject","image","Image","ratio","devicePixelRatio","xOffset","yOffset","onload","drawImage","onerror","error","crossOrigin","src","toDataURL","encoderOptions","undefined","btoa","toSVG","style","touchAction","msTouchAction","userSelect","isIOS","test","navigator","userAgent","PointerEvent","_handlePointerEvents","_handleMouseEvents","_handleTouchEvents","off","_removeMoveUpEventListeners","_getListenerFunctions","canvasWindow","ownerDocument","defaultView","bind","isEmpty","fromData","pointGroups","_fromData","_drawCurve","_drawDot","concat","toData","only","buttons","clientX","clientY","touch","changedTouches","force","group","CustomEvent","detail","pointGroupOptions","newPointGroup","push","_createPoint","lastPointGroup","lastPoints","lastPoint","isLastPointTooClose","curve","_addPoint","shouldUpdate","globalCompositeOperation","rect","getBoundingClientRect","left","top","getTime","unshift","_calculateCurveWidths","shift","velocity","newWidth","_strokeWidth","max","_drawCurveSegment","moveTo","arc","PI","widthDelta","drawSteps","ceil","beginPath","tt","ttt","u","uu","uuu","min","closePath","fill","drawCurve","drawDot","j","basicPoint","includeBackgroundColor","maxX","maxY","svg","createElementNS","setAttribute","toString","createElement","appendChild","path","attr","toFixed","circle","size","outerHTML"],"mappings":";;;;mPAQaA,EAMX,WAAAC,CAAYC,EAAWC,EAAWC,EAAmBC,GACnD,GAAIC,MAAMJ,IAAMI,MAAMH,GACpB,MAAM,IAAII,MAAM,sBAAsBL,MAAMC,MAE9CK,KAAKN,GAAKA,EACVM,KAAKL,GAAKA,EACVK,KAAKJ,SAAWA,GAAY,EAC5BI,KAAKH,KAAOA,GAAQI,KAAKC,KAC1B,CAEM,UAAAC,CAAWC,GAChB,OAAOC,KAAKC,KACVD,KAAKE,IAAIP,KAAKN,EAAIU,EAAMV,EAAG,GAAKW,KAAKE,IAAIP,KAAKL,EAAIS,EAAMT,EAAG,GAE9D,CAEM,MAAAa,CAAOC,GACZ,OACET,KAAKN,IAAMe,EAAMf,GACjBM,KAAKL,IAAMc,EAAMd,GACjBK,KAAKJ,WAAaa,EAAMb,UACxBI,KAAKH,OAASY,EAAMZ,IAEvB,CAEM,YAAAa,CAAaN,GAClB,OAAOJ,KAAKH,OAASO,EAAMP,KACvBG,KAAKG,WAAWC,IAAUJ,KAAKH,KAAOO,EAAMP,MAC5C,CACL,QCzCUc,EACJ,iBAAOC,CACZC,EACAC,GAEA,MAAMC,EAAKf,KAAKgB,uBAAuBH,EAAO,GAAIA,EAAO,GAAIA,EAAO,IAAIE,GAClEE,EAAKjB,KAAKgB,uBAAuBH,EAAO,GAAIA,EAAO,GAAIA,EAAO,IAAIK,GAExE,OAAO,IAAIP,EAAOE,EAAO,GAAIE,EAAIE,EAAIJ,EAAO,GAAIC,EAAOV,MAAOU,EAAOK,IACtE,CAEO,6BAAOH,CACbI,EACAC,EACAC,GAKA,MAAMC,EAAMH,EAAG1B,EAAI2B,EAAG3B,EAChB8B,EAA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AKK,GACvBD,EAAKJ,aAAa,gBAAkC,KAAjBzC,EAAM/J,UAAiB8M,QAAQ,IAClEF,EAAKJ,aAAa,SAAU7I,GAC5BiJ,EAAKJ,aAAa,OAAQ,QAC1BI,EAAKJ,aAAa,iBAAkB,SAEpCF,EAAIK,YAAYC,EACjB,KAGH,CAACrM,GAASoD,WAAUD,UAASL,WAAUC,eACrC,MAAMyJ,EAAShM,SAAS2L,cAAc,UAChCM,EAAOtJ,EAAU,EAAIA,GAAWL,EAAWC,GAAY,EAC7DyJ,EAAOP,aAAa,IAAKQ,EAAKP,YAC9BM,EAAOP,aAAa,KAAMjM,EAAMrD,EAAEuP,YAClCM,EAAOP,aAAa,KAAMjM,EAAMpD,EAAEsP,YAClCM,EAAOP,aAAa,OAAQ7I,GAE5B2I,EAAIK,YAAYI,EAAO,IAIpBT,EAAIW,SACZ"} \ No newline at end of file diff --git a/src/signature_pad.ts b/src/signature_pad.ts index a57dd62d..d61b6901 100644 --- a/src/signature_pad.ts +++ b/src/signature_pad.ts @@ -376,7 +376,7 @@ export default class SignaturePad extends SignatureEventTarget { }; private _handlePointerDown = (event: PointerEvent): void => { - if (!this._isLeftButtonPressed(event) || this._drawingStroke) { + if (!event.isPrimary || !this._isLeftButtonPressed(event) || this._drawingStroke) { return; } @@ -386,6 +386,9 @@ export default class SignaturePad extends SignatureEventTarget { }; private _handlePointerMove = (event: PointerEvent): void => { + if (!event.isPrimary) { + return; + } if (!this._isLeftButtonPressed(event, true) || !this._drawingStroke) { // Stop when primary button not pressed or multiple buttons pressed this._strokeEnd(this._pointerEventToSignatureEvent(event), false); @@ -397,7 +400,7 @@ export default class SignaturePad extends SignatureEventTarget { }; private _handlePointerUp = (event: PointerEvent): void => { - if (this._isLeftButtonPressed(event)) { + if (!event.isPrimary || this._isLeftButtonPressed(event)) { return; } diff --git a/tests/__snapshots__/signature_pad.test.ts.snap b/tests/__snapshots__/signature_pad.test.ts.snap index 9e8260f1..863ace1d 100644 --- a/tests/__snapshots__/signature_pad.test.ts.snap +++ b/tests/__snapshots__/signature_pad.test.ts.snap @@ -17,3 +17,5 @@ exports[`#toSVG returns SVG image with backgroundColor 1`] = `""`; exports[`user interactions allows user to paint on the pad 1`] = `"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB2aWV3Qm94PSIwIDAgMzAwIDE1MCIgd2lkdGg9IjMwMCIgaGVpZ2h0PSIxNTAiPjxjaXJjbGUgcj0iMS41IiBjeD0iNTAiIGN5PSIzMCIgZmlsbD0iYmxhY2siPjwvY2lyY2xlPjxjaXJjbGUgcj0iMS41IiBjeD0iMjQwIiBjeT0iMzAiIGZpbGw9ImJsYWNrIj48L2NpcmNsZT48Y2lyY2xlIHI9IjEuNSIgY3g9IjE1MCIgY3k9IjEyMCIgZmlsbD0iYmxhY2siPjwvY2lyY2xlPjwvc3ZnPg=="`; + +exports[`user interactions non-primary pointer events are ignored 1`] = `"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB2aWV3Qm94PSIwIDAgMzAwIDE1MCIgd2lkdGg9IjMwMCIgaGVpZ2h0PSIxNTAiPjxjaXJjbGUgcj0iMS41IiBjeD0iNTAiIGN5PSIzMCIgZmlsbD0iYmxhY2siPjwvY2lyY2xlPjwvc3ZnPg=="`; diff --git a/tests/signature_pad.test.ts b/tests/signature_pad.test.ts index 8327db66..7e4bce1a 100644 --- a/tests/signature_pad.test.ts +++ b/tests/signature_pad.test.ts @@ -267,6 +267,7 @@ describe('user interactions', () => { const pad = new SignaturePad(canvas); canvas.dispatchEvent( new PointerEvent('pointerdown', { + isPrimary: true, clientX: 50, clientY: 30, pressure: 1, @@ -275,6 +276,7 @@ describe('user interactions', () => { ); window.dispatchEvent( new PointerEvent('pointerup', { + isPrimary: true, clientX: 50, clientY: 30, pressure: 1, @@ -282,6 +284,7 @@ describe('user interactions', () => { ); canvas.dispatchEvent( new PointerEvent('pointerdown', { + isPrimary: true, clientX: 240, clientY: 30, pressure: 1, @@ -290,6 +293,7 @@ describe('user interactions', () => { ); window.dispatchEvent( new PointerEvent('pointerup', { + isPrimary: true, clientX: 240, clientY: 30, pressure: 1, @@ -297,6 +301,7 @@ describe('user interactions', () => { ); canvas.dispatchEvent( new PointerEvent('pointerdown', { + isPrimary: true, clientX: 150, clientY: 120, pressure: 1, @@ -305,6 +310,7 @@ describe('user interactions', () => { ); window.dispatchEvent( new PointerEvent('pointerup', { + isPrimary: true, clientX: 150, clientY: 120, pressure: 1, @@ -313,12 +319,52 @@ describe('user interactions', () => { expect(pad.toDataURL('image/svg+xml')).toMatchSnapshot(); }); + it('non-primary pointer events are ignored', () => { + const pad = new SignaturePad(canvas); + canvas.dispatchEvent( + new PointerEvent('pointerdown', { + isPrimary: true, + clientX: 50, + clientY: 30, + pressure: 1, + buttons: 1, + }), + ); + canvas.dispatchEvent( + new PointerEvent('pointerdown', { + isPrimary: false, + clientX: 240, + clientY: 30, + pressure: 1, + buttons: 1, + }), + ); + window.dispatchEvent( + new PointerEvent('pointerup', { + isPrimary: false, + clientX: 240, + clientY: 30, + pressure: 1, + }), + ); + window.dispatchEvent( + new PointerEvent('pointerup', { + isPrimary: true, + clientX: 50, + clientY: 30, + pressure: 1, + }), + ); + expect(pad.toDataURL('image/svg+xml')).toMatchSnapshot(); + }); + it('call endStroke on pointerup outside canvas', () => { const pad = new SignaturePad(canvas); const endStroke = jest.fn(); pad.addEventListener('endStroke', endStroke); canvas.dispatchEvent( new PointerEvent('pointerdown', { + isPrimary: true, clientX: 50, clientY: 30, pressure: 1, @@ -327,6 +373,7 @@ describe('user interactions', () => { ); window.dispatchEvent( new PointerEvent('pointermove', { + isPrimary: true, clientX: 240, clientY: 30, pressure: 1, @@ -335,6 +382,7 @@ describe('user interactions', () => { ); window.dispatchEvent( new PointerEvent('pointerup', { + isPrimary: true, clientX: 150, clientY: 120, pressure: 1, @@ -359,6 +407,7 @@ describe('user interactions', () => { externalCanvas.dispatchEvent( new PointerEvent('pointerdown', { + isPrimary: true, clientX: 50, clientY: 30, pressure: 1, @@ -367,6 +416,7 @@ describe('user interactions', () => { ); externalCanvas.dispatchEvent( new PointerEvent('pointermove', { + isPrimary: true, clientX: 240, clientY: 30, pressure: 1, @@ -376,6 +426,7 @@ describe('user interactions', () => { // check that original document is not affected window.dispatchEvent( new PointerEvent('pointerup', { + isPrimary: true, clientX: 150, clientY: 120, pressure: 1, @@ -385,6 +436,7 @@ describe('user interactions', () => { // check that external document emits externalDocument.dispatchEvent( new PointerEvent('pointerup', { + isPrimary: true, clientX: 150, clientY: 120, pressure: 1, @@ -505,6 +557,7 @@ describe('Signature events.', () => { describe(`${param.eventName}.`, () => { function createPointerEvent(dispatchedEventName: string) { return new PointerEvent(dispatchedEventName, { + isPrimary: true, clientX: 50, clientY: 30, pressure: 1, @@ -554,6 +607,7 @@ describe('Signature events.', () => { it('the event should be dispatched.', () => { const eventInitObj = { + isPrimary: true, clientX: 50, clientY: 30, pressure: 1, @@ -581,6 +635,7 @@ describe('Signature events.', () => { canvas.dispatchEvent( new PointerEvent('pointerdown', { + isPrimary: true, clientX: 50, clientY: 30, pressure: 1, @@ -589,6 +644,7 @@ describe('Signature events.', () => { ); canvas.dispatchEvent( new PointerEvent('pointermove', { + isPrimary: true, clientX: 50, clientY: 40, pressure: 1, @@ -597,6 +653,7 @@ describe('Signature events.', () => { ); window.dispatchEvent( new PointerEvent('pointerup', { + isPrimary: true, clientX: 50, clientY: 40, pressure: 1,