FIX: bezier resizing img lost
[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.ontouchstart) {
147             canvas.on('touchstart', this._handleTouchStart, this);
148             canvas.on('touchmove', this._handleTouchMove, this);
149             canvas.on('touchend', this._handleTouchEnd, this);
150         }
151         
152         Roo.EventManager.onWindowResize(this.resize, this, true);
153         
154         this.clear();
155         
156         this.resize();
157     },
158     
159     resize: function(){
160         var canvas = this.canvasEl().dom;
161         var ctx = this.canvasElCtx();
162         
163         var img_data = ctx.getImageData(0, 0, canvas.width, canvas.height);
164         
165         // setting canvas width will clean img data inside
166         canvas.width = 0;
167         
168         var style = window.getComputedStyle ? 
169             getComputedStyle(this.el.dom, null) : this.el.dom.currentStyle;
170         
171         var padding_left = parseInt(style.paddingLeft) || 0;
172         var padding_right = parseInt(style.paddingRight) || 0;
173         
174         canvas.width = this.el.dom.clientWidth - padding_left - padding_right;
175         
176         ctx.putImageData(img_data, 0, 0);
177     },
178     
179     _handleMouseDown: function(e)
180     {
181         if (e.browserEvent.which === 1) {
182             this.mouse_btn_down = true;
183             this.strokeBegin(e);
184         }
185     },
186     
187     _handleMouseMove: function (e)
188     {
189         if (this.mouse_btn_down) {
190             this.strokeMoveUpdate(e);
191         }
192     },
193     
194     _handleMouseUp: function (e)
195     {
196         if (e.browserEvent.which === 1 && this.mouse_btn_down) {
197             this.mouse_btn_down = false;
198             this.strokeEnd(e);
199         }
200     },
201     
202     _handleTouchStart: function (e) {
203         e.preventDefault();
204         if (e.browserEvent.targetTouches.length === 1) {
205             // var touch = e.browserEvent.changedTouches[0];
206             // this.strokeBegin(touch);
207             
208              this.strokeBegin(e); // assume e catching the correct xy...
209         }
210     },
211     
212     _handleTouchMove: function (e) {
213         e.preventDefault();
214         // var touch = event.targetTouches[0];
215         // _this._strokeMoveUpdate(touch);
216         this._strokeMoveUpdate(e);
217     },
218     
219     _handleTouchEnd: function (e) {
220         var wasCanvasTouched = e.target === this.canvasEl().dom;
221         if (wasCanvasTouched) {
222             e.preventDefault();
223             // var touch = event.changedTouches[0];
224             // _this._strokeEnd(touch);
225             this.strokeEnd(e);
226         }
227     },
228     
229     reset: function () {
230         this._lastPoints = [];
231         this._lastVelocity = 0;
232         this._lastWidth = (this.min_width + this.max_width) / 2;
233         this.canvasElCtx().fillStyle = this.dot_color;
234     },
235     
236     strokeMoveUpdate: function(e)
237     {
238         this.strokeUpdate(e);
239         
240         if (this.throttle) {
241             this.throttle(this.strokeUpdate, this.throttle);
242         }
243         else {
244             this.strokeUpdate(e);
245         }
246     },
247     
248     strokeBegin: function(e)
249     {
250         var newPointGroup = {
251             color: this.dot_color,
252             points: []
253         };
254         
255         if (typeof this.onBegin === 'function') {
256             this.onBegin(e);
257         }
258         
259         this.curve_data.push(newPointGroup);
260         this.reset();
261         this.strokeUpdate(e);
262     },
263     
264     strokeUpdate: function(e)
265     {
266         var rect = this.canvasEl().dom.getBoundingClientRect();
267         var point = new this.Point(e.xy[0] - rect.left, e.xy[1] - rect.top, new Date().getTime());
268         var lastPointGroup = this.curve_data[this.curve_data.length - 1];
269         var lastPoints = lastPointGroup.points;
270         var lastPoint = lastPoints.length > 0 && lastPoints[lastPoints.length - 1];
271         var isLastPointTooClose = lastPoint
272             ? point.distanceTo(lastPoint) <= this.min_distance
273             : false;
274         var color = lastPointGroup.color;
275         if (!lastPoint || !(lastPoint && isLastPointTooClose)) {
276             var curve = this.addPoint(point);
277             if (!lastPoint) {
278                 this.drawDot({color: color, point: point});
279             }
280             else if (curve) {
281                 this.drawCurve({color: color, curve: curve});
282             }
283             lastPoints.push({
284                 time: point.time,
285                 x: point.x,
286                 y: point.y
287             });
288         }
289     },
290     
291     strokeEnd: function(e)
292     {
293         this.strokeUpdate(e);
294         if (typeof this.onEnd === 'function') {
295             this.onEnd(e);
296         }
297     },
298     
299     addPoint:  function (point) {
300         var _lastPoints = this._lastPoints;
301         _lastPoints.push(point);
302         if (_lastPoints.length > 2) {
303             if (_lastPoints.length === 3) {
304                 _lastPoints.unshift(_lastPoints[0]);
305             }
306             var widths = this.calculateCurveWidths(_lastPoints[1], _lastPoints[2]);
307             var curve = this.Bezier.fromPoints(_lastPoints, widths, this);
308             _lastPoints.shift();
309             return curve;
310         }
311         return null;
312     },
313     
314     calculateCurveWidths: function (startPoint, endPoint) {
315         var velocity = this.velocity_filter_weight * endPoint.velocityFrom(startPoint) +
316             (1 - this.velocity_filter_weight) * this._lastVelocity;
317
318         var newWidth = Math.max(this.max_width / (velocity + 1), this.min_width);
319         var widths = {
320             end: newWidth,
321             start: this._lastWidth
322         };
323         
324         this._lastVelocity = velocity;
325         this._lastWidth = newWidth;
326         return widths;
327     },
328     
329     drawDot: function (_a) {
330         var color = _a.color, point = _a.point;
331         var ctx = this.canvasElCtx();
332         var width = typeof this.dot_size === 'function' ? this.dot_size() : this.dot_size;
333         ctx.beginPath();
334         this.drawCurveSegment(point.x, point.y, width);
335         ctx.closePath();
336         ctx.fillStyle = color;
337         ctx.fill();
338     },
339     
340     drawCurve: function (_a) {
341         var color = _a.color, curve = _a.curve;
342         var ctx = this.canvasElCtx();
343         var widthDelta = curve.endWidth - curve.startWidth;
344         var drawSteps = Math.floor(curve.length()) * 2;
345         ctx.beginPath();
346         ctx.fillStyle = color;
347         for (var i = 0; i < drawSteps; i += 1) {
348         var t = i / drawSteps;
349         var tt = t * t;
350         var ttt = tt * t;
351         var u = 1 - t;
352         var uu = u * u;
353         var uuu = uu * u;
354         var x = uuu * curve.startPoint.x;
355         x += 3 * uu * t * curve.control1.x;
356         x += 3 * u * tt * curve.control2.x;
357         x += ttt * curve.endPoint.x;
358         var y = uuu * curve.startPoint.y;
359         y += 3 * uu * t * curve.control1.y;
360         y += 3 * u * tt * curve.control2.y;
361         y += ttt * curve.endPoint.y;
362         var width = curve.startWidth + ttt * widthDelta;
363         this.drawCurveSegment(x, y, width);
364         }
365         ctx.closePath();
366         ctx.fill();
367     },
368     
369     drawCurveSegment: function (x, y, width) {
370         var ctx = this.canvasElCtx();
371         ctx.moveTo(x, y);
372         ctx.arc(x, y, width, 0, 2 * Math.PI, false);
373         this.is_empty = false;
374     },
375     
376     clear: function()
377     {
378         var ctx = this.canvasElCtx();
379         var canvas = this.canvasEl().dom;
380         ctx.fillStyle = this.bg_color;
381         ctx.clearRect(0, 0, canvas.width, canvas.height);
382         ctx.fillRect(0, 0, canvas.width, canvas.height);
383         this.curve_data = [];
384         this.reset();
385         this.is_empty = true;
386     },
387     
388     canvasEl: function()
389     {
390         return this.el.select('canvas',true).first();
391     },
392     
393     canvasElCtx: function()
394     {
395         return this.el.select('canvas',true).first().dom.getContext('2d');
396     },
397     
398     getImage: function(type)
399     {
400         if(this.is_empty) {
401             return false;
402         }
403         
404         // encryption ?
405         return this.canvasEl().dom.toDataURL('image/'+type, false);
406     },
407     
408     drawFromImage: function(img_src)
409     {
410         var img = new Image();
411         
412         img.src = img_src;
413         
414         this.canvasElCtx().drawImage(img, 0, 0);
415     },
416     
417     // Bezier Point Constructor
418     Point: (function () {
419         function Point(x, y, time) {
420             this.x = x;
421             this.y = y;
422             this.time = time || Date.now();
423         }
424         Point.prototype.distanceTo = function (start) {
425             return Math.sqrt(Math.pow(this.x - start.x, 2) + Math.pow(this.y - start.y, 2));
426         };
427         Point.prototype.equals = function (other) {
428             return this.x === other.x && this.y === other.y && this.time === other.time;
429         };
430         Point.prototype.velocityFrom = function (start) {
431             return this.time !== start.time
432             ? this.distanceTo(start) / (this.time - start.time)
433             : 0;
434         };
435         return Point;
436     }()),
437     
438     
439     // Bezier Constructor
440     Bezier: (function () {
441         function Bezier(startPoint, control2, control1, endPoint, startWidth, endWidth) {
442             this.startPoint = startPoint;
443             this.control2 = control2;
444             this.control1 = control1;
445             this.endPoint = endPoint;
446             this.startWidth = startWidth;
447             this.endWidth = endWidth;
448         }
449         Bezier.fromPoints = function (points, widths, scope) {
450             var c2 = this.calculateControlPoints(points[0], points[1], points[2], scope).c2;
451             var c3 = this.calculateControlPoints(points[1], points[2], points[3], scope).c1;
452             return new Bezier(points[1], c2, c3, points[2], widths.start, widths.end);
453         };
454         Bezier.calculateControlPoints = function (s1, s2, s3, scope) {
455             var dx1 = s1.x - s2.x;
456             var dy1 = s1.y - s2.y;
457             var dx2 = s2.x - s3.x;
458             var dy2 = s2.y - s3.y;
459             var m1 = { x: (s1.x + s2.x) / 2.0, y: (s1.y + s2.y) / 2.0 };
460             var m2 = { x: (s2.x + s3.x) / 2.0, y: (s2.y + s3.y) / 2.0 };
461             var l1 = Math.sqrt(dx1 * dx1 + dy1 * dy1);
462             var l2 = Math.sqrt(dx2 * dx2 + dy2 * dy2);
463             var dxm = m1.x - m2.x;
464             var dym = m1.y - m2.y;
465             var k = l2 / (l1 + l2);
466             var cm = { x: m2.x + dxm * k, y: m2.y + dym * k };
467             var tx = s2.x - cm.x;
468             var ty = s2.y - cm.y;
469             return {
470                 c1: new scope.Point(m1.x + tx, m1.y + ty),
471                 c2: new scope.Point(m2.x + tx, m2.y + ty)
472             };
473         };
474         Bezier.prototype.length = function () {
475             var steps = 10;
476             var length = 0;
477             var px;
478             var py;
479             for (var i = 0; i <= steps; i += 1) {
480                 var t = i / steps;
481                 var cx = this.point(t, this.startPoint.x, this.control1.x, this.control2.x, this.endPoint.x);
482                 var cy = this.point(t, this.startPoint.y, this.control1.y, this.control2.y, this.endPoint.y);
483                 if (i > 0) {
484                     var xdiff = cx - px;
485                     var ydiff = cy - py;
486                     length += Math.sqrt(xdiff * xdiff + ydiff * ydiff);
487                 }
488                 px = cx;
489                 py = cy;
490             }
491             return length;
492         };
493         Bezier.prototype.point = function (t, start, c1, c2, end) {
494             return (start * (1.0 - t) * (1.0 - t) * (1.0 - t))
495             + (3.0 * c1 * (1.0 - t) * (1.0 - t) * t)
496             + (3.0 * c2 * (1.0 - t) * t * t)
497             + (end * t * t * t);
498         };
499         return Bezier;
500     }()),
501     
502     throttle: function(fn, wait) {
503       if (wait === void 0) { wait = 250; }
504       var previous = 0;
505       var timeout = null;
506       var result;
507       var storedContext;
508       var storedArgs;
509       var later = function () {
510           previous = Date.now();
511           timeout = null;
512           result = fn.apply(storedContext, storedArgs);
513           if (!timeout) {
514               storedContext = null;
515               storedArgs = [];
516           }
517       };
518       return function wrapper() {
519           var args = [];
520           for (var _i = 0; _i < arguments.length; _i++) {
521               args[_i] = arguments[_i];
522           }
523           var now = Date.now();
524           var remaining = wait - (now - previous);
525           storedContext = this;
526           storedArgs = args;
527           if (remaining <= 0 || remaining > wait) {
528               if (timeout) {
529                   clearTimeout(timeout);
530                   timeout = null;
531               }
532               previous = now;
533               result = fn.apply(storedContext, storedArgs);
534               if (!timeout) {
535                   storedContext = null;
536                   storedArgs = [];
537               }
538           }
539           else if (!timeout) {
540               timeout = window.setTimeout(later, remaining);
541           }
542           return result;
543       };
544   }
545   
546 });
547
548  
549
550