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