/
flotr.humble2.js
4809 lines (4189 loc) · 163 KB
/
flotr.humble2.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
/* $Id: flotr.js 174 2010-12-14 19:33:33Z fabien.menager $ */
/**
* @projectDescription Flotr is a javascript plotting library based on the Prototype Javascript Framework.
* @author Bas Wenneker
* @license MIT License <http://www.opensource.org/licenses/mit-license.php>
* @version 0.2.0
*/
var Flotr = {
version: "0.2.0-alpha",
revision: ('$Revision: 174 $'.match(/(\d+)/) || [null,null])[1],
author: ['Bas Wenneker', 'Fabien Ménager'],
website: 'http://www.solutoire.com',
isIphone: /iphone/i.test(navigator.userAgent),
isIE9: document.documentMode == 9,
/**
* An object of the registered graph types. Use Flotr.addType(type, object)
* to add your own type.
*/
graphTypes: {},
/**
* The list of the registered plugins
*/
plugins: {},
/**
* Can be used to add your own chart type.
* @param {String} name - Type of chart, like 'pies', 'bars' etc.
* @param {String} graphType - The object containing the basic drawing functions (draw, etc)
*/
addType: function(name, graphType){
Flotr.graphTypes[name] = graphType;
Flotr.defaultOptions[name] = graphType.options || {};
Flotr.defaultOptions.defaultType = Flotr.defaultOptions.defaultType || name;
},
/**
* Can be used to add a plugin
* @param {String} name - The name of the plugin
* @param {String} plugin - The object containing the plugin's data (callbacks, options, function1, function2, ...)
*/
addPlugin: function(name, plugin){
Flotr.plugins[name] = plugin;
Flotr.defaultOptions[name] = plugin.options || {};
},
/**
* Draws the graph. This function is here for backwards compatibility with Flotr version 0.1.0alpha.
* You could also draw graphs by directly calling Flotr.Graph(element, data, options).
* @param {Element} el - element to insert the graph into
* @param {Object} data - an array or object of dataseries
* @param {Object} options - an object containing options
* @param {Class} _GraphKlass_ - (optional) Class to pass the arguments to, defaults to Flotr.Graph
* @return {Object} returns a new graph object and of course draws the graph.
*/
draw: function(el, data, options, GraphKlass){
GraphKlass = GraphKlass || Flotr.Graph;
return new GraphKlass(el, data, options);
},
/**
* Collects dataseries from input and parses the series into the right format. It returns an Array
* of Objects each having at least the 'data' key set.
* @param {Array, Object} data - Object or array of dataseries
* @return {Array} Array of Objects parsed into the right format ({(...,) data: [[x1,y1], [x2,y2], ...] (, ...)})
*/
getSeries: function(data){
return data.collect(function(serie){
serie = (serie.data) ? Object.clone(serie) : {data: serie};
for (var i = serie.data.length-1; i > -1; --i) {
serie.data[i][1] = (serie.data[i][1] === null ? null : parseFloat(serie.data[i][1]));
}
return serie;
});
},
/**
* Recursively merges two objects.
* @param {Object} src - source object (likely the object with the least properties)
* @param {Object} dest - destination object (optional, object with the most properties)
* @return {Object} recursively merged Object
*/
merge: function(src, dest){
var i, v, result = dest || {};
for(i in src){
v = src[i];
result[i] = (v && typeof(v) === 'object' && !(v.constructor === Array || v.constructor === RegExp) && !Object.isElement(v)) ? Flotr.merge(v, dest[i]) : result[i] = v;
}
return result;
},
/**
* Recursively clones an object.
* @param {Object} object - The object to clone
* @return {Object} the clone
*/
clone: function(object){
var i, v, clone = {};
for(i in object){
v = object[i];
clone[i] = (v && typeof(v) === 'object' && !(v.constructor === Array || v.constructor === RegExp) && !Object.isElement(v)) ? Flotr.clone(v) : v;
}
return clone;
},
/**
* Function calculates the ticksize and returns it.
* @param {Integer} noTicks - number of ticks
* @param {Integer} min - lower bound integer value for the current axis
* @param {Integer} max - upper bound integer value for the current axis
* @param {Integer} decimals - number of decimals for the ticks
* @return {Integer} returns the ticksize in pixels
*/
getTickSize: function(noTicks, min, max, decimals){
var delta = (max - min) / noTicks,
magn = Flotr.getMagnitude(delta),
tickSize = 10,
norm = delta / magn; // Norm is between 1.0 and 10.0.
if(norm < 1.5) tickSize = 1;
else if(norm < 2.25) tickSize = 2;
else if(norm < 3) tickSize = ((decimals == 0) ? 2 : 2.5);
else if(norm < 7.5) tickSize = 5;
return tickSize * magn;
},
/**
* Default tick formatter.
* @param {String, Integer} val - tick value integer
* @return {String} formatted tick string
*/
defaultTickFormatter: function(val){
return val+'';
},
/**
* Formats the mouse tracker values.
* @param {Object} obj - Track value Object {x:..,y:..}
* @return {String} Formatted track string
*/
defaultTrackFormatter: function(obj){
return '('+obj.x+', '+obj.y+')';
},
/**
* Utility function to convert file size values in bytes to kB, MB, ...
* @param value {Number} - The value to convert
* @param precision {Number} - The number of digits after the comma (default: 2)
* @param base {Number} - The base (default: 1000)
*/
engineeringNotation: function(value, precision, base){
var sizes = ['Y','Z','E','P','T','G','M','k',''],
fractionSizes = ['y','z','a','f','p','n','µ','m',''],
total = sizes.length;
base = base || 1000;
precision = Math.pow(10, precision || 2);
if (value == 0) return 0;
if (value > 1) {
while (total-- && (value >= base)) value /= base;
}
else {
sizes = fractionSizes;
total = sizes.length;
while (total-- && (value < 1)) value *= base;
}
return (Math.round(value * precision) / precision) + sizes[total];
},
/**
* Returns the magnitude of the input value.
* @param {Integer, Float} x - integer or float value
* @return {Integer, Float} returns the magnitude of the input value
*/
getMagnitude: function(x){
return Math.pow(10, Math.floor(Math.log(x) / Math.LN10));
},
toPixel: function(val){
return Math.floor(val)+0.5;//((val-Math.round(val) < 0.4) ? (Math.floor(val)-0.5) : val);
},
toRad: function(angle){
return -angle * (Math.PI/180);
},
floorInBase: function(n, base) {
return base * Math.floor(n / base);
},
drawText: function(ctx, text, x, y, style) {
if (!ctx.fillText || Flotr.isIphone) {
ctx.drawText(text, x, y, style);
return;
}
style = Object.extend({
size: Flotr.defaultOptions.fontSize,
color: '#000000',
textAlign: 'left',
textBaseline: 'bottom',
weight: 1,
angle: 0
}, style);
ctx.save();
ctx.translate(x, y);
ctx.rotate(style.angle);
ctx.fillStyle = style.color;
ctx.font = (style.weight > 1 ? "bold " : "") + (style.size*1.3) + "px sans-serif";
ctx.textAlign = style.textAlign;
ctx.textBaseline = style.textBaseline;
ctx.fillText(text, 0, 0);
ctx.restore();
},
measureText: function(ctx, text, style) {
if (!ctx.fillText || Flotr.isIphone) {
return {width: ctx.measure(text, style)};
}
style = Object.extend({
size: Flotr.defaultOptions.fontSize,
weight: 1,
angle: 0
}, style);
ctx.save();
ctx.rotate(style.angle);
ctx.font = (style.weight > 1 ? "bold " : "") + (style.size*1.3) + "px sans-serif";
var metrics = ctx.measureText(text);
ctx.restore();
return metrics;
},
getBestTextAlign: function(angle, style) {
style = style || {textAlign: 'center', textBaseline: 'middle'};
angle += Flotr.getTextAngleFromAlign(style);
if (Math.abs(Math.cos(angle)) > 10e-3)
style.textAlign = (Math.cos(angle) > 0 ? 'right' : 'left');
if (Math.abs(Math.sin(angle)) > 10e-3)
style.textBaseline = (Math.sin(angle) > 0 ? 'top' : 'bottom');
return style;
},
alignTable: {
'right middle' : 0,
'right top' : Math.PI/4,
'center top' : Math.PI/2,
'left top' : 3*(Math.PI/4),
'left middle' : Math.PI,
'left bottom' : -3*(Math.PI/4),
'center bottom': -Math.PI/2,
'right bottom' : -Math.PI/4,
'center middle': 0
},
getTextAngleFromAlign: function(style) {
return Flotr.alignTable[style.textAlign+' '+style.textBaseline] || 0;
}
};
Flotr.defaultOptions = {
colors: ['#00A8F0', '#C0D800', '#CB4B4B', '#4DA74D', '#9440ED'], //=> The default colorscheme. When there are > 5 series, additional colors are generated.
title: null, // => The graph's title
subtitle: null, // => The graph's subtitle
shadowSize: 4, // => size of the 'fake' shadow
defaultType: null, // => default series type
HtmlText: true, // => wether to draw the text using HTML or on the canvas
fontSize: 7.5, // => canvas' text font size
resolution: 1, // => resolution of the graph, to have printer-friendly graphs !
legend: {
show: true, // => setting to true will show the legend, hide otherwise
noColumns: 1, // => number of colums in legend table // @todo: doesn't work for HtmlText = false
labelFormatter: function(v){return v}, // => fn: string -> string
labelBoxBorderColor: '#CCCCCC', // => border color for the little label boxes
labelBoxWidth: 14,
labelBoxHeight: 10,
labelBoxMargin: 5,
container: null, // => container (as jQuery object) to put legend in, null means default on top of graph
position: 'nw', // => position of default legend container within plot
margin: 5, // => distance from grid edge to default legend container within plot
backgroundColor: null, // => null means auto-detect
backgroundOpacity: 0.85// => set to 0 to avoid background, set to 1 for a solid background
},
xaxis: {
ticks: null, // => format: either [1, 3] or [[1, 'a'], 3]
minorTicks: null, // => format: either [1, 3] or [[1, 'a'], 3]
showLabels: true, // => setting to true will show the axis ticks labels, hide otherwise
showMinorLabels: false,// => true to show the axis minor ticks labels, false to hide
labelsAngle: 0, // => labels' angle, in degrees
title: null, // => axis title
titleAngle: 0, // => axis title's angle, in degrees
noTicks: 5, // => number of ticks for automagically generated ticks
minorTickFreq: null, // => number of minor ticks between major ticks for autogenerated ticks
tickFormatter: Flotr.defaultTickFormatter, // => fn: number -> string
tickDecimals: null, // => no. of decimals, null means auto
min: null, // => min. value to show, null means set automatically
max: null, // => max. value to show, null means set automatically
autoscaleMargin: 0, // => margin in % to add if auto-setting min/max
color: null, // => color of the ticks
mode: 'normal', // => can be 'time' or 'normal'
timeFormat: null,
scaling: 'linear', // => Scaling, can be 'linear' or 'logarithmic'
base: Math.E,
titleAlign: 'center',
margin: true // => Turn off margins with false
},
x2axis: {},
yaxis: {
ticks: null, // => format: either [1, 3] or [[1, 'a'], 3]
minorTicks: null, // => format: either [1, 3] or [[1, 'a'], 3]
showLabels: true, // => setting to true will show the axis ticks labels, hide otherwise
showMinorLabels: false,// => true to show the axis minor ticks labels, false to hide
labelsAngle: 0, // => labels' angle, in degrees
title: null, // => axis title
titleAngle: 90, // => axis title's angle, in degrees
noTicks: 5, // => number of ticks for automagically generated ticks
minorTickFreq: null, // => number of minor ticks between major ticks for autogenerated ticks
tickFormatter: Flotr.defaultTickFormatter, // => fn: number -> string
tickDecimals: null, // => no. of decimals, null means auto
min: null, // => min. value to show, null means set automatically
max: null, // => max. value to show, null means set automatically
autoscaleMargin: 0, // => margin in % to add if auto-setting min/max
color: null, // => The color of the ticks
scaling: 'linear', // => Scaling, can be 'linear' or 'logarithmic'
base: Math.E,
titleAlign: 'center',
margin: true // => Turn off margins with false
},
y2axis: {
titleAngle: 270
},
grid: {
color: '#545454', // => primary color used for outline and labels
backgroundColor: null, // => null for transparent, else color
backgroundImage: null, // => background image. String or object with src, left and top
watermarkAlpha: 0.4, // =>
tickColor: '#DDDDDD', // => color used for the ticks
labelMargin: 3, // => margin in pixels
verticalLines: true, // => whether to show gridlines in vertical direction
minorVerticalLines: null, // => whether to show gridlines for minor ticks in vertical dir.
horizontalLines: true, // => whether to show gridlines in horizontal direction
minorHorizontalLines: null, // => whether to show gridlines for minor ticks in horizontal dir.
outlineWidth: 2, // => width of the grid outline/border in pixels
circular: false // => if set to true, the grid will be circular, must be used when radars are drawn
},
selection: {
mode: null, // => one of null, 'x', 'y' or 'xy'
color: '#B6D9FF', // => selection box color
fps: 20 // => frames-per-second
},
crosshair: {
mode: null, // => one of null, 'x', 'y' or 'xy'
color: '#FF0000', // => crosshair color
hideCursor: true // => hide the cursor when the crosshair is shown
},
mouse: {
track: false, // => true to track the mouse, no tracking otherwise
trackAll: false,
position: 'se', // => position of the value box (default south-east)
relative: false, // => next to the mouse cursor
trackFormatter: Flotr.defaultTrackFormatter, // => formats the values in the value box
margin: 5, // => margin in pixels of the valuebox
lineColor: '#FF3F19', // => line color of points that are drawn when mouse comes near a value of a series
trackDecimals: 1, // => decimals for the track values
sensibility: 2, // => the lower this number, the more precise you have to aim to show a value
radius: 3, // => radius of the track point
fillColor: null, // => color to fill our select bar with only applies to bar and similar graphs (only bars for now)
fillOpacity: 0.4 // => opacity of the fill color, set to 1 for a solid fill, 0 hides the fill
}
};
/**
* Flotr Graph class that plots a graph on creation.
*/
Flotr.Graph = Class.create({
/**
* Flotr Graph constructor.
* @param {Element} el - element to insert the graph into
* @param {Object} data - an array or object of dataseries
* @param {Object} options - an object containing options
*/
initialize: function(el, data, options){
try {
this.el = $(el);
if (!this.el) throw 'The target container doesn\'t exist';
if (!this.el.clientWidth) throw 'The target container must be visible';
this.registerPlugins();
this.el.fire('flotr:beforeinit', [this]);
// Initialize some variables
this.el.graph = this;
this.data = data;
this.lastMousePos = { pageX: null, pageY: null };
this.selection = { first: { x: -1, y: -1}, second: { x: -1, y: -1} };
this.plotOffset = {left: 0, right: 0, top: 0, bottom: 0};
this.prevSelection = null;
this.selectionInterval = null;
this.ignoreClick = false;
this.prevHit = null;
this.series = Flotr.getSeries(data);
this.setOptions(options);
var type, p;
for (type in Flotr.graphTypes) {
this[type] = Object.clone(Flotr.graphTypes[type]);
for (p in this[type]) {
if (Object.isFunction(this[type][p]))
this[type][p] = this[type][p].bind(this);
}
}
// Create and prepare canvas.
this.constructCanvas();
this.el.fire('flotr:afterconstruct', [this]);
// Add event handlers for mouse tracking, clicking and selection
this.initEvents();
this.findDataRanges();
this.calculateTicks(this.axes.x);
this.calculateTicks(this.axes.x2);
this.calculateTicks(this.axes.y);
this.calculateTicks(this.axes.y2);
this.calculateSpacing();
this.setupAxes();
this.draw(function() {
this.insertLegend();
this.el.fire('flotr:afterinit', [this]);
}.bind(this));
} catch (e) {
try {
console.error(e);
} catch (e) {}
}
},
/**
* Sets options and initializes some variables and color specific values, used by the constructor.
* @param {Object} opts - options object
*/
setOptions: function(opts){
var options = Flotr.clone(Flotr.defaultOptions);
options.x2axis = Object.extend(Object.clone(options.xaxis), options.x2axis);
options.y2axis = Object.extend(Object.clone(options.yaxis), options.y2axis);
this.options = Flotr.merge(opts || {}, options);
// The 4 axes of the plot
this.axes = {
x: {options: this.options.xaxis, n: 1},
x2: {options: this.options.x2axis, n: 2},
y: {options: this.options.yaxis, n: 1},
y2: {options: this.options.y2axis, n: 2}
};
if (this.options.grid.minorVerticalLines === null &&
this.options.xaxis.scaling === 'logarithmic') {
this.options.grid.minorVerticalLines = true;
}
if (this.options.grid.minorHorizontalLines === null &&
this.options.yaxis.scaling === 'logarithmic') {
this.options.grid.minorHorizontalLines = true;
}
// Initialize some variables used throughout this function.
var assignedColors = [],
colors = [],
ln = this.series.length,
neededColors = this.series.length,
oc = this.options.colors,
usedColors = [],
variation = 0,
c, i, j, s;
// Collect user-defined colors from series.
for(i = neededColors - 1; i > -1; --i){
c = this.series[i].color;
if(c){
--neededColors;
if(Object.isNumber(c)) assignedColors.push(c);
else usedColors.push(Flotr.Color.parse(c));
}
}
// Calculate the number of colors that need to be generated.
for(i = assignedColors.length - 1; i > -1; --i)
neededColors = Math.max(neededColors, assignedColors[i] + 1);
// Generate needed number of colors.
for(i = 0; colors.length < neededColors;){
c = (oc.length == i) ? new Flotr.Color(100, 100, 100) : Flotr.Color.parse(oc[i]);
// Make sure each serie gets a different color.
var sign = variation % 2 == 1 ? -1 : 1,
factor = 1 + sign * Math.ceil(variation / 2) * 0.2;
c.scale(factor, factor, factor);
/**
* @todo if we're getting too close to something else, we should probably skip this one
*/
colors.push(c);
if(++i >= oc.length){
i = 0;
++variation;
}
}
// Fill the options with the generated colors.
for(i = 0, j = 0; i < ln; ++i){
s = this.series[i];
// Assign the color.
if(s.color == null){
s.color = colors[j++].toString();
}else if(Object.isNumber(s.color)){
s.color = colors[s.color].toString();
}
// Every series needs an axis
if (!s.xaxis) s.xaxis = this.axes.x;
if (s.xaxis == 1) s.xaxis = this.axes.x;
else if (s.xaxis == 2) s.xaxis = this.axes.x2;
if (!s.yaxis) s.yaxis = this.axes.y;
if (s.yaxis == 1) s.yaxis = this.axes.y;
else if (s.yaxis == 2) s.yaxis = this.axes.y2;
// Apply missing options to the series.
for (var t in Flotr.graphTypes){
s[t] = Object.extend(Object.clone(this.options[t]), s[t]);
}
s.mouse = Object.extend(Object.clone(this.options.mouse), s.mouse);
if(s.shadowSize == null) s.shadowSize = this.options.shadowSize;
}
},
setupAxes: function(){
/**
* Translates data number to pixel number
* @param {Number} v - data number
* @return {Number} translated pixel number
*/
function d2p(v, o){
if (o.scaling === 'logarithmic') {
v = Math.log(Math.max(v, Number.MIN_VALUE));
if (o.base !== Math.E)
v /= Math.log(o.base);
}
return v;
}
/**
* Translates pixel number to data number
* @param {Number} v - pixel data
* @return {Number} translated data number
*/
function p2d(v, o){
if (o.scaling === 'logarithmic')
v = (o.base === Math.E) ? Math.exp(v) : Math.pow(o.base, v);
return v;
}
var x = this.axes.x,
x2 = this.axes.x2,
y = this.axes.y,
y2 = this.axes.y2;
var pw = this.plotWidth,
ph = this.plotHeight;
x.scale = pw / (d2p(x.max, x.options) - d2p(x.min, x.options));
x2.scale = pw / (d2p(x2.max, x2.options) - d2p(x2.min, x2.options));
y.scale = ph / (d2p(y.max, y.options) - d2p(y.min, y.options));
y2.scale = ph / (d2p(y2.max, y2.options) - d2p(y2.min, y2.options));
if (this.options.scaling === 'logarithmic') {
x.d2p = x2.d2p = function(xval){
var o = this.options;
return (d2p(xval, o) - d2p(this.min, o)) * this.scale;
};
x.p2d = this.axes.x2.p2d = function(xval){
var o = this.options;
return p2d(xval / this.scale + d2p(this.min, o), o);
};
y.d2p = y2.d2p = function(yval){
var o = this.options;
return ph - (d2p(yval, o) - d2p(this.min, o)) * this.scale;
};
y.p2d = y2.p2d = function(yval){
var o = this.options;
return p2d((ph - yval) / this.scale + d2p(this.min, o), o);
};
} else {
x.d2p = x2.d2p = function(xval){
return (xval - this.min) * this.scale;
};
x.p2d = this.axes.x2.p2d = function(xval){
return xval / this.scale + this.min;
};
y.d2p = y2.d2p = function(yval){
return ph - (yval - this.min) * this.scale;
};
y.p2d = y2.p2d = function(yval){
return (ph - yval) / this.scale + this.min;
};
}
},
/**
* Initializes the canvas and it's overlay canvas element. When the browser is IE, this makes use
* of excanvas. The overlay canvas is inserted for displaying interactions. After the canvas elements
* are created, the elements are inserted into the container element.
*/
constructCanvas: function(){
var el = this.el,
size, c, oc;
// The old canvases are retrieved to avoid memory leaks ...
this.canvas = el.select('.flotr-canvas')[0];
this.overlay = el.select('.flotr-overlay')[0];
// ... and all the child elements are removed
el.descendants().invoke('remove');
// For positioning labels and overlay.
el.style.position = 'relative';
el.style.cursor = el.style.cursor || 'default';
size = el.getDimensions();
this.canvasWidth = size.width;
this.canvasHeight = size.height;
var style = {
width: size.width+'px',
height: size.height+'px'
};
var o = this.options;
size.width *= o.resolution;
size.height *= o.resolution;
if(this.canvasWidth <= 0 || this.canvasHeight <= 0){
throw 'Invalid dimensions for plot, width = ' + this.canvasWidth + ', height = ' + this.canvasHeight;
}
// Insert main canvas.
if (!this.canvas) {
c = this.canvas = $(document.createElement('canvas')); // Do NOT use new Element()
c.className = 'flotr-canvas';
c.style.cssText = 'position:absolute;left:0px;top:0px;';
}
c = this.canvas.writeAttribute(size).show().setStyle(style);
c.context_ = null; // Reset the ExCanvas context
el.insert(c);
// Insert overlay canvas for interactive features.
if (!this.overlay) {
oc = this.overlay = $(document.createElement('canvas')); // Do NOT use new Element()
oc.className = 'flotr-overlay';
oc.style.cssText = 'position:absolute;left:0px;top:0px;';
}
oc = this.overlay.writeAttribute(size).show().setStyle(style);
oc.context_ = null; // Reset the ExCanvas context
el.insert(oc);
if(window.G_vmlCanvasManager){
window.G_vmlCanvasManager.initElement(c);
window.G_vmlCanvasManager.initElement(oc);
}
this.ctx = c.getContext('2d');
this.octx = oc.getContext('2d');
if(!window.G_vmlCanvasManager){
this.ctx.scale(o.resolution, o.resolution);
this.octx.scale(o.resolution, o.resolution);
}
// Enable text functions
this.textEnabled = !!this.ctx.drawText;
},
processColor: function(color, options){
if (!color) return 'rgba(0, 0, 0, 0)';
options = Object.extend({
x1: 0, y1: 0, x2: this.plotWidth, y2: this.plotHeight, opacity: 1, ctx: this.ctx
}, options);
if (color instanceof Flotr.Color) return color.adjust(null, null, null, options.opacity).toString();
if (Object.isString(color)) return Flotr.Color.parse(color).scale(null, null, null, options.opacity).toString();
var grad = color.colors ? color : {colors: color};
if (!options.ctx) {
if (!Object.isArray(grad.colors)) return 'rgba(0, 0, 0, 0)';
return Flotr.Color.parse(Object.isArray(grad.colors[0]) ? grad.colors[0][1] : grad.colors[0]).scale(null, null, null, options.opacity).toString();
}
grad = Object.extend({start: 'top', end: 'bottom'}, grad);
if (/top/i.test(grad.start)) options.x1 = 0;
if (/left/i.test(grad.start)) options.y1 = 0;
if (/bottom/i.test(grad.end)) options.x2 = 0;
if (/right/i.test(grad.end)) options.y2 = 0;
var i, c, stop, gradient = options.ctx.createLinearGradient(options.x1, options.y1, options.x2, options.y2);
for (i = 0; i < grad.colors.length; i++) {
c = grad.colors[i];
if (Object.isArray(c)) {
stop = c[0];
c = c[1];
}
else stop = i / (grad.colors.length-1);
gradient.addColorStop(stop, Flotr.Color.parse(c).scale(null, null, null, options.opacity));
}
return gradient;
},
registerPlugins: function(){
var name, plugin, c;
for (name in Flotr.plugins) {
plugin = Flotr.plugins[name];
for (c in plugin.callbacks) {
// Ensure no old handlers are still observing this element (prevent memory leaks)
this.el.
stopObserving(c).
observe(c, plugin.callbacks[c].bindAsEventListener(this));
}
this[name] = Object.clone(plugin);
for (p in this[name]) {
if (Object.isFunction(this[name][p]))
this[name][p] = this[name][p].bind(this);
}
}
},
/**
* Calculates a text box dimensions, wether it is drawn on the canvas or inserted into the DOM
* @param {String} text - The text in the box
* @param {Object} canvasStyle - An object containing the style for the text if drawn on the canvas
* @param {String} HtmlStyle - A CSS style for the text if inserted into the DOM
* @param {Object} className - A CSS className for the text if inserted into the DOM
*/
getTextDimensions: function(text, canvasStyle, HtmlStyle, className) {
if (!text) return {width:0, height:0};
if (!this.options.HtmlText && this.textEnabled) {
var bounds = this.ctx.getTextBounds(text, canvasStyle);
return {
width: bounds.width+2,
height: bounds.height+6
};
}
else {
var dummyDiv = this.el.insert('<div style="position:absolute;top:-10000px;'+HtmlStyle+'" class="'+className+' flotr-dummy-div">' + text + '</div>').select(".flotr-dummy-div")[0],
dim = dummyDiv.getDimensions();
dummyDiv.remove();
return dim;
}
},
/**
* Builds a matrix of the data to make the correspondance between the x values and the y values :
* X value => Y values from the axes
* @return {Array} The data grid
*/
loadDataGrid: function(){
if (this.seriesData) return this.seriesData;
var s = this.series,
dg = [];
/* The data grid is a 2 dimensions array. There is a row for each X value.
* Each row contains the x value and the corresponding y value for each serie ('undefined' if there isn't one)
**/
for(i = 0; i < s.length; ++i){
s[i].data.each(function(v) {
var x = v[0],
y = v[1],
r = dg.find(function(row) {return row[0] == x});
if (r) r[i+1] = y;
else {
var newRow = [];
newRow[0] = x;
newRow[i+1] = y;
dg.push(newRow);
}
});
}
// The data grid is sorted by x value
return this.seriesData = dg.sortBy(function(v){return v[0]});
},
/**
* Initializes event some handlers.
*/
initEvents: function () {
//@todo: maybe stopObserving with only flotr functions
this.overlay.stopObserving()
.observe('mousedown', this.mouseDownHandler.bindAsEventListener(this))
.observe('mousemove', this.mouseMoveHandler.bindAsEventListener(this))
.observe('mouseout', this.clearHit.bindAsEventListener(this))
.observe('click', this.clickHandler.bindAsEventListener(this));
},
/**
* Function determines the min and max values for the xaxis and yaxis.
*/
findDataRanges: function(){
var s = this.series,
a = this.axes;
a.x.datamin = a.x2.datamin = a.y.datamin = a.y2.datamin = Number.MAX_VALUE;
a.x.datamax = a.x2.datamax = a.y.datamax = a.y2.datamax = -Number.MAX_VALUE;
if(s.length > 0){
var i, j, h, x, y, data, xaxis, yaxis;
// Get datamin, datamax start values
for(i = 0; i < s.length; ++i) {
data = s[i].data,
xaxis = s[i].xaxis,
yaxis = s[i].yaxis;
if (data.length > 0 && !s[i].hide) {
for(h = data.length - 1; h > -1; --h){
x = data[h][0];
// Logarithm is only defined for values > 0
if ((x <= 0) && (xaxis.options.scaling === 'logarithmic')) continue;
if(x < xaxis.datamin) {
xaxis.datamin = x;
xaxis.used = true;
}
if(x > xaxis.datamax) {
xaxis.datamax = x;
xaxis.used = true;
}
for(j = 1; j < data[h].length; j++){
y = data[h][j];
// Logarithm is only defined for values > 0
if ((y <= 0) && (yaxis.options.scaling === 'logarithmic')) continue;
if(y < yaxis.datamin) {
yaxis.datamin = y;
yaxis.used = true;
}
if(y > yaxis.datamax) {
yaxis.datamax = y;
yaxis.used = true;
}
}
}
}
}
}
this.findXAxesValues();
this.calculateRange(a.x, 'x');
if (a.x2.used) {
this.calculateRange(a.x2, 'x');
}
this.calculateRange(a.y, 'y');
if (a.y2.used) {
this.calculateRange(a.y2, 'y');
}
},
extendRange: function(axis, type) {
var f = (type === 'y') ? 'extendYRange' : 'extendXRange'
for (var t in Flotr.graphTypes) {
if(this.series[type] && this.series[type].show){
if (this[t][f]) this[t][f](axis);
}
}
},
/**
* Calculates the range of an axis to apply autoscaling.
* @param {Object} axis - The axis for what the range will be calculated
*/
calculateRange: function(axis, type){
var o = axis.options,
min = o.min != null ? o.min : axis.datamin,
max = o.max != null ? o.max : axis.datamax,
margin = o.autoscaleMargin;
if (o.scaling == 'logarithmic') {
if (min <= 0) min = axis.datamin;
// Let it widen later on
if (max <= 0) max = min;
}
if(max - min == 0.0){
var widen = (max == 0.0) ? 1.0 : 0.01;
min -= widen;
max += widen;
}
if (o.scaling === 'logarithmic') {
if (min < 0) min = max / o.base; // Could be the result of widening
var maxexp = Math.log(max);
if (o.base != Math.E) maxexp /= Math.log(o.base);
maxexp = Math.ceil(maxexp);
var minexp = Math.log(min);
if (o.base != Math.E) minexp /= Math.log(o.base);
minexp = Math.ceil(minexp);
axis.tickSize = Flotr.getTickSize(o.noTicks, minexp, maxexp, o.tickDecimals === null ? 0 : o.tickDecimals);
// Try to determine a suitable amount of miniticks based on the length of a decade
if (o.minorTickFreq === null) {
if (maxexp - minexp > 10)
o.minorTickFreq = 0;
else if (maxexp - minexp > 5)
o.minorTickFreq = 2;
else
o.minorTickFreq = 5;
}
} else {
axis.tickSize = Flotr.getTickSize(o.noTicks, min, max, o.tickDecimals);
}
// Autoscaling. @todo This probably fails with log scale. Find a testcase and fix it
if(o.min == null && margin != 0){
min -= axis.tickSize * margin;
// Make sure we don't go below zero if all values are positive.
if(min < 0 && axis.datamin >= 0) min = 0;
min = axis.tickSize * Math.floor(min / axis.tickSize);
}
if(o.max == null && margin != 0){
max += axis.tickSize * margin;
if(max > 0 && axis.datamax <= 0 && axis.datamax != axis.datamin) max = 0;
max = axis.tickSize * Math.ceil(max / axis.tickSize);
}
if (min == max) max = min + 1;
axis.min = min;
axis.max = max;
this.extendRange(axis, type);
},
/**
* Find every values of the x axes
*/
findXAxesValues: function(){
var i, j, s;
for(i = this.series.length-1; i > -1 ; --i){
s = this.series[i];
s.xaxis.values = s.xaxis.values || {};
for (j = s.data.length-1; j > -1 ; --j){
s.xaxis.values[s.data[j][0]+''] = {};
}
}
},
/**
* Calculate axis ticks.
* @param {Object} axis - The axis for what the ticks will be calculated
*/
calculateTicks: function(axis){
var o = axis.options, i, v;
axis.ticks = [];
axis.minorTicks = [];
if(o.ticks){
var ticks = o.ticks,
minorTicks = o.minorTicks || [],
t, label;
if(Object.isFunction(ticks)){
ticks = ticks({min: axis.min, max: axis.max});
}
if(Object.isFunction(minorTicks)){
minorTicks = minorTicks({min: axis.min, max: axis.max});
}
// Clean up the user-supplied ticks, copy them over.