3bbdd17b9dde2033aa2020dde3b9f358a7664aed
[roojs1] / Roo / bootstrap / BezierSignature.js
1 /**
2 *    This script refer to:
3 *    Title: Signature Pad
4 *    Author: szimek
5 *    Availability: https://github.com/szimek/signature_pad
6 **/
7
8 /**
9  * @class Roo.bootstrap.BezierSignature
10  * @extends Roo.bootstrap.Component
11  * Bootstrap BezierSignature class
12  * 
13  * @constructor
14  * Create a new BezierSignature
15  * @param {Object} config The config object
16  */
17
18 Roo.bootstrap.BezierSignature = function(config){
19     Roo.bootstrap.BezierSignature.superclass.constructor.call(this, config);
20     this.addEvents({
21         "resize" : true
22     });
23 };
24
25 Roo.extend(Roo.bootstrap.BezierSignature, Roo.bootstrap.Component,  {
26     
27     curve_data: [],
28     
29     is_empty: true,
30     
31     mouse_btn_down: true,
32     
33     /**
34      * @cfg(int) canvas height
35      */
36     canvas_height: '200px',
37     
38     /**
39      * @cfg(float or function) Radius of a single dot.
40      */ 
41     dot_size: false,
42     
43     /**
44      * @cfg(float) Minimum width of a line. Defaults to 0.5.
45      */
46     min_width: 0.5,
47     
48     /**
49      * @cfg(float) Maximum width of a line. Defaults to 2.5.
50      */
51     max_width: 2.5,
52     
53     /**
54      * @cfg(integer) Draw the next point at most once per every x milliseconds. Set it to 0 to turn off throttling. Defaults to 16.
55      */
56     throttle: 16,
57     
58     /**
59      * @cfg(integer) Add the next point only if the previous one is farther than x pixels. Defaults to 5.
60      */
61     min_distance: 5,
62     
63     /**
64      * @cfg(string) Color used to clear the background. Can be any color format accepted by context.fillStyle. Defaults to "rgba(0,0,0,0)" (transparent black). Use a non-transparent color e.g. "rgb(255,255,255)" (opaque white) if you'd like to save signatures as JPEG images.
65      */
66     bg_color: 'rgba(0, 0, 0, 0)',
67     
68     /**
69      * @cfg(string) Color used to draw the lines. Can be any color format accepted by context.fillStyle. Defaults to "black".
70      */
71     dot_color: 'black',
72     
73     /**
74      * @cfg(float) Weight used to modify new velocity based on the previous velocity. Defaults to 0.7.
75      */
76     velocity_filter_weight: 0.7,
77     
78     /**
79      * @cfg(function) Callback when stroke begin.
80      */
81     onBegin: false,
82     
83     /**
84      * @cfg(function) Callback when stroke end.
85      */
86     onEnd: false,
87     
88     getAutoCreate : function()
89     {
90         var cls = 'roo-signature column';
91         
92         if(this.cls){
93             cls += ' ' + this.cls;
94         }
95         
96         var col_sizes = [
97             'lg',
98             'md',
99             'sm',
100             'xs'
101         ];
102         
103         for(var i = 0; i < col_sizes.length; i++) {
104             if(this[col_sizes[i]]) {
105                 cls += " col-"+col_sizes[i]+"-"+this[col_sizes[i]];
106             }
107         }
108         
109         var cfg = {
110             tag: 'div',
111             cls: cls,
112             cn: [
113                 {
114                     tag: 'div',
115                     cls: 'roo-signature-body',
116                     cn: [
117                         {
118                             tag: 'canvas',
119                             cls: 'roo-signature-body-canvas',
120                             height: this.canvas_height,
121                             width: this.canvas_width
122                         }
123                     ]
124                 }
125             ]
126         };
127         
128         return cfg;
129     },
130     
131     initEvents: function() 
132     {
133         Roo.bootstrap.BezierSignature.superclass.initEvents.call(this);
134         
135         var canvas = this.canvasEl();
136         
137         // mouse && touch event swapping...
138         canvas.dom.style.touchAction = 'none';
139         canvas.dom.style.msTouchAction = 'none';
140         
141         this.mouse_btn_down = false;
142         canvas.on('mousedown', this._handleMouseDown, this);
143         canvas.on('mousemove', this._handleMouseMove, this);
144         Roo.select('html').first().on('mouseup', this._handleMouseUp, this);
145         
146         if (window.PointerEvent) {
147             canvas.on('pointerdown', this._handleMouseDown, this);
148             canvas.on('pointermove', this._handleMouseMove, this);
149             Roo.select('html').first().on('pointerup', this._handleMouseUp, this);
150         }
151         
152         if ('ontouchstart' in window) {
153             canvas.on('touchstart', this._handleTouchStart, this);
154             canvas.on('touchmove', this._handleTouchMove, this);
155             canvas.on('touchend', this._handleTouchEnd, this);
156         }
157         
158         Roo.EventManager.onWindowResize(this.resize, this, true);
159         
160         this.clear();
161         
162         this.resize();
163     },
164     
165     resize: function(){
166         
167         var canvas = this.canvasEl().dom;
168         var ctx = this.canvasElCtx();
169         var img_data = ctx.getImageData(0, 0, canvas.width, canvas.height);
170         
171         // setting canvas width will clean img data
172         canvas.width = 0;
173         
174         var style = window.getComputedStyle ? 
175             getComputedStyle(this.el.dom, null) : this.el.dom.currentStyle;
176             
177         var padding_left = parseInt(style.paddingLeft) || 0;
178         var padding_right = parseInt(style.paddingRight) || 0;
179         
180         canvas.width = this.el.dom.clientWidth - padding_left - padding_right;
181         
182         ctx.putImageData(img_data, 0, 0);
183     },
184     
185     _handleMouseDown: function(e)
186     {
187         if (e.browserEvent.which === 1) {
188             this.mouse_btn_down = true;
189             this.strokeBegin(e);
190         }
191     },
192     
193     _handleMouseMove: function (e)
194     {
195         if (this.mouse_btn_down) {
196             this.strokeMoveUpdate(e);
197         }
198     },
199     
200     _handleMouseUp: function (e)
201     {
202         if (e.browserEvent.which === 1 && this.mouse_btn_down) {
203             this.mouse_btn_down = false;
204             this.strokeEnd(e);
205         }
206     },
207     
208     _handleTouchStart: function (e) {
209         
210         e.preventDefault();
211         if (e.browserEvent.targetTouches.length === 1) {
212             // var touch = e.browserEvent.changedTouches[0];
213             // this.strokeBegin(touch);
214             
215              this.strokeBegin(e); // assume e catching the correct xy...
216         }
217     },
218     
219     _handleTouchMove: function (e) {
220         e.preventDefault();
221         // var touch = event.targetTouches[0];
222         // _this._strokeMoveUpdate(touch);
223         this.strokeMoveUpdate(e);
224     },
225     
226     _handleTouchEnd: function (e) {
227         var wasCanvasTouched = e.target === this.canvasEl().dom;
228         if (wasCanvasTouched) {
229             e.preventDefault();
230             // var touch = event.changedTouches[0];
231             // _this._strokeEnd(touch);
232             this.strokeEnd(e);
233         }
234     },
235     
236     reset: function () {
237         this._lastPoints = [];
238         this._lastVelocity = 0;
239         this._lastWidth = (this.min_width + this.max_width) / 2;
240         this.canvasElCtx().fillStyle = this.dot_color;
241     },
242     
243     strokeMoveUpdate: function(e)
244     {
245         this.strokeUpdate(e);
246         
247         if (this.throttle) {
248             this.throttle(this.strokeUpdate, this.throttle);
249         }
250         else {
251             this.strokeUpdate(e);
252         }
253     },
254     
255     strokeBegin: function(e)
256     {
257         var newPointGroup = {
258             color: this.dot_color,
259             points: []
260         };
261         
262         if (typeof this.onBegin === 'function') {
263             this.onBegin(e);
264         }
265         
266         this.curve_data.push(newPointGroup);
267         this.reset();
268         this.strokeUpdate(e);
269     },
270     
271     strokeUpdate: function(e)
272     {
273         var rect = this.canvasEl().dom.getBoundingClientRect();
274         var point = new this.Point(e.xy[0] - rect.left, e.xy[1] - rect.top, new Date().getTime());
275         var lastPointGroup = this.curve_data[this.curve_data.length - 1];
276         var lastPoints = lastPointGroup.points;
277         var lastPoint = lastPoints.length > 0 && lastPoints[lastPoints.length - 1];
278         var isLastPointTooClose = lastPoint
279             ? point.distanceTo(lastPoint) <= this.min_distance
280             : false;
281         var color = lastPointGroup.color;
282         if (!lastPoint || !(lastPoint && isLastPointTooClose)) {
283             var curve = this.addPoint(point);
284             if (!lastPoint) {
285                 this.drawDot({color: color, point: point});
286             }
287             else if (curve) {
288                 this.drawCurve({color: color, curve: curve});
289             }
290             lastPoints.push({
291                 time: point.time,
292                 x: point.x,
293                 y: point.y
294             });
295         }
296     },
297     
298     strokeEnd: function(e)
299     {
300         this.strokeUpdate(e);
301         if (typeof this.onEnd === 'function') {
302             this.onEnd(e);
303         }
304     },
305     
306     addPoint:  function (point) {
307         var _lastPoints = this._lastPoints;
308         _lastPoints.push(point);
309         if (_lastPoints.length > 2) {
310             if (_lastPoints.length === 3) {
311                 _lastPoints.unshift(_lastPoints[0]);
312             }
313             var widths = this.calculateCurveWidths(_lastPoints[1], _lastPoints[2]);
314             var curve = this.Bezier.fromPoints(_lastPoints, widths, this);
315             _lastPoints.shift();
316             return curve;
317         }
318         return null;
319     },
320     
321     calculateCurveWidths: function (startPoint, endPoint) {
322         var velocity = this.velocity_filter_weight * endPoint.velocityFrom(startPoint) +
323             (1 - this.velocity_filter_weight) * this._lastVelocity;
324
325         var newWidth = Math.max(this.max_width / (velocity + 1), this.min_width);
326         var widths = {
327             end: newWidth,
328             start: this._lastWidth
329         };
330         
331         this._lastVelocity = velocity;
332         this._lastWidth = newWidth;
333         return widths;
334     },
335     
336     drawDot: function (_a) {
337         var color = _a.color, point = _a.point;
338         var ctx = this.canvasElCtx();
339         var width = typeof this.dot_size === 'function' ? this.dot_size() : this.dot_size;
340         ctx.beginPath();
341         this.drawCurveSegment(point.x, point.y, width);
342         ctx.closePath();
343         ctx.fillStyle = color;
344         ctx.fill();
345     },
346     
347     drawCurve: function (_a) {
348         var color = _a.color, curve = _a.curve;
349         var ctx = this.canvasElCtx();
350         var widthDelta = curve.endWidth - curve.startWidth;
351         var drawSteps = Math.floor(curve.length()) * 2;
352         ctx.beginPath();
353         ctx.fillStyle = color;
354         for (var i = 0; i < drawSteps; i += 1) {
355         var t = i / drawSteps;
356         var tt = t * t;
357         var ttt = tt * t;
358         var u = 1 - t;
359         var uu = u * u;
360         var uuu = uu * u;
361         var x = uuu * curve.startPoint.x;
362         x += 3 * uu * t * curve.control1.x;
363         x += 3 * u * tt * curve.control2.x;
364         x += ttt * curve.endPoint.x;
365         var y = uuu * curve.startPoint.y;
366         y += 3 * uu * t * curve.control1.y;
367         y += 3 * u * tt * curve.control2.y;
368         y += ttt * curve.endPoint.y;
369         var width = curve.startWidth + ttt * widthDelta;
370         this.drawCurveSegment(x, y, width);
371         }
372         ctx.closePath();
373         ctx.fill();
374     },
375     
376     drawCurveSegment: function (x, y, width) {
377         var ctx = this.canvasElCtx();
378         ctx.moveTo(x, y);
379         ctx.arc(x, y, width, 0, 2 * Math.PI, false);
380         this.is_empty = false;
381     },
382     
383     clear: function()
384     {
385         var ctx = this.canvasElCtx();
386         var canvas = this.canvasEl().dom;
387         ctx.fillStyle = this.bg_color;
388         ctx.clearRect(0, 0, canvas.width, canvas.height);
389         ctx.fillRect(0, 0, canvas.width, canvas.height);
390         this.curve_data = [];
391         this.reset();
392         this.is_empty = true;
393     },
394     
395     canvasEl: function()
396     {
397         return this.el.select('canvas',true).first();
398     },
399     
400     canvasElCtx: function()
401     {
402         return this.el.select('canvas',true).first().dom.getContext('2d');
403     },
404     
405     getImage: function(type)
406     {
407         if(this.is_empty) {
408             return false;
409         }
410         
411         // encryption ?
412         return this.canvasEl().dom.toDataURL('image/'+type, 1);
413     },
414     
415     drawFromImage: function(img_src)
416     {
417         var img = new Image();
418         
419         img.onload = function(){
420             this.canvasElCtx().drawImage(img, 0, 0);
421         }.bind(this);
422         
423         img.src = img_src;
424         
425         this.is_empty = false;
426     },
427     
428     // Bezier Point Constructor
429     Point: (function () {
430         function Point(x, y, time) {
431             this.x = x;
432             this.y = y;
433             this.time = time || Date.now();
434         }
435         Point.prototype.distanceTo = function (start) {
436             return Math.sqrt(Math.pow(this.x - start.x, 2) + Math.pow(this.y - start.y, 2));
437         };
438         Point.prototype.equals = function (other) {
439             return this.x === other.x && this.y === other.y && this.time === other.time;
440         };
441         Point.prototype.velocityFrom = function (start) {
442             return this.time !== start.time
443             ? this.distanceTo(start) / (this.time - start.time)
444             : 0;
445         };
446         return Point;
447     }()),
448     
449     
450     // Bezier Constructor
451     Bezier: (function () {
452         function Bezier(startPoint, control2, control1, endPoint, startWidth, endWidth) {
453             this.startPoint = startPoint;
454             this.control2 = control2;
455             this.control1 = control1;
456             this.endPoint = endPoint;
457             this.startWidth = startWidth;
458             this.endWidth = endWidth;
459         }
460         Bezier.fromPoints = function (points, widths, scope) {
461             var c2 = this.calculateControlPoints(points[0], points[1], points[2], scope).c2;
462             var c3 = this.calculateControlPoints(points[1], points[2], points[3], scope).c1;
463             return new Bezier(points[1], c2, c3, points[2], widths.start, widths.end);
464         };
465         Bezier.calculateControlPoints = function (s1, s2, s3, scope) {
466             var dx1 = s1.x - s2.x;
467             var dy1 = s1.y - s2.y;
468             var dx2 = s2.x - s3.x;
469             var dy2 = s2.y - s3.y;
470             var m1 = { x: (s1.x + s2.x) / 2.0, y: (s1.y + s2.y) / 2.0 };
471             var m2 = { x: (s2.x + s3.x) / 2.0, y: (s2.y + s3.y) / 2.0 };
472             var l1 = Math.sqrt(dx1 * dx1 + dy1 * dy1);
473             var l2 = Math.sqrt(dx2 * dx2 + dy2 * dy2);
474             var dxm = m1.x - m2.x;
475             var dym = m1.y - m2.y;
476             var k = l2 / (l1 + l2);
477             var cm = { x: m2.x + dxm * k, y: m2.y + dym * k };
478             var tx = s2.x - cm.x;
479             var ty = s2.y - cm.y;
480             return {
481                 c1: new scope.Point(m1.x + tx, m1.y + ty),
482                 c2: new scope.Point(m2.x + tx, m2.y + ty)
483             };
484         };
485         Bezier.prototype.length = function () {
486             var steps = 10;
487             var length = 0;
488             var px;
489             var py;
490             for (var i = 0; i <= steps; i += 1) {
491                 var t = i / steps;
492                 var cx = this.point(t, this.startPoint.x, this.control1.x, this.control2.x, this.endPoint.x);
493                 var cy = this.point(t, this.startPoint.y, this.control1.y, this.control2.y, this.endPoint.y);
494                 if (i > 0) {
495                     var xdiff = cx - px;
496                     var ydiff = cy - py;
497                     length += Math.sqrt(xdiff * xdiff + ydiff * ydiff);
498                 }
499                 px = cx;
500                 py = cy;
501             }
502             return length;
503         };
504         Bezier.prototype.point = function (t, start, c1, c2, end) {
505             return (start * (1.0 - t) * (1.0 - t) * (1.0 - t))
506             + (3.0 * c1 * (1.0 - t) * (1.0 - t) * t)
507             + (3.0 * c2 * (1.0 - t) * t * t)
508             + (end * t * t * t);
509         };
510         return Bezier;
511     }()),
512     
513     throttle: function(fn, wait) {
514       if (wait === void 0) { wait = 250; }
515       var previous = 0;
516       var timeout = null;
517       var result;
518       var storedContext;
519       var storedArgs;
520       var later = function () {
521           previous = Date.now();
522           timeout = null;
523           result = fn.apply(storedContext, storedArgs);
524           if (!timeout) {
525               storedContext = null;
526               storedArgs = [];
527           }
528       };
529       return function wrapper() {
530           var args = [];
531           for (var _i = 0; _i < arguments.length; _i++) {
532               args[_i] = arguments[_i];
533           }
534           var now = Date.now();
535           var remaining = wait - (now - previous);
536           storedContext = this;
537           storedArgs = args;
538           if (remaining <= 0 || remaining > wait) {
539               if (timeout) {
540                   clearTimeout(timeout);
541                   timeout = null;
542               }
543               previous = now;
544               result = fn.apply(storedContext, storedArgs);
545               if (!timeout) {
546                   storedContext = null;
547                   storedArgs = [];
548               }
549           }
550           else if (!timeout) {
551               timeout = window.setTimeout(later, remaining);
552           }
553           return result;
554       };
555   }
556   
557 });
558
559  
560
561