Merge branch 'master' into frac_reg
[dygraphs.git] / dygraph-canvas.js
CommitLineData
6a1aa64f
DV
1// Copyright 2006 Dan Vanderkam (danvdk@gmail.com)
2// All Rights Reserved.
3
4/**
3df0ccf0
DV
5 * @fileoverview Based on PlotKit, but modified to meet the needs of dygraphs.
6 * In particular, support for:
7 * - grid overlays
8 * - error bars
9 * - dygraphs attribute system
6a1aa64f
DV
10 */
11
6a1aa64f 12/**
3df0ccf0 13 * Creates a new DygraphLayout object.
6a1aa64f 14 * @param {Object} options Options for PlotKit.Layout
285a6bda 15 * @return {Object} The DygraphLayout object
6a1aa64f 16 */
efe0829a
DV
17DygraphLayout = function(dygraph, options) {
18 this.dygraph_ = dygraph;
19 this.options = {}; // TODO(danvk): remove, use attr_ instead.
fc80a396 20 Dygraph.update(this.options, options ? options : {});
efe0829a 21 this.datasets = new Array();
937029df 22 this.annotations = new Array();
6a1aa64f 23};
efe0829a
DV
24
25DygraphLayout.prototype.attr_ = function(name) {
26 return this.dygraph_.attr_(name);
27};
28
29DygraphLayout.prototype.addDataset = function(setname, set_xy) {
30 this.datasets[setname] = set_xy;
31};
32
5c528fa2
DV
33DygraphLayout.prototype.setAnnotations = function(ann) {
34 // The Dygraph object's annotations aren't parsed. We parse them here and
35 // save a copy.
973e2b79 36 this.annotations = [];
5c528fa2
DV
37 var parse = this.attr_('xValueParser');
38 for (var i = 0; i < ann.length; i++) {
39 var a = {};
a685723c 40 if (!ann[i].xval && !ann[i].x) {
5c528fa2
DV
41 this.dygraph_.error("Annotations must have an 'x' property");
42 return;
43 }
ce5e8d36 44 if (ann[i].icon &&
33030f33
DV
45 !(ann[i].hasOwnProperty('width') &&
46 ann[i].hasOwnProperty('height'))) {
47 this.dygraph_.error("Must set width and height when setting " +
ce5e8d36
DV
48 "annotation.icon property");
49 return;
50 }
5c528fa2 51 Dygraph.update(a, ann[i]);
a685723c 52 if (!a.xval) a.xval = parse(a.x);
5c528fa2 53 this.annotations.push(a);
ce49c2fa 54 }
ce49c2fa
DV
55};
56
efe0829a
DV
57DygraphLayout.prototype.evaluate = function() {
58 this._evaluateLimits();
59 this._evaluateLineCharts();
60 this._evaluateLineTicks();
ce49c2fa 61 this._evaluateAnnotations();
efe0829a
DV
62};
63
64DygraphLayout.prototype._evaluateLimits = function() {
65 this.minxval = this.maxxval = null;
f6401bf6
DV
66 if (this.options.dateWindow) {
67 this.minxval = this.options.dateWindow[0];
68 this.maxxval = this.options.dateWindow[1];
69 } else {
70 for (var name in this.datasets) {
71 if (!this.datasets.hasOwnProperty(name)) continue;
72 var series = this.datasets[name];
48841144
NN
73 if (series.length > 1) {
74 var x1 = series[0][0];
75 if (!this.minxval || x1 < this.minxval) this.minxval = x1;
76
77 var x2 = series[series.length - 1][0];
78 if (!this.maxxval || x2 > this.maxxval) this.maxxval = x2;
79 }
f6401bf6 80 }
efe0829a
DV
81 }
82 this.xrange = this.maxxval - this.minxval;
83 this.xscale = (this.xrange != 0 ? 1/this.xrange : 1.0);
84
85 this.minyval = this.options.yAxis[0];
86 this.maxyval = this.options.yAxis[1];
87 this.yrange = this.maxyval - this.minyval;
88 this.yscale = (this.yrange != 0 ? 1/this.yrange : 1.0);
89};
90
91DygraphLayout.prototype._evaluateLineCharts = function() {
92 // add all the rects
93 this.points = new Array();
94 for (var setName in this.datasets) {
85b99f0b
DV
95 if (!this.datasets.hasOwnProperty(setName)) continue;
96
97 var dataset = this.datasets[setName];
98 for (var j = 0; j < dataset.length; j++) {
99 var item = dataset[j];
100 var point = {
ff00d3e2 101 // TODO(danvk): here
85b99f0b
DV
102 x: ((parseFloat(item[0]) - this.minxval) * this.xscale),
103 y: 1.0 - ((parseFloat(item[1]) - this.minyval) * this.yscale),
104 xval: parseFloat(item[0]),
105 yval: parseFloat(item[1]),
106 name: setName
107 };
108
1a26f3fb 109 this.points.push(point);
85b99f0b 110 }
efe0829a
DV
111 }
112};
113
114DygraphLayout.prototype._evaluateLineTicks = function() {
115 this.xticks = new Array();
116 for (var i = 0; i < this.options.xTicks.length; i++) {
117 var tick = this.options.xTicks[i];
118 var label = tick.label;
119 var pos = this.xscale * (tick.v - this.minxval);
120 if ((pos >= 0.0) && (pos <= 1.0)) {
121 this.xticks.push([pos, label]);
122 }
123 }
124
125 this.yticks = new Array();
126 for (var i = 0; i < this.options.yTicks.length; i++) {
127 var tick = this.options.yTicks[i];
128 var label = tick.label;
129 var pos = 1.0 - (this.yscale * (tick.v - this.minyval));
130 if ((pos >= 0.0) && (pos <= 1.0)) {
131 this.yticks.push([pos, label]);
132 }
133 }
134};
135
6a1aa64f
DV
136
137/**
138 * Behaves the same way as PlotKit.Layout, but also copies the errors
139 * @private
140 */
285a6bda 141DygraphLayout.prototype.evaluateWithError = function() {
6a1aa64f
DV
142 this.evaluate();
143 if (!this.options.errorBars) return;
144
145 // Copy over the error terms
146 var i = 0; // index in this.points
147 for (var setName in this.datasets) {
85b99f0b
DV
148 if (!this.datasets.hasOwnProperty(setName)) continue;
149 var j = 0;
150 var dataset = this.datasets[setName];
151 for (var j = 0; j < dataset.length; j++, i++) {
152 var item = dataset[j];
153 var xv = parseFloat(item[0]);
154 var yv = parseFloat(item[1]);
155
156 if (xv == this.points[i].xval &&
157 yv == this.points[i].yval) {
158 this.points[i].errorMinus = parseFloat(item[2]);
159 this.points[i].errorPlus = parseFloat(item[3]);
160 }
161 }
6a1aa64f
DV
162 }
163};
164
ce49c2fa
DV
165DygraphLayout.prototype._evaluateAnnotations = function() {
166 // Add the annotations to the point to which they belong.
167 // Make a map from (setName, xval) to annotation for quick lookups.
168 var annotations = {};
169 for (var i = 0; i < this.annotations.length; i++) {
170 var a = this.annotations[i];
171 annotations[a.xval + "," + a.series] = a;
172 }
173
174 this.annotated_points = [];
175 for (var i = 0; i < this.points.length; i++) {
176 var p = this.points[i];
177 var k = p.xval + "," + p.name;
178 if (k in annotations) {
179 p.annotation = annotations[k];
180 this.annotated_points.push(p);
181 }
182 }
183};
184
6a1aa64f
DV
185/**
186 * Convenience function to remove all the data sets from a graph
187 */
285a6bda 188DygraphLayout.prototype.removeAllDatasets = function() {
6a1aa64f
DV
189 delete this.datasets;
190 this.datasets = new Array();
191};
192
193/**
194 * Change the values of various layout options
195 * @param {Object} new_options an associative array of new properties
196 */
285a6bda 197DygraphLayout.prototype.updateOptions = function(new_options) {
fc80a396 198 Dygraph.update(this.options, new_options ? new_options : {});
6a1aa64f
DV
199};
200
667d510b 201/**
202 * Return a copy of the point at the indicated index, with its yval unstacked.
203 * @param int index of point in layout_.points
204 */
8c03ba63 205DygraphLayout.prototype.unstackPointAtIndex = function(idx) {
667d510b 206 var point = this.points[idx];
207
208 // Clone the point since we modify it
209 var unstackedPoint = {};
210 for (var i in point) {
211 unstackedPoint[i] = point[i];
212 }
213
214 if (!this.attr_("stackedGraph")) {
215 return unstackedPoint;
216 }
217
218 // The unstacked yval is equal to the current yval minus the yval of the
219 // next point at the same xval.
220 for (var i = idx+1; i < this.points.length; i++) {
221 if (this.points[i].xval == point.xval) {
222 unstackedPoint.yval -= this.points[i].yval;
223 break;
224 }
225 }
226
227 return unstackedPoint;
228}
229
6a1aa64f
DV
230// Subclass PlotKit.CanvasRenderer to add:
231// 1. X/Y grid overlay
232// 2. Ability to draw error bars (if required)
233
234/**
235 * Sets some PlotKit.CanvasRenderer options
236 * @param {Object} element The canvas to attach to
285a6bda 237 * @param {Layout} layout The DygraphLayout object for this graph.
6a1aa64f
DV
238 * @param {Object} options Options to pass on to CanvasRenderer
239 */
9317362d
DV
240DygraphCanvasRenderer = function(dygraph, element, layout, options) {
241 // TODO(danvk): remove options, just use dygraph.attr_.
9317362d 242 this.dygraph_ = dygraph;
fbe31dc8
DV
243
244 // default options
245 this.options = {
f474c2a3
DV
246 "strokeWidth": 0.5,
247 "drawXAxis": true,
248 "drawYAxis": true,
249 "axisLineColor": "black",
250 "axisLineWidth": 0.5,
251 "axisTickSize": 3,
252 "axisLabelColor": "black",
253 "axisLabelFont": "Arial",
254 "axisLabelFontSize": 9,
255 "axisLabelWidth": 50,
256 "drawYGrid": true,
257 "drawXGrid": true,
43af96e7 258 "gridLineColor": "rgb(128,128,128)",
e7746234
EC
259 "fillAlpha": 0.15,
260 "underlayCallback": null
fbe31dc8 261 };
fc80a396 262 Dygraph.update(this.options, options);
6a1aa64f 263
fbe31dc8 264 this.layout = layout;
b0c3b730 265 this.element = element;
fbe31dc8
DV
266 this.container = this.element.parentNode;
267
fbe31dc8
DV
268 this.height = this.element.height;
269 this.width = this.element.width;
270
271 // --- check whether everything is ok before we return
272 if (!this.isIE && !(DygraphCanvasRenderer.isSupported(this.element)))
273 throw "Canvas is not supported.";
274
275 // internal state
276 this.xlabels = new Array();
277 this.ylabels = new Array();
ce49c2fa 278 this.annotations = new Array();
fbe31dc8
DV
279
280 this.area = {
281 x: this.options.yAxisLabelWidth + 2 * this.options.axisTickSize,
282 y: 0
283 };
284 this.area.w = this.width - this.area.x - this.options.rightGap;
285 this.area.h = this.height - this.options.axisLabelFontSize -
286 2 * this.options.axisTickSize;
287
b0c3b730
DV
288 this.container.style.position = "relative";
289 this.container.style.width = this.width + "px";
fbe31dc8
DV
290};
291
292DygraphCanvasRenderer.prototype.clear = function() {
293 if (this.isIE) {
294 // VML takes a while to start up, so we just poll every this.IEDelay
295 try {
296 if (this.clearDelay) {
297 this.clearDelay.cancel();
298 this.clearDelay = null;
299 }
300 var context = this.element.getContext("2d");
301 }
302 catch (e) {
76171648 303 // TODO(danvk): this is broken, since MochiKit.Async is gone.
fbe31dc8
DV
304 this.clearDelay = MochiKit.Async.wait(this.IEDelay);
305 this.clearDelay.addCallback(bind(this.clear, this));
306 return;
307 }
308 }
309
310 var context = this.element.getContext("2d");
311 context.clearRect(0, 0, this.width, this.height);
312
2160ed4a 313 for (var i = 0; i < this.xlabels.length; i++) {
b0c3b730
DV
314 var el = this.xlabels[i];
315 el.parentNode.removeChild(el);
2160ed4a
DV
316 }
317 for (var i = 0; i < this.ylabels.length; i++) {
b0c3b730
DV
318 var el = this.ylabels[i];
319 el.parentNode.removeChild(el);
2160ed4a 320 }
ce49c2fa
DV
321 for (var i = 0; i < this.annotations.length; i++) {
322 var el = this.annotations[i];
323 el.parentNode.removeChild(el);
324 }
fbe31dc8
DV
325 this.xlabels = new Array();
326 this.ylabels = new Array();
ce49c2fa 327 this.annotations = new Array();
fbe31dc8
DV
328};
329
330
331DygraphCanvasRenderer.isSupported = function(canvasName) {
332 var canvas = null;
333 try {
21d3323f 334 if (typeof(canvasName) == 'undefined' || canvasName == null)
b0c3b730 335 canvas = document.createElement("canvas");
fbe31dc8 336 else
b0c3b730 337 canvas = canvasName;
fbe31dc8
DV
338 var context = canvas.getContext("2d");
339 }
340 catch (e) {
341 var ie = navigator.appVersion.match(/MSIE (\d\.\d)/);
342 var opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
343 if ((!ie) || (ie[1] < 6) || (opera))
344 return false;
345 return true;
346 }
347 return true;
6a1aa64f 348};
6a1aa64f
DV
349
350/**
351 * Draw an X/Y grid on top of the existing plot
352 */
285a6bda 353DygraphCanvasRenderer.prototype.render = function() {
6a1aa64f
DV
354 // Draw the new X/Y grid
355 var ctx = this.element.getContext("2d");
e7746234
EC
356
357 if (this.options.underlayCallback) {
d9e6fa47 358 this.options.underlayCallback(ctx, this.area, this.layout, this.dygraph_);
e7746234
EC
359 }
360
6a1aa64f
DV
361 if (this.options.drawYGrid) {
362 var ticks = this.layout.yticks;
363 ctx.save();
f2f24402 364 ctx.strokeStyle = this.options.gridLineColor;
6a1aa64f
DV
365 ctx.lineWidth = this.options.axisLineWidth;
366 for (var i = 0; i < ticks.length; i++) {
367 var x = this.area.x;
368 var y = this.area.y + ticks[i][0] * this.area.h;
369 ctx.beginPath();
370 ctx.moveTo(x, y);
371 ctx.lineTo(x + this.area.w, y);
372 ctx.closePath();
373 ctx.stroke();
374 }
375 }
376
377 if (this.options.drawXGrid) {
378 var ticks = this.layout.xticks;
379 ctx.save();
f2f24402 380 ctx.strokeStyle = this.options.gridLineColor;
6a1aa64f
DV
381 ctx.lineWidth = this.options.axisLineWidth;
382 for (var i=0; i<ticks.length; i++) {
383 var x = this.area.x + ticks[i][0] * this.area.w;
384 var y = this.area.y + this.area.h;
385 ctx.beginPath();
386 ctx.moveTo(x, y);
387 ctx.lineTo(x, this.area.y);
388 ctx.closePath();
389 ctx.stroke();
390 }
391 }
2ce09b19
DV
392
393 // Do the ordinary rendering, as before
2ce09b19 394 this._renderLineChart();
fbe31dc8 395 this._renderAxis();
ce49c2fa 396 this._renderAnnotations();
fbe31dc8
DV
397};
398
399
400DygraphCanvasRenderer.prototype._renderAxis = function() {
401 if (!this.options.drawXAxis && !this.options.drawYAxis)
402 return;
403
404 var context = this.element.getContext("2d");
405
34fedff8
DV
406 var labelStyle = {
407 "position": "absolute",
408 "fontSize": this.options.axisLabelFontSize + "px",
409 "zIndex": 10,
f474c2a3 410 "color": this.options.axisLabelColor,
34fedff8
DV
411 "width": this.options.axisLabelWidth + "px",
412 "overflow": "hidden"
413 };
414 var makeDiv = function(txt) {
415 var div = document.createElement("div");
416 for (var name in labelStyle) {
85b99f0b
DV
417 if (labelStyle.hasOwnProperty(name)) {
418 div.style[name] = labelStyle[name];
419 }
fbe31dc8 420 }
34fedff8
DV
421 div.appendChild(document.createTextNode(txt));
422 return div;
fbe31dc8
DV
423 };
424
425 // axis lines
426 context.save();
f474c2a3 427 context.strokeStyle = this.options.axisLineColor;
fbe31dc8
DV
428 context.lineWidth = this.options.axisLineWidth;
429
fbe31dc8 430 if (this.options.drawYAxis) {
8b7a0cc3 431 if (this.layout.yticks && this.layout.yticks.length > 0) {
2160ed4a
DV
432 for (var i = 0; i < this.layout.yticks.length; i++) {
433 var tick = this.layout.yticks[i];
fbe31dc8
DV
434 if (typeof(tick) == "function") return;
435 var x = this.area.x;
436 var y = this.area.y + tick[0] * this.area.h;
437 context.beginPath();
438 context.moveTo(x, y);
439 context.lineTo(x - this.options.axisTickSize, y);
440 context.closePath();
441 context.stroke();
442
34fedff8 443 var label = makeDiv(tick[1]);
fbe31dc8
DV
444 var top = (y - this.options.axisLabelFontSize / 2);
445 if (top < 0) top = 0;
446
447 if (top + this.options.axisLabelFontSize + 3 > this.height) {
448 label.style.bottom = "0px";
449 } else {
450 label.style.top = top + "px";
451 }
452 label.style.left = "0px";
453 label.style.textAlign = "right";
454 label.style.width = this.options.yAxisLabelWidth + "px";
b0c3b730 455 this.container.appendChild(label);
fbe31dc8 456 this.ylabels.push(label);
2160ed4a 457 }
fbe31dc8
DV
458
459 // The lowest tick on the y-axis often overlaps with the leftmost
460 // tick on the x-axis. Shift the bottom tick up a little bit to
461 // compensate if necessary.
462 var bottomTick = this.ylabels[0];
463 var fontSize = this.options.axisLabelFontSize;
464 var bottom = parseInt(bottomTick.style.top) + fontSize;
465 if (bottom > this.height - fontSize) {
466 bottomTick.style.top = (parseInt(bottomTick.style.top) -
467 fontSize / 2) + "px";
468 }
469 }
470
471 context.beginPath();
472 context.moveTo(this.area.x, this.area.y);
473 context.lineTo(this.area.x, this.area.y + this.area.h);
474 context.closePath();
475 context.stroke();
476 }
477
478 if (this.options.drawXAxis) {
479 if (this.layout.xticks) {
2160ed4a
DV
480 for (var i = 0; i < this.layout.xticks.length; i++) {
481 var tick = this.layout.xticks[i];
fbe31dc8
DV
482 if (typeof(dataset) == "function") return;
483
484 var x = this.area.x + tick[0] * this.area.w;
485 var y = this.area.y + this.area.h;
486 context.beginPath();
487 context.moveTo(x, y);
488 context.lineTo(x, y + this.options.axisTickSize);
489 context.closePath();
490 context.stroke();
491
34fedff8 492 var label = makeDiv(tick[1]);
fbe31dc8
DV
493 label.style.textAlign = "center";
494 label.style.bottom = "0px";
495
496 var left = (x - this.options.axisLabelWidth/2);
497 if (left + this.options.axisLabelWidth > this.width) {
498 left = this.width - this.options.xAxisLabelWidth;
499 label.style.textAlign = "right";
500 }
501 if (left < 0) {
502 left = 0;
503 label.style.textAlign = "left";
504 }
505
506 label.style.left = left + "px";
507 label.style.width = this.options.xAxisLabelWidth + "px";
b0c3b730 508 this.container.appendChild(label);
fbe31dc8 509 this.xlabels.push(label);
2160ed4a 510 }
fbe31dc8
DV
511 }
512
513 context.beginPath();
514 context.moveTo(this.area.x, this.area.y + this.area.h);
515 context.lineTo(this.area.x + this.area.w, this.area.y + this.area.h);
516 context.closePath();
517 context.stroke();
518 }
519
520 context.restore();
6a1aa64f
DV
521};
522
fbe31dc8 523
ce49c2fa
DV
524DygraphCanvasRenderer.prototype._renderAnnotations = function() {
525 var annotationStyle = {
526 "position": "absolute",
527 "fontSize": this.options.axisLabelFontSize + "px",
528 "zIndex": 10,
3bf2fa91 529 "overflow": "hidden"
ce49c2fa
DV
530 };
531
ab5e5c75
DV
532 var bindEvt = function(eventName, classEventName, p, self) {
533 return function(e) {
534 var a = p.annotation;
535 if (a.hasOwnProperty(eventName)) {
536 a[eventName](a, p, self.dygraph_, e);
537 } else if (self.dygraph_.attr_(classEventName)) {
538 self.dygraph_.attr_(classEventName)(a, p, self.dygraph_,e );
539 }
540 };
541 }
542
ce49c2fa
DV
543 // Get a list of point with annotations.
544 var points = this.layout.annotated_points;
545 for (var i = 0; i < points.length; i++) {
546 var p = points[i];
e6d53148
DV
547 if (p.canvasx < this.area.x || p.canvasx > this.area.x + this.area.w) {
548 continue;
549 }
550
ce5e8d36
DV
551 var a = p.annotation;
552 var tick_height = 6;
553 if (a.hasOwnProperty("tickHeight")) {
554 tick_height = a.tickHeight;
9a40897e
DV
555 }
556
ce49c2fa
DV
557 var div = document.createElement("div");
558 for (var name in annotationStyle) {
559 if (annotationStyle.hasOwnProperty(name)) {
560 div.style[name] = annotationStyle[name];
561 }
562 }
ce5e8d36
DV
563 if (!a.hasOwnProperty('icon')) {
564 div.className = "dygraphDefaultAnnotation";
565 }
566 if (a.hasOwnProperty('cssClass')) {
567 div.className += " " + a.cssClass;
568 }
569
a5ad69cc
DV
570 var width = a.hasOwnProperty('width') ? a.width : 16;
571 var height = a.hasOwnProperty('height') ? a.height : 16;
ce5e8d36
DV
572 if (a.hasOwnProperty('icon')) {
573 var img = document.createElement("img");
574 img.src = a.icon;
33030f33
DV
575 img.width = width;
576 img.height = height;
ce5e8d36
DV
577 div.appendChild(img);
578 } else if (p.annotation.hasOwnProperty('shortText')) {
579 div.appendChild(document.createTextNode(p.annotation.shortText));
5c528fa2 580 }
ce5e8d36 581 div.style.left = (p.canvasx - width / 2) + "px";
d14b9eed
DV
582 if (a.attachAtBottom) {
583 div.style.top = (this.area.h - height - tick_height) + "px";
584 } else {
585 div.style.top = (p.canvasy - height - tick_height) + "px";
586 }
ce5e8d36
DV
587 div.style.width = width + "px";
588 div.style.height = height + "px";
ce49c2fa
DV
589 div.title = p.annotation.text;
590 div.style.color = this.colors[p.name];
591 div.style.borderColor = this.colors[p.name];
e6d53148 592 a.div = div;
ab5e5c75 593
9a40897e
DV
594 Dygraph.addEvent(div, 'click',
595 bindEvt('clickHandler', 'annotationClickHandler', p, this));
596 Dygraph.addEvent(div, 'mouseover',
597 bindEvt('mouseOverHandler', 'annotationMouseOverHandler', p, this));
598 Dygraph.addEvent(div, 'mouseout',
599 bindEvt('mouseOutHandler', 'annotationMouseOutHandler', p, this));
600 Dygraph.addEvent(div, 'dblclick',
601 bindEvt('dblClickHandler', 'annotationDblClickHandler', p, this));
ab5e5c75 602
ce49c2fa
DV
603 this.container.appendChild(div);
604 this.annotations.push(div);
9a40897e
DV
605
606 var ctx = this.element.getContext("2d");
607 ctx.strokeStyle = this.colors[p.name];
608 ctx.beginPath();
d14b9eed
DV
609 if (!a.attachAtBottom) {
610 ctx.moveTo(p.canvasx, p.canvasy);
611 ctx.lineTo(p.canvasx, p.canvasy - 2 - tick_height);
612 } else {
613 ctx.moveTo(p.canvasx, this.area.h);
614 ctx.lineTo(p.canvasx, this.area.h - 2 - tick_height);
615 }
9a40897e
DV
616 ctx.closePath();
617 ctx.stroke();
ce49c2fa
DV
618 }
619};
620
621
6a1aa64f
DV
622/**
623 * Overrides the CanvasRenderer method to draw error bars
624 */
285a6bda 625DygraphCanvasRenderer.prototype._renderLineChart = function() {
6a1aa64f
DV
626 var context = this.element.getContext("2d");
627 var colorCount = this.options.colorScheme.length;
628 var colorScheme = this.options.colorScheme;
43af96e7 629 var fillAlpha = this.options.fillAlpha;
6a1aa64f 630 var errorBars = this.layout.options.errorBars;
5954ef32 631 var fillGraph = this.layout.options.fillGraph;
354e15ab 632 var stackedGraph = this.layout.options.stackedGraph;
afdc483f 633 var stepPlot = this.layout.options.stepPlot;
21d3323f
DV
634
635 var setNames = [];
ca43052c 636 for (var name in this.layout.datasets) {
85b99f0b
DV
637 if (this.layout.datasets.hasOwnProperty(name)) {
638 setNames.push(name);
639 }
ca43052c 640 }
21d3323f 641 var setCount = setNames.length;
6a1aa64f 642
f032c51d
AV
643 this.colors = {}
644 for (var i = 0; i < setCount; i++) {
645 this.colors[setNames[i]] = colorScheme[i % colorCount];
646 }
647
ff00d3e2
DV
648 // Update Points
649 // TODO(danvk): here
2160ed4a
DV
650 for (var i = 0; i < this.layout.points.length; i++) {
651 var point = this.layout.points[i];
6a1aa64f
DV
652 point.canvasx = this.area.w * point.x + this.area.x;
653 point.canvasy = this.area.h * point.y + this.area.y;
654 }
6a1aa64f
DV
655
656 // create paths
9317362d 657 var isOK = function(x) { return x && !isNaN(x); };
6a1aa64f 658
80aaae18
DV
659 var ctx = context;
660 if (errorBars) {
6a834bbb
DV
661 if (fillGraph) {
662 this.dygraph_.warn("Can't use fillGraph option with error bars");
663 }
664
6a1aa64f
DV
665 for (var i = 0; i < setCount; i++) {
666 var setName = setNames[i];
f032c51d 667 var color = this.colors[setName];
6a1aa64f
DV
668
669 // setup graphics context
80aaae18 670 ctx.save();
56623f3b 671 var prevX = NaN;
afdc483f 672 var prevY = NaN;
6a1aa64f 673 var prevYs = [-1, -1];
6a1aa64f 674 var yscale = this.layout.yscale;
f474c2a3
DV
675 // should be same color as the lines but only 15% opaque.
676 var rgb = new RGBColor(color);
43af96e7
NK
677 var err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
678 fillAlpha + ')';
f474c2a3 679 ctx.fillStyle = err_color;
05c9d0c4
DV
680 ctx.beginPath();
681 for (var j = 0; j < this.layout.points.length; j++) {
682 var point = this.layout.points[j];
6a1aa64f 683 if (point.name == setName) {
5954ef32 684 if (!isOK(point.y)) {
56623f3b 685 prevX = NaN;
ae85914a 686 continue;
5011e7a1 687 }
ce49c2fa 688
ff00d3e2 689 // TODO(danvk): here
afdc483f
NN
690 if (stepPlot) {
691 var newYs = [ prevY - point.errorPlus * yscale,
47600757 692 prevY + point.errorMinus * yscale ];
afdc483f
NN
693 prevY = point.y;
694 } else {
695 var newYs = [ point.y - point.errorPlus * yscale,
47600757 696 point.y + point.errorMinus * yscale ];
afdc483f 697 }
6a1aa64f
DV
698 newYs[0] = this.area.h * newYs[0] + this.area.y;
699 newYs[1] = this.area.h * newYs[1] + this.area.y;
56623f3b 700 if (!isNaN(prevX)) {
afdc483f 701 if (stepPlot) {
47600757 702 ctx.moveTo(prevX, newYs[0]);
afdc483f 703 } else {
47600757 704 ctx.moveTo(prevX, prevYs[0]);
afdc483f 705 }
5954ef32
DV
706 ctx.lineTo(point.canvasx, newYs[0]);
707 ctx.lineTo(point.canvasx, newYs[1]);
afdc483f 708 if (stepPlot) {
47600757 709 ctx.lineTo(prevX, newYs[1]);
afdc483f 710 } else {
47600757 711 ctx.lineTo(prevX, prevYs[1]);
afdc483f 712 }
5954ef32
DV
713 ctx.closePath();
714 }
354e15ab 715 prevYs = newYs;
5954ef32
DV
716 prevX = point.canvasx;
717 }
718 }
719 ctx.fill();
720 }
721 } else if (fillGraph) {
354e15ab
DE
722 var axisY = 1.0 + this.layout.minyval * this.layout.yscale;
723 if (axisY < 0.0) axisY = 0.0;
724 else if (axisY > 1.0) axisY = 1.0;
725 axisY = this.area.h * axisY + this.area.y;
726
727 var baseline = [] // for stacked graphs: baseline for filling
728
729 // process sets in reverse order (needed for stacked graphs)
730 for (var i = setCount - 1; i >= 0; i--) {
5954ef32 731 var setName = setNames[i];
f032c51d 732 var color = this.colors[setName];
5954ef32
DV
733
734 // setup graphics context
735 ctx.save();
56623f3b 736 var prevX = NaN;
5954ef32 737 var prevYs = [-1, -1];
5954ef32
DV
738 var yscale = this.layout.yscale;
739 // should be same color as the lines but only 15% opaque.
740 var rgb = new RGBColor(color);
43af96e7
NK
741 var err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
742 fillAlpha + ')';
5954ef32
DV
743 ctx.fillStyle = err_color;
744 ctx.beginPath();
745 for (var j = 0; j < this.layout.points.length; j++) {
746 var point = this.layout.points[j];
5954ef32
DV
747 if (point.name == setName) {
748 if (!isOK(point.y)) {
56623f3b 749 prevX = NaN;
5954ef32
DV
750 continue;
751 }
354e15ab
DE
752 var newYs;
753 if (stackedGraph) {
754 lastY = baseline[point.canvasx];
755 if (lastY === undefined) lastY = axisY;
756 baseline[point.canvasx] = point.canvasy;
757 newYs = [ point.canvasy, lastY ];
758 } else {
759 newYs = [ point.canvasy, axisY ];
760 }
56623f3b 761 if (!isNaN(prevX)) {
05c9d0c4 762 ctx.moveTo(prevX, prevYs[0]);
afdc483f 763 if (stepPlot) {
47600757 764 ctx.lineTo(point.canvasx, prevYs[0]);
afdc483f 765 } else {
47600757 766 ctx.lineTo(point.canvasx, newYs[0]);
afdc483f 767 }
05c9d0c4
DV
768 ctx.lineTo(point.canvasx, newYs[1]);
769 ctx.lineTo(prevX, prevYs[1]);
770 ctx.closePath();
6a1aa64f 771 }
354e15ab 772 prevYs = newYs;
6a1aa64f
DV
773 prevX = point.canvasx;
774 }
05c9d0c4 775 }
6a1aa64f
DV
776 ctx.fill();
777 }
80aaae18
DV
778 }
779
780 for (var i = 0; i < setCount; i++) {
781 var setName = setNames[i];
f032c51d 782 var color = this.colors[setName];
227b93cc 783 var strokeWidth = this.dygraph_.attr_("strokeWidth", setName);
80aaae18
DV
784
785 // setup graphics context
786 context.save();
787 var point = this.layout.points[0];
227b93cc 788 var pointSize = this.dygraph_.attr_("pointSize", setName);
80aaae18 789 var prevX = null, prevY = null;
227b93cc 790 var drawPoints = this.dygraph_.attr_("drawPoints", setName);
80aaae18
DV
791 var points = this.layout.points;
792 for (var j = 0; j < points.length; j++) {
793 var point = points[j];
794 if (point.name == setName) {
795 if (!isOK(point.canvasy)) {
5d13ef68 796 if (stepPlot && prevX != null) {
0599d13b
NN
797 // Draw a horizontal line to the start of the missing data
798 ctx.beginPath();
799 ctx.strokeStyle = color;
800 ctx.lineWidth = this.options.strokeWidth;
801 ctx.moveTo(prevX, prevY);
802 ctx.lineTo(point.canvasx, prevY);
803 ctx.stroke();
804 }
80aaae18
DV
805 // this will make us move to the next point, not draw a line to it.
806 prevX = prevY = null;
807 } else {
808 // A point is "isolated" if it is non-null but both the previous
809 // and next points are null.
810 var isIsolated = (!prevX && (j == points.length - 1 ||
811 !isOK(points[j+1].canvasy)));
812
813 if (!prevX) {
814 prevX = point.canvasx;
815 prevY = point.canvasy;
816 } else {
46dde5f9
DV
817 // TODO(danvk): figure out why this conditional is necessary.
818 if (strokeWidth) {
819 ctx.beginPath();
820 ctx.strokeStyle = color;
821 ctx.lineWidth = strokeWidth;
822 ctx.moveTo(prevX, prevY);
823 if (stepPlot) {
824 ctx.lineTo(point.canvasx, prevY);
825 }
826 prevX = point.canvasx;
827 prevY = point.canvasy;
828 ctx.lineTo(prevX, prevY);
829 ctx.stroke();
afdc483f 830 }
80aaae18
DV
831 }
832
833 if (drawPoints || isIsolated) {
834 ctx.beginPath();
835 ctx.fillStyle = color;
7bf6a9fe
DV
836 ctx.arc(point.canvasx, point.canvasy, pointSize,
837 0, 2 * Math.PI, false);
80aaae18
DV
838 ctx.fill();
839 }
840 }
841 }
842 }
843 }
6a1aa64f 844
6a1aa64f
DV
845 context.restore();
846};