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