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