-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChart.js
1228 lines (1012 loc) · 32.5 KB
/
Chart.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
Dave_js.chart = function(name) {
var self = this;
//////////////////////////Private Members//////////////////////////////
//keeps track of current index of the data point closest to the mouse
var coord_i = 0;
//contains all of the canvas attributes the user will set
var chart = {
//canvas id based on the user specified name
id : name + "-canvas",
//Type of chart to be drawn.
//Options are xy (lines and or points), polar, hist
type : "",
//default canvas size
sizes : {
canvas : {
//drawable area height and width
width : 0,
height : 0,
//margin between canvas edge and ploting region
//(used for titels, labels, etc...)
margin : 200
},
//chart height and width or radius
width : 0,
height : 0,
radius : 0,
lineWidth : 3,
pointSize : 6,
halfPointSize : 3,
},
//default x and y origins for the canvas coordinate system
origin : { x : 60, y : 20},
totalOffsetX : 0,
totalOffsetY : 0,
//the id attribute for an image tag on the
//page which contains the desired background
bgImg : undefined,
//settings for chart text
cssFont : '14px sans-serif',
labels : {
title : "",
indep : "",
dep : ""
},
//Default number of y tics to skip
skipTics : {dep : 1, indep : 1 },
//number of pixels per point in each dimension
pntSpacing : {dep : 1, indep : 1},
//min and max values for dependent variables
limits : {xmin : 0, xmax : 0, ymin : 0, ymax : 0},
//default settings for plot scale
scale : {"type" : "lin", "value" : 1},
//histogram bar width plus margin
histBarTotal : undefined,
histBarWidth : undefined,
histBarMargin : undefined,
//default 90% histogram bar width
histBarRatio : 0.9,
//direction of increasing angles in polar plots
// -1 = anticlockwise; 1 = clockwise
polarRot : -1,
//where 0 degrees is located on the polar plot
zeroAngle : 0,
//define plot range
range: {
"start" : Number.NEGATIVE_INFINITY,
"stop" : Number.POSITIVE_INFINITY,
"numOfPts" : 0
},
//holds the different colors used for in the plot
colors: {
// default colors
activePoint : "#00FF00",
text : "black",
grid : "gray",
data : ['Red','Blue','Green', 'Yellow'],
borderColor : '#000000',
bgColor : '#CCCCCC',
}
};
//holds all of the info for the coordinat display
var coordDisp = {
xId : undefined,
yId : undefined,
oldIndex : 0,
index : 0
};
//canvas context used for drawing
var ctx = null;
//contains all of the page elements that the plotter will use
var elms = {
//element reference for a div that will hold the canvas element.
//If not specified, canvas will be generated in the "body" tag.
canvasBox : document.getElementsByTagName("body")[0],
//element reference to the canvas we will draw to
canvas : undefined,
//divs to hold the pointer coordinats.
//Coord event listener will not be created without both of these
xCoordBox : undefined,
yCoordBox : undefined
};
//contains flags that may be set to govern the plotter's behavior
var flags = {
//set true if the data has been plotted once.
//Prevents scaling data multiple times
replot : false,
//set this to indicate a polar
polar : false,
//draw a bar from zero up to the point value
hist : false,
//rectangular box for an xy plot
xy : false,
//setting this true indicates we are drawing on top of an existing plot.
//Frame, background, axis labels, tics, and limits are all skipped.
subPlot : false,
//setting this true will add an event listener to the plot
//so we can display exact mouseover plot values
showCoords : true,
//values will be connected with a line
lines : false,
//values will be represented by a point
points : false,
//the user sets a fixed point width
fixedPtSize : false,
//convert angular/radial values to longitude/lattitude
map : false,
//scale the data before plotting
scaled : false,
//false for fitting the y axis to the data,
//true to use pre defined axis limits
limits : false,
//draw a background grid (only for polar plots right now)
grid : false,
axis : false,
title : false,
//on xy plots this lists variable names in their color along the top,
//in polar plots, this draws a line from a colored variable name to
//the last drawn point
legend : false,
//makes plot zoomable by clicking and dragging over the desired area
zoomable : true
};
var vars = {
indep : "",
deps : [],
trackers : [],
trackLabels : []
};
//Contains a reference to the data store we will be using
var dataStore;
//////////////////////////Private Methods//////////////////////////////
//method to test the browser's ability to display HTML5 canvas
function browserTest() {
//set special values based on browser
var userAgent=navigator.userAgent;
if (userAgent.indexOf("MSIE") != -1) {
if (parseInt(navigator.appVersion, 10) < 9) {
alert(
'Internet Explorer does not support HTML5 canvas. ' +
'Please use Google Chrome, Firefox, Opera, or Safari'
);
return;
}
} else if(userAgent.indexOf("Firefox") != -1) {
if (parseInt(navigator.appVersion, 10) < 3) {
alert(
"Firefox 3.0 or later required for proper display"
);
}
}
}
// Add a new canvas to the "canvasBox" element,
// gets the canvas context, and draws a skeleton graph
function buildCanvas() {
var timer = (new Date()).getTime();
//if this is not part of an existing plot, clear the canvas
if(flags.subplot != 1) {
//remove old canvas element
if(elms.canvas) {
elms.canvasBox.removeChild(elms.canvas);
elms.canvas = null;
}
//create a canvas and insert it into the canvasBox
elms.canvas = document.createElement("canvas");
elms.canvas.id = chart.id;
elms.canvas.width = chart.sizes.canvas.width;
elms.canvas.height = chart.sizes.canvas.height;
elms.canvasBox.appendChild(elms.canvas);
}
//initialize canvas context
ctx = null;
ctx = elms.canvas.getContext("2d");
//move coord origin to the upper left corner of plot area
ctx.translate(
chart.origin.x, chart.origin.y
);
if (!flags.subplot) {
//draw background and border
if (chart.bgImg) {
ctx.drawImage( chart.bgImg, 0, 0 );
} else {
ctx.fillStyle = chart.colors.bgColor;
ctx.fillRect( 0, 0, chart.sizes.width, chart.sizes.height );
}
ctx.strokeStyle = chart.colors.borderColor;
ctx.strokeRect(0, 0, chart.sizes.width, chart.sizes.height);
//print title (bold)
if (flags.title) {
ctx.textAlign = "center";
ctx.fillStyle = chart.colors.text;
ctx.font = "bold " + chart.cssFont;
ctx.fillText(
chart.labels.title,
(chart.sizes.width / 2), -5
);
}
//print axis labels
if (flags.axis) {
ctx.font = chart.cssFont;
ctx.fillStyle = chart.colors.text;
ctx.textAlign = "start";
ctx.fillText(
chart.labels.indep,
-50, (chart.sizes.height + 40)
);
ctx.save();
ctx.translate(-45, (chart.sizes.height / 2) );
ctx.rotate(1.5 * Math.PI);
ctx.textAlign = "center";
ctx.fillText(chart.labels.dep, 0, -20);
ctx.restore();
}
}
//add coordinate display if this is an xy plot and the coord flag is set
if(flags.xy && flags.showCoords) {
//create a message holder
elms.coordMsg = new Dave_js.message();
elms.coordMsg.box.style.opacity = "0.8";
elms.coordMsg.box.style.filter = "alpha(opacity=80)";
}
//add event listeners to display coordinates in the message holder
elms.canvas.addEventListener("mouseover", canvasMouseIn);
elms.canvasBox.addEventListener("mouseover", canvasMouseOut);
timer = (new Date()).getTime() - timer;
console.log("Canvas Build = " + timer / 1000);
}
function canvasMouseIn(e) {
e.stopPropagation();
//create zoom object if one does not yet exist
if(Dave_js.chart_zoom && flags.zoomable) {
if (!chart.zoom) {
chart.zoom = new Dave_js.chart_zoom(self, dataStore, elms, chart);
}
}
//add event listeners for tracking mouse pointer
elms.canvasBox.addEventListener(
"mousedown", mouseDown
);
elms.canvasBox.addEventListener(
"mouseup", mouseUp
);
elms.canvasBox.addEventListener(
"mousemove", mouseMove
);
}
function canvasMouseOut(e) {
//make sure the mouse out did not occur because of running over a mask
if (e.target.className == "daveMask") {return;}
//remove event listeners
elms.canvasBox.removeEventListener(
"mousedown", mouseDown
);
elms.canvasBox.removeEventListener(
"mouseup", mouseUp
);
elms.canvasBox.removeEventListener(
"mousemove", mouseMove
);
//remove the masking divs
if (chart.zoom) {chart.zoom = chart.zoom.destroy();}
//remove the coordinate message
if (flags.showCoords && elms.coordMsg.box.parentNode) {
elms.coordMsg.box.hidden = true;
}
}
function mouseDown(e) {
if(Dave_js.chart_zoom && flags.zoomable) { //stop tracking mouse
//start tracking the mouse pointer
chart.zoom.start(coord_i);
}
}
function mouseUp(e) {
if(Dave_js.chart_zoom && flags.zoomable) { //stop tracking mouse
chart.zoom.stop(coord_i, e.pageX);
}
}
function mouseMove(e) {
var
//x coordinate of cursor relative to canvas
x = e.pageX - chart.origin.x - elms.canvasBox.offsetLeft,
range = chart.range,
indepVarData = dataStore.getVarData(vars.indep) || [],
indepVarLength = indepVarData.length;
//calculate the data point index we are closest to
coord_i =
Math.round(x * (range.numOfPts - 1) / chart.sizes.width) + range.start;
//make sure the coord_i is within the data set
coord_i = Math.min(coord_i, (indepVarLength - 1));
coord_i = Math.max(coord_i, 0);
if(Dave_js.message && flags.showCoords) {
showCoord(coord_i, e.pageX, e.pageY);
}
if(Dave_js.chart_zoom && flags.zoomable) { //stop tracking mouse
if(!chart.zoom) {
}
chart.zoom.moveMask(e.pageX);
}
}
function showCoord(coord_i, x, y) {
var
indepVarData = dataStore.getVarData(vars.indep) || [],
indepVarLength = indepVarData.length,
depVarNames = vars.deps || [],
numDepVars = vars.deps.length,
scaleType = chart.scale.type,
scaleValue = chart.scale.value,
depVarData,
depVarLength,
message,
yCoord,
xCoord,
plt_i,
negOffset,
taposOffset;
//make sure the coordinate box is visible
elms.coordMsg.box.hidden = false;
//create message and show message if we are within the plot
if((xCoord = indepVarData[coord_i]) === undefined){
return;
}
message = chart.labels.indep + " = " + xCoord;
for (plt_i = 0; plt_i < numDepVars; plt_i++) {
depVarData = dataStore.getVarData(depVarNames[plt_i]);
//make sure the yCoord is a number
//try stepping backwards and forwards until a number is found ,
//or the end of the dataset is reached
negOffset = posOffset = coord_i;
while (1) {
//try to step back
if (negOffset >= 0) {
yCoord = depVarData[negOffset];
}
//try to step forward
if (isNaN(yCoord) && posOffset < numDepVars) {
yCoord = depVarData[posOffset];
}
//check to see if it is time to break
if (!isNaN(yCoord) || (negOffset < 0 && posOffset > numDepVars)) {
break;
}
negOffset--;
posOffset++;
}
//unscale the yCoord if needed
if (flags.scaled) {
if (scaleType == "log") {
yCoord = Math.pow(scaleValue, yCoord);
} else if(scaleType == "lin") {
yCoord /= scaleValue;
}
}
//drop values past 3 decimal places
if (((yCoord % 1) !== 0) && (typeof yCoord == "function")) {
yCoord = yCoord.toFixed(3);
}
message += "<br />" + depVarNames[plt_i] + " = " + yCoord;
}
elms.coordMsg.showMessage(
message, (x + 10), (y + 10)
);
}
//Scales the data set by either a linear value or logrithmically
function scaler() {
var
indepVarData = dataStore.getVarData(vars.indep) || [],
indepVarLength = indepVarData.length,
depVarNames = vars.deps || [],
numDepVars = vars.deps.length,
message,
timer = (new Date()).getTime(),
scale_type = chart.scale.type,
scale_val = chart.scale.value,
plt_i,
pnt_i,
y_data;
if (scale_type == "log") { //log plot
for (plt_i = 0; plt_i < numDepVars; plt_i++) {
y_data = dataStore.getVarData(dapVarNames[plt_i]);
for (pnt_i = 0; pnt_i <= indepVarLength; pnt_i++) {
if (y_data[pnt_i] !== 0 && !isNaN(y_data[pnt_i])) {
y_data[pnt_i] =
Math.log(y_data[pnt_i]) / Math.log(scale_val);
}
}
}
} else if (scale_type == "lin") { //linear plot
for (plt_i = 0; plt_i < numDepVars; plt_i++) {
y_data = dataStore.getVarData(dapVarNames[plt_i]);
for (pnt_i = 0; pnt_i <= indepVarLength; pnt_i++) {
if (!isNaN(y_data[pnt_i])) {
y_data[pnt_i] *= scale_val;
}
}
}
}
timer = (new Date()).getTime() - timer;
console.log("Scale Data = " + timer / 1000);
}
//either apply limits to dependent data, or generate axis limits from it
function doLimits() {
var
start = chart.range.start,
stop = chart.range.stop,
numOfPts = chart.range.numOfPts,
timer = (new Date()).getTime(),
indepVarData = dataStore.getVarData(vars.indep) || [],
indepVarLength = indepVarData.length,
depVarNames = vars.deps || [],
numDepVars = vars.deps.length,
depVarData,
plt_i,
pnt_i,
minLimit,
maxLimit,
pltMax,
pltMin;
if (!flags.limits) {
//user has not defined limits, so take the max and of the data set
//create an array of max and mins for each subset
pltMax = [];
pltMin = [];
for (plt_i = 0; plt_i < numDepVars; plt_i++) {
depVarData = dataStore.getVarData(depVarNames[plt_i]);
//find first real data point for initial min/max
for (pnt_i = 0; pnt_i < numOfPts; pnt_i++) {
if (!isNaN(depVarData[pnt_i + start])) {
pltMin[plt_i] = pltMax[plt_i] =
parseFloat(depVarData[pnt_i + start]);
break;
}
}
//go through the rest of the data points looking for min/max
for (pnt_i; pnt_i < numOfPts; pnt_i++) {
if (isNaN(depVarData[pnt_i + start])) {
continue;
}
pltMin[plt_i] =
Math.min(depVarData[pnt_i + start], pltMin[plt_i]);
pltMax[plt_i] =
Math.max(depVarData[pnt_i + start], pltMax[plt_i]);
}
}
//select the extremes from the max and min arrays
minLimit = Math.min.apply(null, pltMin);
maxLimit = Math.max.apply(null, pltMax);
} else {
minLimit = +chart.limits.ymin || 0;
maxLimit = +chart.limits.ymax || 0;
//the user has predefined data limits, so apply to each subset
for (plt_i = 0; plt_i < numDepVars; plt_i++) {
depVarData = dataStore.getVarData(depVarNames[plt_i]);
for (pnt_i = 0; pnt_i < numOfPts; pnt_i++) {
depVarData[pnt_i] =
Math.min( depVarData[pnt_i + start], maxLimit );
depVarData[pnt_i] =
Math.max( depVarData[pnt_i + start], minLimit );
}
}
}
//Make sure the ymax and min are not the same value
if (minLimit == maxLimit) {
minLimit -= chart.sizes.height / 2;
maxLimit += chart.sizes.height / 2;
}
//if we have a log plot, make the y axis start and end at an integer
if (flags.scaled && chart.scale.type == "log") {
minLimit = Math.floor(minLimit);
maxLimit = Math.ceil(maxLimit);
}
chart.limits.ymin = minLimit;
chart.limits.ymax = maxLimit;
timer = (new Date()).getTime() - timer;
console.log("Limits Calculated = " + timer / 1000);
}
function configSpacing() {
var
numOfPts = chart.range.numOfPts,
depRange = Math.abs(chart.limits.ymax - chart.limits.ymin);
chart.skipTics.indep =
Math.max(1, parseInt((20 * numOfPts / chart.sizes.width), 10));
chart.skipTics.dep =
Math.max(1, parseInt((20 * depRange / chart.sizes.height), 10));
if (flags.polar) {//polar plots only need spacing in the radial direction
chart.pntSpacing.dep = chart.sizes.radius / chart.limits.ymax;
} else { // all other plots are rectangular and need x/y spacing
chart.pntSpacing.indep = chart.sizes.width / (numOfPts - 1);
chart.pntSpacing.dep = chart.sizes.height / depRange;
}
}
function drawLinesPoints() {
var
x = 0,
y = 0, //screen coordinate for the plotted point
timer = (new Date()).getTime(),
legendOffset = 10,
range_start = chart.range.start,
chart_min = chart.limits.ymin,
y_spacing = chart.pntSpacing.dep,
x_spacing = chart.pntSpacing.indep,
//x_data = dataStore.getVarData(vars.indep) || [],
depVarNames = vars.deps || [],
numDepVars = depVarNames.length,
numOfPts = chart.range.numOfPts,
y_data,
plt_i,
plot = new Dave_js.Plot('Cartesian');
plot.ctx = ctx;
plot.dataStore = dataStore;
plot.chart = chart;
plot.loadData({
x: vars.indep,
y: vars.deps
});
plot.decorate();
plot.plotData();
timer = (new Date()).getTime() - timer;
console.log("Draw Time = " + timer / 1000);
}
function configHistBars() {
var
numOfPts = (dataStore.getVarData(vars.indep) || []).length;
//figure out total possible bar size
chart.histBarTotal =
parseInt((chart.sizes.width / numOfPts), 10);
if (chart.histBarTotal < 1) {
chart.histBarTotal = 1;
chart.histBarWidth = 1;
chart.histBarMargin = 0;
} else {
chart.histBarWidth =
parseInt((chart.histBarTotal * chart.histBarRatio), 10);
chart.histBarMargin =
chart.histBarTotal - chart.histBarWidth;
}
}
function drawHistBars() {
var
numOfPts = chart.range.numOfPts,
start = chart.range.start,
depVarNames = vars.deps || [],
numDepVars = depVarNames.length,
spacing = chart.pntSpacing.dep,
minLimit = chart.limits.ymin,
chartHeight = chart.sizes.height,
depVarData,
baseLineOffset,
barHeight,
plt_i,
pnt_i;
//set bar width
ctx.lineWidth = chart.histBarWidth;
//move to the chart origin
//ctx.translate( 0, chartHeight + minLimit * spacing );
ctx.save();
//if ymax>0>ymin, we need to find the location of the 0 line to plot from
if (minLimit < 0 && minLimit > 0) {
baseLineOffset = minLimit;
} else {
baseLineOffset = 0;
}
//loop once for each array stored in data.dep
for (plt_i = 0; plt_i < numDepVars; plt_i++) {
depVarData = dataStore.getVarData(depVarNames[plt_i]);
//set stroke color
ctx.strokeStyle = colors.data[plt_i];
//loop through each sub array
for (pnt_i = 0; pnt_i < numOfPts; pnt_i++) {
try {
barHeight = -1 * depVarData[pnt_i + start];
ctx.beginPath();
ctx.moveTo(
chart.histBarTotal * ( pnt_i + 0.5 ), (baseLineOffset * spacing)
);
ctx.lineTo(
chart.histBarTotal * ( pnt_i + 0.5 ), (barHeight * spacing)
);
ctx.stroke();
} catch(err) {
continue;
}
}
}
//translate the coord system back
//ctx.translate( 0, -1 * (chartHeight + minLimit * spacing) );
ctx.restore();
}
function configPolar() {
var
numOfPts = chart.range.numOfPts,
start = chart.range.start,
depVarNames = vars.deps || [],
numDepVars = depVarNames.length,
depVarData,
plt_i,
pnt_i;
//move to center of plot
ctx.translate((chart.sizes.width) / 2, (chart.sizes.height) / 2);
//convert radius values to angles if this is a map
if (flags.map) {
for (plt_i = 0; plt_i < numDepVars; plt_i++) {
depVarData = dataStore.getVarData(depVarNames[plt_i]);
for (pnt_i = 0; pnt_i < numOfPts; pnt_i++) {
depVarData[pnt_i + start] -= 90;
}
}
}
}
function drawPolarGrid() {
var
grid,
radius_i,
angle_i,
spacing = chart.pntSpacing.dep,
maxLimit = chart.limits.ymax;
//rotate the plot
ctx.rotate(chart.zeroAngle);
//set colors
ctx.strokeStyle = chart.colors.grid;
ctx.fillStyle = chart.colors.text;
//Draw a set of radius circles and angle markers if flag is set
if(flags.grid) {
grid = {
"radii": [],
"angles": []
};
//Draw 4 radius circles
grid.radii = [
(0.25 * maxLimit),
(0.5 * maxLimit),
(0.75 * maxLimit),
(maxLimit)
];
ctx.textAlign = "end";
for (radius_i = 0; radius_i < grid.radii.length; radius_i++) {
ctx.beginPath();
ctx.arc(
0, 0, spacing * grid.radii[radius_i],
0,2 * Math.PI,
true
);
ctx.closePath();
ctx.stroke();
//if this is a map, radii should display as latitude angles
if (flags.map) {
ctx.fillText(
90 - grid.radii[radius_i] + "\u00B0",
0, spacing * grid.radii[radius_i] - 5
);
} else {
ctx.fillText(
grid.radii[radius_i],
0, spacing * grid.radii[radius_i] - 5
);
}
}
//Draw 6 angle markers
if (flags.map) {
//grid angles for map should be -180 to 180,
//angles for a polar plot should be 0 to 360
grid.angles = [
0,
Math.PI / 4,
Math.PI / 2,
3 * Math.PI / 4,
Math.PI,
-1 * Math.PI / 4,
-1 * Math.PI / 2,
-3 * Math.PI / 4
];
} else {
grid.angles = [
0,
Math.PI / 4,
Math.PI / 2,
3 * Math.PI / 4,
Math.PI,
5 * Math.PI / 4,
3 * Math.PI / 2,
7 * Math.PI / 4
];
}
ctx.textAlign = "start";
for (angle_i = 0; angle_i < grid.angles.length; angle_i++) {
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.save();
//rotate the coordinate system and draw a straight line
ctx.rotate(chart.polarRot * grid.angles[angle_i]);
ctx.lineTo(maxLimit * spacing , 0);
ctx.stroke();
//move coord system to text location
ctx.textAlign = "end";
ctx.fillText(
(180 * grid.angles[angle_i] / Math.PI) + "\u00B0",
chart.sizes.radius, 0
);
ctx.restore();
}
}
}
function drawPolarPlot() {
var
indepVarData = dataStore.getVarData(vars.indep),
numOfPts = chart.range.numOfPts,
start = chart.range.start,
depVarNames = vars.deps || [],
numDepVars = depVarNames.length,
depVarData,
spacing = chart.pntSpacing.dep,
angle,
radius,
plt_i,
pnt_i;
//rotate the plot so zero lines up with where the use wants
ctx.save();
ctx.rotate( -1 * chart.polarRot * chart.zeroAngle);
ctx.lineWidth = chart.sizes.lineWidth;
pntOffset = -1 * chart.sizes.halfPointSize;
//Draw lines and points
for (plt_i = 0; plt_i < numDepVars; plt_i++) {
//set colors
if (!chart.colors.data[plt_i]) {
chart.colors.data[plt_i] = "Black";
}
ctx.fillStyle = chart.colors.data[plt_i];
ctx.strokeStyle = chart.colors.data[plt_i];
//start line path
if (flags.lines) {
ctx.save();
ctx.rotate(chart.polarRot * angle);
ctx.beginPath();
ctx.rotate(chart.polarRot * angle);
ctx.moveTo(radius * spacing);
ctx.restore();
}
depVarData = dataStore.getVarData(depVarNames[plt_i]);
for (pnt_i = 0; pnt_i < numOfPts; pnt_i++) {
//get the angle and radius of the next point
angle = indepVarData[pnt_i + start] * Math.PI / 180;
radius = depVarData[pnt_i + start];
angle -= 90 * Math.PI / 180;
ctx.save();
ctx.rotate(chart.polarRot * angle);
try {
if (flags.points) {
//rotate coord system, plot point, rotate back
ctx.fillRect(
radius * spacing + pntOffset, pntOffset,
chart.sizes.pointSize, chart.sizes.pointSize
);
}
if (flags.lines) {
//rotate coord system, plot point, rotate back
ctx.lineTo(radius * spacing, 0);
}
} catch(err) {
continue;
}
ctx.restore();
}
//finish line path
if (flags.lines) {
ctx.stroke();
}
//add perimiter label
if (flags.legend) {
ctx.lineWidth = 1;
ctx.save();
ctx.rotate(chart.polarRot * angle);
ctx.beginPath();
ctx.moveTo(chart.pntSpacing.dep * radius, 0);
ctx.lineTo( (chart.sizes.radius + 5), 0 );
ctx.fillText(depVarNames[plt_i], (chart.sizes.radius + 5), 0);
ctx.stroke();
ctx.restore();
}
}
//rotate the plot back
ctx.restore();
}
//////////////////////////Accessors//////////////////////////
self.setCanvasHolder = function(canvasHolderID) {
elms.canvasBox = document.getElementById(canvasHolderID);
};
self.setOrigin = function(x,y) {
chart.origin.x = x;
chart.origin.y = y;
};
self.setCanvasSize = function(height, width, margin) {
chart.sizes.canvas.height = height;
chart.sizes.canvas.width = width;
chart.sizes.canvas.margin = margin;
chart.sizes.height = height - chart.sizes.canvas.margin;
chart.sizes.width = width - chart.sizes.canvas.margin;
chart.sizes.radius =
Math.max(width, height) - (chart.sizes.canvas.margin) / 2;
};
self.setChartSize = function(height, width) {
chart.sizes.height = height;
chart.sizes.width = width;
chart.sizes.canvas.height = height + chart.sizes.canvas.margin;
chart.sizes.canvas.width = width + chart.sizes.canvas.margin;
chart.sizes.radius = Math.max(width, height) / 2;
};
self.setColor = function(type, color) {
chart.colors[type] = color;
};
self.setVars = function setVars(v) {
vars.indep = v.independent;
vars.deps = [].concat(v.dependent);
};