forked from willowsystems/jSignature
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjSignature.js
executable file
·1374 lines (1217 loc) · 43.3 KB
/
jSignature.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** @preserve
jSignature v2
Copyright (c) 2012 Willow Systems Corp http://willow-systems.com
Copyright (c) 2010 Brinley Ang http://www.unbolt.net
MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
;(function($) {
var apinamespace = 'jSignature'
/**
Allows one to delay certain eventual action by setting up a timer for it and allowing one to delay it
by "kick"ing it. Sorta like "kick the can down the road"
@public
@class
@param
@returns {Type}
*/
var KickTimerClass = function(time, callback) {
var timer
this.kick = function() {
clearTimeout(timer)
timer = setTimeout(
callback
, time
)
}
this.clear = function() {
clearTimeout(timer)
}
return this
}
var PubSubClass = function(context){
'use strict'
/* @preserve
-----------------------------------------------------------------------------------------------
JavaScript PubSub library
2012 (c) Willow Systems Corp (www.willow-systems.com)
based on Peter Higgins (dante@dojotoolkit.org)
Loosely based on Dojo publish/subscribe API, limited in scope. Rewritten blindly.
Original is (c) Dojo Foundation 2004-2010. Released under either AFL or new BSD, see:
http://dojofoundation.org/license for more information.
-----------------------------------------------------------------------------------------------
*/
this.topics = {}
// here we choose what will be "this" for the called events.
// if context is defined, it's context. Else, 'this' is this instance of PubSub
this.context = context ? context : this
/**
* Allows caller to emit an event and pass arguments to event listeners.
* @public
* @function
* @param topic {String} Name of the channel on which to voice this event
* @param **arguments Any number of arguments you want to pass to the listeners of this event.
*/
this.publish = function(topic, arg1, arg2, etc) {
'use strict'
if (this.topics[topic]) {
var currentTopic = this.topics[topic]
, args = Array.prototype.slice.call(arguments, 1)
, toremove = []
, fn
, i, l
, pair
for (i = 0, l = currentTopic.length; i < l; i++) {
pair = currentTopic[i] // this is a [function, once_flag] array
fn = pair[0]
if (pair[1] /* 'run once' flag set */){
pair[0] = function(){}
toremove.push(i)
}
fn.apply(this.context, args)
}
for (i = 0, l = toremove.length; i < l; i++) {
currentTopic.splice(toremove[i], 1)
}
}
}
/**
* Allows listener code to subscribe to channel and be called when data is available
* @public
* @function
* @param topic {String} Name of the channel on which to voice this event
* @param callback {Function} Executable (function pointer) that will be ran when event is voiced on this channel.
* @param once {Boolean} (optional. False by default) Flag indicating if the function is to be triggered only once.
* @returns {Object} A token object that cen be used for unsubscribing.
*/
this.subscribe = function(topic, callback, once) {
'use strict'
if (!this.topics[topic]) {
this.topics[topic] = [[callback, once]];
} else {
this.topics[topic].push([callback,once]);
}
return {
"topic": topic,
"callback": callback
};
};
/**
* Allows listener code to unsubscribe from a channel
* @public
* @function
* @param token {Object} A token object that was returned by `subscribe` method
*/
this.unsubscribe = function(token) {
if (this.topics[token.topic]) {
var currentTopic = this.topics[token.topic]
for (var i = 0, l = currentTopic.length; i < l; i++) {
if (currentTopic[i][0] === token.callback) {
currentTopic.splice(i, 1)
}
}
}
}
}
/// Returns front, back and "decor" colors derived from element (as jQuery obj)
function getColors($e){
var tmp
, undef
, frontcolor = $e.css('color')
, backcolor
, e = $e[0]
var toOfDOM = false
while(e && !backcolor && !toOfDOM){
try{
tmp = $(e).css('background-color')
} catch (ex) {
tmp = 'transparent'
}
if (tmp !== 'transparent' && tmp !== 'rgba(0, 0, 0, 0)'){
backcolor = tmp
}
toOfDOM = e.body
e = e.parentNode
}
var rgbaregex = /rgb[a]*\((\d+),\s*(\d+),\s*(\d+)/ // modern browsers
, hexregex = /#([AaBbCcDdEeFf\d]{2})([AaBbCcDdEeFf\d]{2})([AaBbCcDdEeFf\d]{2})/ // IE 8 and less.
, frontcolorcomponents
// Decomposing Front color into R, G, B ints
tmp = undef
tmp = frontcolor.match(rgbaregex)
if (tmp){
frontcolorcomponents = {'r':parseInt(tmp[1],10),'g':parseInt(tmp[2],10),'b':parseInt(tmp[3],10)}
} else {
tmp = frontcolor.match(hexregex)
if (tmp) {
frontcolorcomponents = {'r':parseInt(tmp[1],16),'g':parseInt(tmp[2],16),'b':parseInt(tmp[3],16)}
}
}
// if(!frontcolorcomponents){
// frontcolorcomponents = {'r':255,'g':255,'b':255}
// }
var backcolorcomponents
// Decomposing back color into R, G, B ints
if(!backcolor){
// HIghly unlikely since this means that no background styling was applied to any element from here to top of dom.
// we'll pick up back color from front color
if(frontcolorcomponents){
if (Math.max.apply(null, [frontcolorcomponents.r, frontcolorcomponents.g, frontcolorcomponents.b]) > 127){
backcolorcomponents = {'r':0,'g':0,'b':0}
} else {
backcolorcomponents = {'r':255,'g':255,'b':255}
}
} else {
// arg!!! front color is in format we don't understand (hsl, named colors)
// Let's just go with white background.
backcolorcomponents = {'r':255,'g':255,'b':255}
}
} else {
tmp = undef
tmp = backcolor.match(rgbaregex)
if (tmp){
backcolorcomponents = {'r':parseInt(tmp[1],10),'g':parseInt(tmp[2],10),'b':parseInt(tmp[3],10)}
} else {
tmp = backcolor.match(hexregex)
if (tmp) {
backcolorcomponents = {'r':parseInt(tmp[1],16),'g':parseInt(tmp[2],16),'b':parseInt(tmp[3],16)}
}
}
// if(!backcolorcomponents){
// backcolorcomponents = {'r':0,'g':0,'b':0}
// }
}
// Deriving Decor color
// THis is LAZY!!!! Better way would be to use HSL and adjust luminocity. However, that could be an overkill.
var toRGBfn = function(o){return 'rgb(' + [o.r, o.g, o.b].join(', ') + ')'}
, decorcolorcomponents
, frontcolorbrightness
, adjusted
if (frontcolorcomponents && backcolorcomponents){
var backcolorbrightness = Math.max.apply(null, [frontcolorcomponents.r, frontcolorcomponents.g, frontcolorcomponents.b])
frontcolorbrightness = Math.max.apply(null, [backcolorcomponents.r, backcolorcomponents.g, backcolorcomponents.b])
adjusted = Math.round(frontcolorbrightness + (-1 * (frontcolorbrightness - backcolorbrightness) * 0.75)) // "dimming" the difference between pen and back.
decorcolorcomponents = {'r':adjusted,'g':adjusted,'b':adjusted} // always shade of gray
} else if (frontcolorcomponents) {
frontcolorbrightness = Math.max.apply(null, [frontcolorcomponents.r, frontcolorcomponents.g, frontcolorcomponents.b])
var polarity = +1
if (frontcolorbrightness > 127){
polarity = -1
}
// shifting by 25% (64 points on RGB scale)
adjusted = Math.round(frontcolorbrightness + (polarity * 96)) // "dimming" the pen's color by 75% to get decor color.
decorcolorcomponents = {'r':adjusted,'g':adjusted,'b':adjusted} // always shade of gray
} else {
decorcolorcomponents = {'r':191,'g':191,'b':191} // always shade of gray
}
return {
'color': frontcolor
, 'background-color': backcolorcomponents? toRGBfn(backcolorcomponents) : backcolor
, 'decor-color': toRGBfn(decorcolorcomponents)
}
}
function Vector(x,y){
this.x = x
this.y = y
this.reverse = function(){
return new this.constructor(
this.x * -1
, this.y * -1
)
}
this._length = null
this.getLength = function(){
if (!this._length){
this._length = Math.sqrt( Math.pow(this.x, 2) + Math.pow(this.y, 2) )
}
return this._length
}
var polarity = function (e){
return Math.round(e / Math.abs(e))
}
this.resizeTo = function(length){
// proportionally changes x,y such that the hypotenuse (vector length) is = new length
if (this.x === 0 && this.y === 0){
this._length = 0
} else if (this.x === 0){
this._length = length
this.y = length * polarity(this.y)
} else if(this.y === 0){
this._length = length
this.x = length * polarity(this.x)
} else {
var proportion = Math.abs(this.y / this.x)
, x = Math.sqrt(Math.pow(length, 2) / (1 + Math.pow(proportion, 2)))
, y = proportion * x
this._length = length
this.x = x * polarity(this.x)
this.y = y * polarity(this.y)
}
return this
}
/**
* Calculates the angle between 'this' vector and another.
* @public
* @function
* @returns {Number} The angle between the two vectors as measured in PI.
*/
this.angleTo = function(vectorB) {
var divisor = this.getLength() * vectorB.getLength()
if (divisor === 0) {
return 0
} else {
// JavaScript floating point math is screwed up.
// because of it, the core of the formula can, on occasion, have values
// over 1.0 and below -1.0.
return Math.acos(
Math.min(
Math.max(
( this.x * vectorB.x + this.y * vectorB.y ) / divisor
, -1.0
)
, 1.0
)
) / Math.PI
}
}
}
function Point(x,y){
this.x = x
this.y = y
this.getVectorToCoordinates = function (x, y) {
return new Vector(x - this.x, y - this.y)
}
this.getVectorFromCoordinates = function (x, y) {
return this.getVectorToCoordinates(x, y).reverse()
}
this.getVectorToPoint = function (point) {
return new Vector(point.x - this.x, point.y - this.y)
}
this.getVectorFromPoint = function (point) {
return this.getVectorToPoint(point).reverse()
}
}
/*
* About data structure:
* We don't store / deal with "pictures" this signature capture code captures "vectors"
*
* We don't store bitmaps. We store "strokes" as arrays of arrays. (Actually, arrays of objects containing arrays of coordinates.
*
* Stroke = mousedown + mousemoved * n (+ mouseup but we don't record that as that was the "end / lack of movement" indicator)
*
* Vectors = not classical vectors where numbers indicated shift relative last position. Our vectors are actually coordinates against top left of canvas.
* we could calc the classical vectors, but keeping the the actual coordinates allows us (through Math.max / min)
* to calc the size of resulting drawing very quickly. If we want classical vectors later, we can always get them in backend code.
*
* So, the data structure:
*
* var data = [
* { // stroke starts
* x : [101, 98, 57, 43] // x points
* , y : [1, 23, 65, 87] // y points
* } // stroke ends
* , { // stroke starts
* x : [55, 56, 57, 58] // x points
* , y : [101, 97, 54, 4] // y points
* } // stroke ends
* , { // stroke consisting of just a dot
* x : [53] // x points
* , y : [151] // y points
* } // stroke ends
* ]
*
* we don't care or store stroke width (it's canvas-size-relative), color, shadow values. These can be added / changed on whim post-capture.
*
*/
function DataEngine(storageObject, context, startStrokeFn, addToStrokeFn, endStrokeFn){
this.data = storageObject // we expect this to be an instance of Array
this.context = context
if (storageObject.length){
// we have data to render
var numofstrokes = storageObject.length
, stroke
, numofpoints
for (var i = 0; i < numofstrokes; i++){
stroke = storageObject[i]
numofpoints = stroke.x.length
startStrokeFn.call(context, stroke)
for(var j = 1; j < numofpoints; j++){
addToStrokeFn.call(context, stroke, j)
}
endStrokeFn.call(context, stroke)
}
}
this.changed = function(){}
this.startStrokeFn = startStrokeFn
this.addToStrokeFn = addToStrokeFn
this.endStrokeFn = endStrokeFn
this.inStroke = false
this._lastPoint = null
this._stroke = null
this.startStroke = function(point){
if(point && typeof(point.x) == "number" && typeof(point.y) == "number"){
this._stroke = {'x':[point.x], 'y':[point.y]}
this.data.push(this._stroke)
this._lastPoint = point
this.inStroke = true
// 'this' does not work same inside setTimeout(
var stroke = this._stroke
, fn = this.startStrokeFn
, context = this.context
setTimeout(
// some IE's don't support passing args per setTimeout API. Have to create closure every time instead.
function() {fn.call(context, stroke)}
, 3
)
return point
} else {
return null
}
}
// that "5" at the very end of this if is important to explain.
// we do NOT render links between two captured points (in the middle of the stroke) if the distance is shorter than that number.
// not only do we NOT render it, we also do NOT capture (add) these intermediate points to storage.
// when clustering of these is too tight, it produces noise on the line, which, because of smoothing, makes lines too curvy.
// maybe, later, we can expose this as a configurable setting of some sort.
this.addToStroke = function(point){
if (this.inStroke &&
typeof(point.x) === "number" &&
typeof(point.y) === "number" &&
// calculates absolute shift in diagonal pixels away from original point
(Math.abs(point.x - this._lastPoint.x) + Math.abs(point.y - this._lastPoint.y)) > 4
){
var positionInStroke = this._stroke.x.length
this._stroke.x.push(point.x)
this._stroke.y.push(point.y)
this._lastPoint = point
var stroke = this._stroke
, fn = this.addToStrokeFn
, context = this.context
setTimeout(
// some IE's don't support passing args per setTimeout API. Have to create closure every time instead.
function() {fn.call(context, stroke, positionInStroke)}
, 3
)
return point
} else {
return null
}
}
this.endStroke = function(){
var c = this.inStroke
this.inStroke = false
this._lastPoint = null
if (c){
var stroke = this._stroke
, fn = this.endStrokeFn // 'this' does not work same inside setTimeout(
, context = this.context
, changedfn = this.changed
setTimeout(
// some IE's don't support passing args per setTimeout API. Have to create closure every time instead.
function(){
fn.call(context, stroke)
changedfn.call(context)
}
, 3
)
return true
} else {
return null
}
}
}
var basicDot = function(ctx, x, y, size){
var fillStyle = ctx.fillStyle
ctx.fillStyle = ctx.strokeStyle
ctx.fillRect(x + size / -2 , y + size / -2, size, size)
ctx.fillStyle = fillStyle
}
, basicLine = function(ctx, startx, starty, endx, endy){
ctx.beginPath()
ctx.moveTo(startx, starty)
ctx.lineTo(endx, endy)
ctx.stroke()
}
, basicCurve = function(ctx, startx, starty, endx, endy, cp1x, cp1y, cp2x, cp2y){
ctx.beginPath()
ctx.moveTo(startx, starty)
ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, endx, endy)
ctx.stroke()
}
, strokeStartCallback = function(stroke) {
// this = jSignatureClass instance
basicDot(this.canvasContext, stroke.x[0], stroke.y[0], this.settings.lineWidth)
}
, strokeAddCallback = function(stroke, positionInStroke){
// this = jSignatureClass instance
// Because we are funky this way, here we draw TWO curves.
// 1. POSSIBLY "this line" - spanning from point right before us, to this latest point.
// 2. POSSIBLY "prior curve" - spanning from "latest point" to the one before it.
// Why you ask?
// long lines (ones with many pixels between them) do not look good when they are part of a large curvy stroke.
// You know, the jaggedy crocodile spine instead of a pretty, smooth curve. Yuck!
// We want to approximate pretty curves in-place of those ugly lines.
// To approximate a very nice curve we need to know the direction of line before and after.
// Hence, on long lines we actually wait for another point beyond it to come back from
// mousemoved before we draw this curve.
// So for "prior curve" to be calc'ed we need 4 points
// A, B, C, D (we are on D now, A is 3 points in the past.)
// and 3 lines:
// pre-line (from points A to B),
// this line (from points B to C), (we call it "this" because if it was not yet, it's the only one we can draw for sure.)
// post-line (from points C to D) (even through D point is 'current' we don't know how we can draw it yet)
//
// Well, actually, we don't need to *know* the point A, just the vector A->B
var Cpoint = new Point(stroke.x[positionInStroke-1], stroke.y[positionInStroke-1])
, Dpoint = new Point(stroke.x[positionInStroke], stroke.y[positionInStroke])
, CDvector = Cpoint.getVectorToPoint(Dpoint)
// Again, we have a chance here to draw TWO things:
// BC Curve (only if it's long, because if it was short, it was drawn by previous callback) and
// CD Line (only if it's short)
// So, let's start with BC curve.
// if there is only 2 points in stroke array, we don't have "history" long enough to have point B, let alone point A.
// Falling through to drawing line CD is proper, as that's the only line we have points for.
if(positionInStroke > 1) {
// we are here when there are at least 3 points in stroke array.
var Bpoint = new Point(stroke.x[positionInStroke-2], stroke.y[positionInStroke-2])
, BCvector = Bpoint.getVectorToPoint(Cpoint)
, ABvector
if(BCvector.getLength() > this.lineCurveThreshold){
// Yey! Pretty curves, here we come!
if(positionInStroke > 2) {
// we are here when at least 4 points in stroke array.
ABvector = (new Point(stroke.x[positionInStroke-3], stroke.y[positionInStroke-3])).getVectorToPoint(Bpoint)
} else {
ABvector = new Vector(0,0)
}
var minlenfraction = 0.05
, maxlen = BCvector.getLength() * 0.35
, ABCangle = BCvector.angleTo(ABvector.reverse())
, BCDangle = CDvector.angleTo(BCvector.reverse())
, BCP1vector = new Vector(ABvector.x + BCvector.x, ABvector.y + BCvector.y).resizeTo(
Math.max(minlenfraction, ABCangle) * maxlen
)
, CCP2vector = (new Vector(BCvector.x + CDvector.x, BCvector.y + CDvector.y)).reverse().resizeTo(
Math.max(minlenfraction, BCDangle) * maxlen
)
basicCurve(
this.canvasContext
, Bpoint.x
, Bpoint.y
, Cpoint.x
, Cpoint.y
, Bpoint.x + BCP1vector.x
, Bpoint.y + BCP1vector.y
, Cpoint.x + CCP2vector.x
, Cpoint.y + CCP2vector.y
)
}
}
if(CDvector.getLength() <= this.lineCurveThreshold){
basicLine(
this.canvasContext
, Cpoint.x
, Cpoint.y
, Dpoint.x
, Dpoint.y
)
}
}
, strokeEndCallback = function(stroke){
// this = jSignatureClass instance
// Here we tidy up things left unfinished in last strokeAddCallback run.
// What's POTENTIALLY left unfinished there is the curve between the last points
// in the stroke, if the len of that line is more than lineCurveThreshold
// If the last line was shorter than lineCurveThreshold, it was drawn there, and there
// is nothing for us here to do.
// We can also be called when there is only one point in the stroke (meaning, the
// stroke was just a dot), in which case, again, there is nothing for us to do.
// So for "this curve" to be calc'ed we need 3 points
// A, B, C
// and 2 lines:
// pre-line (from points A to B),
// this line (from points B to C)
// Well, actually, we don't need to *know* the point A, just the vector A->B
// so, we really need points B, C and AB vector.
var positionInStroke = stroke.x.length - 1
if (positionInStroke > 0){
// there are at least 2 points in the stroke.we are in business.
var Cpoint = new Point(stroke.x[positionInStroke], stroke.y[positionInStroke])
, Bpoint = new Point(stroke.x[positionInStroke-1], stroke.y[positionInStroke-1])
, BCvector = Bpoint.getVectorToPoint(Cpoint)
, ABvector
if (BCvector.getLength() > this.lineCurveThreshold){
// yep. This one was left undrawn in prior callback. Have to draw it now.
if (positionInStroke > 1){
// we have at least 3 elems in stroke
ABvector = (new Point(stroke.x[positionInStroke-2], stroke.y[positionInStroke-2])).getVectorToPoint(Bpoint)
var BCP1vector = new Vector(ABvector.x + BCvector.x, ABvector.y + BCvector.y).resizeTo(BCvector.getLength() / 2)
basicCurve(
this.canvasContext
, Bpoint.x
, Bpoint.y
, Cpoint.x
, Cpoint.y
, Bpoint.x + BCP1vector.x
, Bpoint.y + BCP1vector.y
, Cpoint.x
, Cpoint.y
)
} else {
// Since there is no AB leg, there is no curve to draw. This line is still "long" but no curve.
basicLine(
this.canvasContext
, Bpoint.x
, Bpoint.y
, Cpoint.x
, Cpoint.y
)
}
}
}
}
/*
var getDataStats = function(){
var strokecnt = strokes.length
, stroke
, pointid
, pointcnt
, x, y
, maxX = Number.NEGATIVE_INFINITY
, maxY = Number.NEGATIVE_INFINITY
, minX = Number.POSITIVE_INFINITY
, minY = Number.POSITIVE_INFINITY
for(strokeid = 0; strokeid < strokecnt; strokeid++){
stroke = strokes[strokeid]
pointcnt = stroke.length
for(pointid = 0; pointid < pointcnt; pointid++){
x = stroke.x[pointid]
y = stroke.y[pointid]
if (x > maxX){
maxX = x
} else if (x < minX) {
minX = x
}
if (y > maxY){
maxY = y
} else if (y < minY) {
minY = y
}
}
}
return {'maxX': maxX, 'minX': minX, 'maxY': maxY, 'minY': minY}
}
*/
function conditionallyLinkCanvasResizeToWindowResize(jSignatureInstance, settingsWidth, apinamespace, globalEvents){
'use strict'
if ( settingsWidth === 'ratio' || settingsWidth.split('')[settingsWidth.length - 1] === '%' ) {
this.eventTokens[apinamespace + '.parentresized'] = globalEvents.subscribe(
apinamespace + '.parentresized'
, (function(eventTokens, $parent, originalParentWidth, sizeRatio){
'use strict'
return function(){
'use strict'
var w = $parent.width()
if (w !== originalParentWidth) {
// UNsubscribing this particular instance of signature pad only.
// there is a separate `eventTokens` per each instance of signature pad
for (var key in eventTokens){
if (eventTokens.hasOwnProperty(key)) {
globalEvents.unsubscribe(eventTokens[key])
delete eventTokens[key]
}
}
var settings = jSignatureInstance.settings
jSignatureInstance.$parent.children().remove()
for (var key in jSignatureInstance){
if (jSignatureInstance.hasOwnProperty(key)) {
delete jSignatureInstance[key]
}
}
// scale data to new signature pad size
settings.data = (function(data, scale){
var newData = []
var o, i, l, j, m, stroke
for ( i = 0, l = data.length; i < l; i++) {
stroke = data[i]
o = {'x':[],'y':[]}
for ( j = 0, m = stroke.x.length; j < m; j++) {
o.x.push(stroke.x[j] * scale)
o.y.push(stroke.y[j] * scale)
}
newData.push(o)
}
return newData
})(
settings.data
, w * 1.0 / originalParentWidth
)
$parent[apinamespace](settings)
}
}
})(
this.eventTokens
, this.$parent
, this.$parent.width()
, this.canvas.width * 1.0 / this.canvas.height
)
)
}
}
function jSignatureClass(parent, options, instanceExtensions) {
var $parent = this.$parent = $(parent)
, eventTokens = this.eventTokens = {}
, events = this.events = new PubSubClass(this)
, globalEvents = $.fn[apinamespace]('globalEvents')
, settings = {
'width' : 'ratio'
,'height' : 'ratio'
,'sizeRatio': 4 // only used when height = 'ratio'
,'color' : '#000'
,'background-color': '#fff'
,'decor-color': '#eee'
,'lineWidth' : 0
,'minFatFingerCompensation' : -10
,'showUndoButton': false
,'data': []
}
$.extend(settings, getColors($parent))
if (options) {
$.extend(settings, options)
}
this.settings = settings
for (var extensionName in instanceExtensions){
if (instanceExtensions.hasOwnProperty(extensionName)) {
instanceExtensions[extensionName].call(this, extensionName)
}
}
this.events.publish(apinamespace+'.initializing')
// these, when enabled, will hover above the sig area. Hence we append them to DOM before canvas.
this.$controlbarUpper = (function(){
var controlbarstyle = 'padding:0 !important;margin:0 !important;'+
'width: 100% !important; height: 0 !important;'+
'margin-top:-1em !important;margin-bottom:1em !important;'
return $('<div style="'+controlbarstyle+'"></div>').appendTo($parent)
})();
this.isCanvasEmulator = false // will be flipped by initializer when needed.
var canvas = this.canvas = this.initializeCanvas(settings)
, $canvas = $(canvas)
this.$controlbarLower = (function(){
var controlbarstyle = 'padding:0 !important;margin:0 !important;'+
'width: 100% !important; height: 0 !important;'+
'margin-top:-1.5em !important;margin-bottom:1.5em !important;'
return $('<div style="'+controlbarstyle+'"></div>').appendTo($parent)
})();
this.canvasContext = canvas.getContext("2d")
// Most of our exposed API will be looking for this:
$canvas.data(apinamespace + '.this', this)
settings.lineWidth = (function(defaultLineWidth, canvasWidth){
if (!defaultLineWidth){
return Math.max(
Math.round(canvasWidth / 400) /*+1 pixel for every extra 300px of width.*/
, 2 /* minimum line width */
)
} else {
return defaultLineWidth
}
})(settings.lineWidth, canvas.width);
this.lineCurveThreshold = settings.lineWidth * 3
// Add custom class if defined
if(settings.cssclass && $.trim(settings.cssclass) != "") {
$canvas.addClass(settings.cssclass)
}
// used for shifting the drawing point up on touch devices, so one can see the drawing above the finger.
this.fatFingerCompensation = 0
var movementHandlers = (function(jSignatureInstance) {
//================================
// mouse down, move, up handlers:
// shifts - adjustment values in viewport pixels drived from position of canvas on the page
var shiftX
, shiftY
, setStartValues = function(){
var tos = $(jSignatureInstance.canvas).offset()
shiftX = tos.left * -1
shiftY = tos.top * -1
}
, getPointFromEvent = function(e) {
var firstEvent = (e.changedTouches && e.changedTouches.length > 0 ? e.changedTouches[0] : e)
// All devices i tried report correct coordinates in pageX,Y
// Android Chrome 2.3.x, 3.1, 3.2., Opera Mobile, safari iOS 4.x,
// Windows: Chrome, FF, IE9, Safari
// None of that scroll shift calc vs screenXY other sigs do is needed.
// ... oh, yeah, the "fatFinger.." is for tablets so that people see what they draw.
return new Point(
Math.round(firstEvent.pageX + shiftX)
, Math.round(firstEvent.pageY + shiftY) + jSignatureInstance.fatFingerCompensation
)
}
, timer = new KickTimerClass(
750
, function() { jSignatureInstance.dataEngine.endStroke() }
)
this.drawEndHandler = function(e) {
try { e.preventDefault() } catch (ex) {}
timer.clear()
jSignatureInstance.dataEngine.endStroke()
}
this.drawStartHandler = function(e) {
e.preventDefault()
// for performance we cache the offsets
// we recalc these only at the beginning the stroke
setStartValues()
jSignatureInstance.dataEngine.startStroke( getPointFromEvent(e) )
timer.kick()
}
this.drawMoveHandler = function(e) {
e.preventDefault()
if (!jSignatureInstance.dataEngine.inStroke){
return
}
jSignatureInstance.dataEngine.addToStroke( getPointFromEvent(e) )
timer.kick()
}
return this
}).call( {}, this )
//
//================================
;(function(drawEndHandler, drawStartHandler, drawMoveHandler) {
var canvas = this.canvas
, $canvas = $(canvas)
, undef
if (this.isCanvasEmulator){
$canvas.bind('mousemove.'+apinamespace, drawMoveHandler)
$canvas.bind('mouseup.'+apinamespace, drawEndHandler)
$canvas.bind('mousedown.'+apinamespace, drawStartHandler)
} else {
canvas.ontouchstart = function(e) {
canvas.onmousedown = undef
canvas.onmouseup = undef
canvas.onmousemove = undef
this.fatFingerCompensation = (
settings.minFatFingerCompensation &&
settings.lineWidth * -3 > settings.minFatFingerCompensation
) ? settings.lineWidth * -3 : settings.minFatFingerCompensation
drawStartHandler(e)
canvas.ontouchend = drawEndHandler
canvas.ontouchstart = drawStartHandler
canvas.ontouchmove = drawMoveHandler
}
canvas.onmousedown = function(e) {
canvas.ontouchstart = undef
canvas.ontouchend = undef
canvas.ontouchmove = undef
drawStartHandler(e)
canvas.onmousedown = drawStartHandler
canvas.onmouseup = drawEndHandler
canvas.onmousemove = drawMoveHandler
}
}
}).call(
this
, movementHandlers.drawEndHandler
, movementHandlers.drawStartHandler
, movementHandlers.drawMoveHandler
)
//=========================================
// various event handlers
// on mouseout + mouseup canvas did not know that mouseUP fired. Continued to draw despite mouse UP.
// it is bettr than
// $canvas.bind('mouseout', drawEndHandler)
// because we don't want to break the stroke where user accidentally gets ouside and wants to get back in quickly.
eventTokens[apinamespace + '.windowmouseup'] = globalEvents.subscribe(
apinamespace + '.windowmouseup'
, movementHandlers.drawEndHandler
)
this.events.publish(apinamespace+'.attachingEventHandlers')
// If we have proportional width, we sign up to events broadcasting "window resized" and checking if
// parent's width changed. If so, we (1) extract settings + data from current signature pad,
// (2) remove signature pad from parent, and (3) reinit new signature pad at new size with same settings, (rescaled) data.
conditionallyLinkCanvasResizeToWindowResize.call(
this
, this
, settings.width.toString(10)
, apinamespace, globalEvents
)
// end of event handlers.
// ===============================
this.resetCanvas(settings.data)
// resetCanvas renders the data on the screen and fires ONE "change" event
// if there is data. If you have controls that rely on "change" firing
// attach them to something that runs before this.resetCanvas, like
// apinamespace+'.attachingEventHandlers' that fires a bit higher.
this.events.publish(apinamespace+'.initialized')
return this
} // end of initBase
//=========================================================================
// jSignatureClass's methods and supporting fn's
jSignatureClass.prototype.resetCanvas = function(data){
var canvas = this.canvas
, settings = this.settings
, ctx = this.canvasContext
, isCanvasEmulator = this.isCanvasEmulator
, cw = canvas.width
, ch = canvas.height
// preparing colors, drawing area
ctx.clearRect(0, 0, cw + 30, ch + 30)
ctx.shadowColor = ctx.fillStyle = settings['background-color']
if (isCanvasEmulator){
// FLashCanvas fills with Black by default, covering up the parent div's background
// hence we refill
ctx.fillRect(0,0,cw + 30, ch + 30)
}
ctx.lineWidth = Math.ceil(parseInt(settings.lineWidth, 10))
ctx.lineCap = ctx.lineJoin = "round"
// signature line
ctx.strokeStyle = settings['decor-color']
ctx.shadowOffsetX = 0
ctx.shadowOffsetY = 0
var lineoffset = Math.round( ch / 5 )
basicLine(ctx, lineoffset * 1.5, ch - lineoffset, cw - (lineoffset * 1.5), ch - lineoffset)
ctx.strokeStyle = settings.color
if (!isCanvasEmulator){
ctx.shadowColor = ctx.strokeStyle
ctx.shadowOffsetX = ctx.lineWidth * 0.5
ctx.shadowOffsetY = ctx.lineWidth * -0.6
ctx.shadowBlur = 0
}
// setting up new dataEngine
if (!data) { data = [] }
var dataEngine = this.dataEngine = new DataEngine(
data
, this
, strokeStartCallback
, strokeAddCallback
, strokeEndCallback
)
settings.data = data // onwindowresize handler uses it, i think.
$(canvas).data(apinamespace+'.data', data)
.data(apinamespace+'.settings', settings)
// we fire "change" event on every change in data.
// setting this up:
dataEngine.changed = (function(target, events, apinamespace) {
'use strict'
return function() {
events.publish(apinamespace+'.change')
target.trigger('change')
}