hjg
2024-10-30 8cf23534166c07e711aac2a25911ada317ba01f0
提交 | 用户 | 时间
58d006 1 /*!jQuery Knob*/
A 2 /**
3  * Downward compatible, touchable dial
4  *
5  * Version: 1.2.0 (15/07/2012)
6  * Requires: jQuery v1.7+
7  *
8  * Copyright (c) 2012 Anthony Terrien
9  * Under MIT and GPL licenses:
10  *  http://www.opensource.org/licenses/mit-license.php
11  *  http://www.gnu.org/licenses/gpl.html
12  *
13  * Thanks to vor, eskimoblood, spiffistan, FabrizioC
14  */
15 (function($) {
16
17     /**
18      * Kontrol library
19      */
20     "use strict";
21
22     /**
23      * Definition of globals and core
24      */
25     var k = {}, // kontrol
26         max = Math.max,
27         min = Math.min;
28
29     k.c = {};
30     k.c.d = $(document);
31     k.c.t = function (e) {
32         return e.originalEvent.touches.length - 1;
33     };
34
35     /**
36      * Kontrol Object
37      *
38      * Definition of an abstract UI control
39      *
40      * Each concrete component must call this one.
41      * <code>
42      * k.o.call(this);
43      * </code>
44      */
45     k.o = function () {
46         var s = this;
47
48         this.o = null; // array of options
49         this.$ = null; // jQuery wrapped element
50         this.i = null; // mixed HTMLInputElement or array of HTMLInputElement
51         this.g = null; // deprecated 2D graphics context for 'pre-rendering'
52         this.v = null; // value ; mixed array or integer
53         this.cv = null; // change value ; not commited value
54         this.x = 0; // canvas x position
55         this.y = 0; // canvas y position
56         this.w = 0; // canvas width
57         this.h = 0; // canvas height
58         this.$c = null; // jQuery canvas element
59         this.c = null; // rendered canvas context
60         this.t = 0; // touches index
61         this.isInit = false;
62         this.fgColor = null; // main color
63         this.pColor = null; // previous color
64         this.dH = null; // draw hook
65         this.cH = null; // change hook
66         this.eH = null; // cancel hook
67         this.rH = null; // release hook
68         this.scale = 1; // scale factor
69         this.relative = false;
70         this.relativeWidth = false;
71         this.relativeHeight = false;
72         this.$div = null; // component div
73
74         this.run = function () {
75             var cf = function (e, conf) {
76                 var k;
77                 for (k in conf) {
78                     s.o[k] = conf[k];
79                 }
80                 s.init();
81                 s._configure()
82                  ._draw();
83             };
84
85             if(this.$.data('kontroled')) return;
86             this.$.data('kontroled', true);
87
88             this.extend();
89             this.o = $.extend(
90                 {
91                     // Config
92                     min : this.$.data('min') || 0,
93                     max : this.$.data('max') || 100,
94                     stopper : true,
95                     readOnly : this.$.data('readonly'),
96
97                     // UI
98                     cursor : (this.$.data('cursor') === true && 30)
99                                 || this.$.data('cursor')
100                                 || 0,
101                     thickness : this.$.data('thickness') || 0.35,
102                     lineCap : this.$.data('linecap') || 'butt',
103                     width : this.$.data('width') || 200,
104                     height : this.$.data('height') || 200,
105                     displayInput : this.$.data('displayinput') == null || this.$.data('displayinput'),
106                     displayPrevious : this.$.data('displayprevious'),
107                     fgColor : this.$.data('fgcolor') || '#87CEEB',
108                     inputColor: this.$.data('inputcolor') || this.$.data('fgcolor') || '#87CEEB',
109                     font: this.$.data('font') || 'Arial',
110                     fontWeight: this.$.data('font-weight') || 'bold',
111                     inline : false,
112                     step : this.$.data('step') || 1,
113
114                     // Hooks
115                     draw : null, // function () {}
116                     change : null, // function (value) {}
117                     cancel : null, // function () {}
118                     release : null, // function (value) {}
119                     error : null // function () {}
120                 }, this.o
121             );
122
123             // routing value
124             if(this.$.is('fieldset')) {
125
126                 // fieldset = array of integer
127                 this.v = {};
128                 this.i = this.$.find('input')
129                 this.i.each(function(k) {
130                     var $this = $(this);
131                     s.i[k] = $this;
132                     s.v[k] = $this.val();
133
134                     $this.bind(
135                         'change'
136                         , function () {
137                             var val = {};
138                             val[k] = $this.val();
139                             s.val(val);
140                         }
141                     );
142                 });
143                 this.$.find('legend').remove();
144
145             } else {
146
147                 // input = integer
148                 this.i = this.$;
149                 this.v = this.$.val();
150                 (this.v == '') && (this.v = this.o.min);
151
152                 this.$.bind(
153                     'change'
154                     , function () {
155                         s.val(s._validate(s.$.val()));
156                     }
157                 );
158
159             }
160
161             (!this.o.displayInput) && this.$.hide();
162
163             // adds needed DOM elements (canvas, div)
164             this.$c = $(document.createElement('canvas'));
165             if (typeof G_vmlCanvasManager !== 'undefined') {
166               G_vmlCanvasManager.initElement(this.$c[0]);
167             }
168             this.c = this.$c[0].getContext ? this.$c[0].getContext('2d') : null;
169             if (!this.c) {
170                 this.o.error && this.o.error();
171                 return;
172             }
173
174             // hdpi support
175             this.scale = (window.devicePixelRatio || 1) /
176                         (
177                             this.c.webkitBackingStorePixelRatio ||
178                             this.c.mozBackingStorePixelRatio ||
179                             this.c.msBackingStorePixelRatio ||
180                             this.c.oBackingStorePixelRatio ||
181                             this.c.backingStorePixelRatio || 1
182                         );
183
184             // detects relative width / height
185             this.relativeWidth = ((this.o.width % 1 !== 0)
186                                     && this.o.width.indexOf('%'));
187             this.relativeHeight = ((this.o.height % 1 !== 0)
188                                     && this.o.height.indexOf('%'));
189
190             this.relative = (this.relativeWidth || this.relativeHeight);
191
192             // wraps all elements in a div
193             this.$div = $('<div style="'
194                         + (this.o.inline ? 'display:inline;' : '')
195                         + '"></div>');
196
197             this.$.wrap(this.$div).before(this.$c);
198             this.$div = this.$.parent();
199
200             // computes size and carves the component
201             this._carve();
202
203             // prepares props for transaction
204             if (this.v instanceof Object) {
205                 this.cv = {};
206                 this.copy(this.v, this.cv);
207             } else {
208                 this.cv = this.v;
209             }
210
211             // binds configure event
212             this.$
213                 .bind("configure", cf)
214                 .parent()
215                 .bind("configure", cf);
216
217             // finalize init
218             this._listen()
219                 ._configure()
220                 ._xy()
221                 .init();
222
223             this.isInit = true;
224
225             // the most important !
226             this._draw();
227
228             return this;
229         };
230
231         this._carve = function() {
232             if(this.relative) {
233                 var w = this.relativeWidth
234                             ? this.$div.parent().width()
235                                 * parseInt(this.o.width) / 100
236                             : this.$div.parent().width(),
237                     h = this.relativeHeight
238                             ? this.$div.parent().height()
239                                 * parseInt(this.o.height) / 100
240                             : this.$div.parent().height();
241
242                 // apply relative
243                 this.w = this.h = Math.min(w, h);
244             } else {
245                 this.w = this.o.width;
246                 this.h = this.o.height;
247             }
248
249             // finalize div
250             this.$div.css({
251                 'width': this.w + 'px',
252                 'height': this.h + 'px'
253             });
254
255             // finalize canvas with computed width
256             this.$c.attr({
257                 width: this.w,
258                 height: this.h
259             });
260
261             // scaling
262             if (this.scale !== 1) {
263                 this.$c[0].width = this.$c[0].width * this.scale;
264                 this.$c[0].height = this.$c[0].height * this.scale;
265                 this.$c.width(this.w);
266                 this.$c.height(this.h);
267             }
268
269             return this;
270         }
271
272         this._draw = function () {
273
274             // canvas pre-rendering
275             var d = true;
276
277             s.g = s.c;
278
279             s.clear();
280
281             s.dH
282             && (d = s.dH());
283
284             (d !== false) && s.draw();
285
286         };
287
288         this._touch = function (e) {
289
290             var touchMove = function (e) {
291
292                 var v = s.xy2val(
293                             e.originalEvent.touches[s.t].pageX,
294                             e.originalEvent.touches[s.t].pageY
295                             );
296
297                 if (v == s.cv) return;
298
299                 if (
300                     s.cH
301                     && (s.cH(v) === false)
302                 ) return;
303
304
305                 s.change(s._validate(v));
306                 s._draw();
307             };
308
309             // get touches index
310             this.t = k.c.t(e);
311
312             // First touch
313             touchMove(e);
314
315             // Touch events listeners
316             k.c.d
317                 .bind("touchmove.k", touchMove)
318                 .bind(
319                     "touchend.k"
320                     , function () {
321                         k.c.d.unbind('touchmove.k touchend.k');
322
323                         if (
324                             s.rH
325                             && (s.rH(s.cv) === false)
326                         ) return;
327
328                         s.val(s.cv);
329                     }
330                 );
331
332             return this;
333         };
334
335         this._mouse = function (e) {
336
337             var mouseMove = function (e) {
338                 var v = s.xy2val(e.pageX, e.pageY);
339                 if (v == s.cv) return;
340
341                 if (
342                     s.cH
343                     && (s.cH(v) === false)
344                 ) return;
345
346                 s.change(s._validate(v));
347                 s._draw();
348             };
349
350             // First click
351             mouseMove(e);
352
353             // Mouse events listeners
354             k.c.d
355                 .bind("mousemove.k", mouseMove)
356                 .bind(
357                     // Escape key cancel current change
358                     "keyup.k"
359                     , function (e) {
360                         if (e.keyCode === 27) {
361                             k.c.d.unbind("mouseup.k mousemove.k keyup.k");
362
363                             if (
364                                 s.eH
365                                 && (s.eH() === false)
366                             ) return;
367
368                             s.cancel();
369                         }
370                     }
371                 )
372                 .bind(
373                     "mouseup.k"
374                     , function (e) {
375                         k.c.d.unbind('mousemove.k mouseup.k keyup.k');
376
377                         if (
378                             s.rH
379                             && (s.rH(s.cv) === false)
380                         ) return;
381
382                         s.val(s.cv);
383                     }
384                 );
385
386             return this;
387         };
388
389         this._xy = function () {
390             var o = this.$c.offset();
391             this.x = o.left;
392             this.y = o.top;
393             return this;
394         };
395
396         this._listen = function () {
397
398             if (!this.o.readOnly) {
399                 this.$c
400                     .bind(
401                         "mousedown"
402                         , function (e) {
403                             e.preventDefault();
404                             s._xy()._mouse(e);
405                          }
406                     )
407                     .bind(
408                         "touchstart"
409                         , function (e) {
410                             e.preventDefault();
411                             s._xy()._touch(e);
412                          }
413                     );
414
415                 if(this.relative) {
416                     $(window).resize(function() {
417                         s._carve()
418                          .init();
419                         s._draw();
420                     });
421                 }
422
423                 this.listen();
424             } else {
425                 this.$.attr('readonly', 'readonly');
426             }
427
428             return this;
429         };
430
431         this._configure = function () {
432
433             // Hooks
434             if (this.o.draw) this.dH = this.o.draw;
435             if (this.o.change) this.cH = this.o.change;
436             if (this.o.cancel) this.eH = this.o.cancel;
437             if (this.o.release) this.rH = this.o.release;
438
439             if (this.o.displayPrevious) {
440                 this.pColor = this.h2rgba(this.o.fgColor, "0.4");
441                 this.fgColor = this.h2rgba(this.o.fgColor, "0.6");
442             } else {
443                 this.fgColor = this.o.fgColor;
444             }
445
446             return this;
447         };
448
449         this._clear = function () {
450             this.$c[0].width = this.$c[0].width;
451         };
452
453         this._validate = function(v) {
454             return (~~ (((v < 0) ? -0.5 : 0.5) + (v/this.o.step))) * this.o.step;
455         };
456
457         // Abstract methods
458         this.listen = function () {}; // on start, one time
459         this.extend = function () {}; // each time configure triggered
460         this.init = function () {}; // each time configure triggered
461         this.change = function (v) {}; // on change
462         this.val = function (v) {}; // on release
463         this.xy2val = function (x, y) {}; //
464         this.draw = function () {}; // on change / on release
465         this.clear = function () { this._clear(); };
466
467         // Utils
468         this.h2rgba = function (h, a) {
469             var rgb;
470             h = h.substring(1,7)
471             rgb = [parseInt(h.substring(0,2),16)
472                    ,parseInt(h.substring(2,4),16)
473                    ,parseInt(h.substring(4,6),16)];
474             return "rgba(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + "," + a + ")";
475         };
476
477         this.copy = function (f, t) {
478             for (var i in f) { t[i] = f[i]; }
479         };
480     };
481
482
483     /**
484      * k.Dial
485      */
486     k.Dial = function () {
487         k.o.call(this);
488
489         this.startAngle = null;
490         this.xy = null;
491         this.radius = null;
492         this.lineWidth = null;
493         this.cursorExt = null;
494         this.w2 = null;
495         this.PI2 = 2*Math.PI;
496
497         this.extend = function () {
498             this.o = $.extend(
499                 {
500                     bgColor : this.$.data('bgcolor') || '#EEEEEE',
501                     angleOffset : this.$.data('angleoffset') || 0,
502                     angleArc : this.$.data('anglearc') || 360,
503                     inline : true
504                 }, this.o
505             );
506         };
507
508         this.val = function (v) {
509             if (null != v) {
510                 this.cv = this.o.stopper ? max(min(v, this.o.max), this.o.min) : v;
511                 this.v = this.cv;
512                 this.$.val(this.v);
513                 this._draw();
514             } else {
515                 return this.v;
516             }
517         };
518
519         this.xy2val = function (x, y) {
520             var a, ret;
521
522             a = Math.atan2(
523                         x - (this.x + this.w2)
524                         , - (y - this.y - this.w2)
525                     ) - this.angleOffset;
526
527             if(this.angleArc != this.PI2 && (a < 0) && (a > -0.5)) {
528                 // if isset angleArc option, set to min if .5 under min
529                 a = 0;
530             } else if (a < 0) {
531                 a += this.PI2;
532             }
533
534             ret = ~~ (0.5 + (a * (this.o.max - this.o.min) / this.angleArc))
535                     + this.o.min;
536
537             this.o.stopper
538             && (ret = max(min(ret, this.o.max), this.o.min));
539
540             return ret;
541         };
542
543         this.listen = function () {
544             // bind MouseWheel
545             var s = this,
546                 mw = function (e) {
547                             e.preventDefault();
548                             var ori = e.originalEvent
549                                 ,deltaX = ori.detail || ori.wheelDeltaX
550                                 ,deltaY = ori.detail || ori.wheelDeltaY
551                                 ,v = parseInt(s.$.val()) + (deltaX>0 || deltaY>0 ? s.o.step : deltaX<0 || deltaY<0 ? -s.o.step : 0);
552
553                             if (
554                                 s.cH
555                                 && (s.cH(v) === false)
556                             ) return;
557
558                             s.val(v);
559                         }
560                 , kval, to, m = 1, kv = {37:-s.o.step, 38:s.o.step, 39:s.o.step, 40:-s.o.step};
561
562             this.$
563                 .bind(
564                     "keydown"
565                     ,function (e) {
566                         var kc = e.keyCode;
567
568                         // numpad support
569                         if(kc >= 96 && kc <= 105) {
570                             kc = e.keyCode = kc - 48;
571                         }
572
573                         kval = parseInt(String.fromCharCode(kc));
574
575                         if (isNaN(kval)) {
576
577                             (kc !== 13)         // enter
578                             && (kc !== 8)       // bs
579                             && (kc !== 9)       // tab
580                             && (kc !== 189)     // -
581                             && e.preventDefault();
582
583                             // arrows
584                             if ($.inArray(kc,[37,38,39,40]) > -1) {
585                                 e.preventDefault();
586
587                                 var v = parseInt(s.$.val()) + kv[kc] * m;
588
589                                 s.o.stopper
590                                 && (v = max(min(v, s.o.max), s.o.min));
591
592                                 s.change(v);
593                                 s._draw();
594
595                                 // long time keydown speed-up
596                                 to = window.setTimeout(
597                                     function () { m*=2; }
598                                     ,30
599                                 );
600                             }
601                         }
602                     }
603                 )
604                 .bind(
605                     "keyup"
606                     ,function (e) {
607                         if (isNaN(kval)) {
608                             if (to) {
609                                 window.clearTimeout(to);
610                                 to = null;
611                                 m = 1;
612                                 s.val(s.$.val());
613                             }
614                         } else {
615                             // kval postcond
616                             (s.$.val() > s.o.max && s.$.val(s.o.max))
617                             || (s.$.val() < s.o.min && s.$.val(s.o.min));
618                         }
619
620                     }
621                 );
622
623             this.$c.bind("mousewheel DOMMouseScroll", mw);
624             this.$.bind("mousewheel DOMMouseScroll", mw)
625         };
626
627         this.init = function () {
628
629             if (
630                 this.v < this.o.min
631                 || this.v > this.o.max
632             ) this.v = this.o.min;
633
634             this.$.val(this.v);
635             this.w2 = this.w / 2;
636             this.cursorExt = this.o.cursor / 100;
637             this.xy = this.w2 * this.scale;
638             this.lineWidth = this.xy * this.o.thickness;
639             this.lineCap = this.o.lineCap;
640             this.radius = this.xy - this.lineWidth / 2;
641
642             this.o.angleOffset
643             && (this.o.angleOffset = isNaN(this.o.angleOffset) ? 0 : this.o.angleOffset);
644
645             this.o.angleArc
646             && (this.o.angleArc = isNaN(this.o.angleArc) ? this.PI2 : this.o.angleArc);
647
648             // deg to rad
649             this.angleOffset = this.o.angleOffset * Math.PI / 180;
650             this.angleArc = this.o.angleArc * Math.PI / 180;
651
652             // compute start and end angles
653             this.startAngle = 1.5 * Math.PI + this.angleOffset;
654             this.endAngle = 1.5 * Math.PI + this.angleOffset + this.angleArc;
655
656             var s = max(
657                             String(Math.abs(this.o.max)).length
658                             , String(Math.abs(this.o.min)).length
659                             , 2
660                             ) + 2;
661
662             this.o.displayInput
663                 && this.i.css({
664                         'width' : ((this.w / 2 + 4) >> 0) + 'px'
665                         ,'height' : ((this.w / 3) >> 0) + 'px'
666                         ,'position' : 'absolute'
667                         ,'vertical-align' : 'middle'
668                         ,'margin-top' : ((this.w / 3) >> 0) + 'px'
669                         ,'margin-left' : '-' + ((this.w * 3 / 4 + 2) >> 0) + 'px'
670                         ,'border' : 0
671                         ,'background' : 'none'
672                         ,'font' : this.o.fontWeight + ' ' + ((this.w / s) >> 0) + 'px ' + this.o.font
673                         ,'text-align' : 'center'
674                         ,'color' : this.o.inputColor || this.o.fgColor
675                         ,'padding' : '0px'
676                         ,'-webkit-appearance': 'none'
677                         })
678                 || this.i.css({
679                         'width' : '0px'
680                         ,'visibility' : 'hidden'
681                         });
682         };
683
684         this.change = function (v) {
685             this.cv = v;
686             this.$.val(v);
687         };
688
689         this.angle = function (v) {
690             return (v - this.o.min) * this.angleArc / (this.o.max - this.o.min);
691         };
692
693         this.draw = function () {
694
695             var c = this.g,                 // context
696                 a = this.angle(this.cv)    // Angle
697                 , sat = this.startAngle     // Start angle
698                 , eat = sat + a             // End angle
699                 , sa, ea                    // Previous angles
700                 , r = 1;
701
702             c.lineWidth = this.lineWidth;
703
704             c.lineCap = this.lineCap;
705
706             this.o.cursor
707                 && (sat = eat - this.cursorExt)
708                 && (eat = eat + this.cursorExt);
709
710             c.beginPath();
711                 c.strokeStyle = this.o.bgColor;
712                 c.arc(this.xy, this.xy, this.radius, this.endAngle, this.startAngle, true);
713             c.stroke();
714
715             if (this.o.displayPrevious) {
716                 ea = this.startAngle + this.angle(this.v);
717                 sa = this.startAngle;
718                 this.o.cursor
719                     && (sa = ea - this.cursorExt)
720                     && (ea = ea + this.cursorExt);
721
722                 c.beginPath();
723                     c.strokeStyle = this.pColor;
724                     c.arc(this.xy, this.xy, this.radius, sa, ea, false);
725                 c.stroke();
726                 r = (this.cv == this.v);
727             }
728
729             c.beginPath();
730                 c.strokeStyle = r ? this.o.fgColor : this.fgColor ;
731                 c.arc(this.xy, this.xy, this.radius, sat, eat, false);
732             c.stroke();
733         };
734
735         this.cancel = function () {
736             this.val(this.v);
737         };
738     };
739
740     $.fn.dial = $.fn.knob = function (o) {
741         return this.each(
742             function () {
743                 var d = new k.Dial();
744                 d.o = o;
745                 d.$ = $(this);
746                 d.run();
747             }
748         ).parent();
749     };
750
751 })(jQuery);