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