clipping rectangles for interaction layer
[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 el.parentNode.removeChild(el);
351 }
352 for (var i = 0; i < this.ylabels.length; i++) {
353 var el = this.ylabels[i];
354 el.parentNode.removeChild(el);
355 }
356 for (var i = 0; i < this.annotations.length; i++) {
357 var el = this.annotations[i];
358 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
390 var ctx = this.element.getContext("2d");
391
392 if (this.options.underlayCallback) {
393 this.options.underlayCallback(ctx, this.area, this.layout, this.dygraph_);
394 }
395
396 if (this.options.drawYGrid) {
397 var ticks = this.layout.yticks;
398 ctx.save();
399 ctx.strokeStyle = this.options.gridLineColor;
400 ctx.lineWidth = this.options.axisLineWidth;
401 for (var i = 0; i < ticks.length; i++) {
402 // TODO(danvk): allow secondary axes to draw a grid, too.
403 if (ticks[i][0] != 0) continue;
404 var x = this.area.x;
405 var y = this.area.y + ticks[i][1] * this.area.h;
406 ctx.beginPath();
407 ctx.moveTo(x, y);
408 ctx.lineTo(x + this.area.w, y);
409 ctx.closePath();
410 ctx.stroke();
411 }
412 }
413
414 if (this.options.drawXGrid) {
415 var ticks = this.layout.xticks;
416 ctx.save();
417 ctx.strokeStyle = this.options.gridLineColor;
418 ctx.lineWidth = this.options.axisLineWidth;
419 for (var i=0; i<ticks.length; i++) {
420 var x = this.area.x + ticks[i][0] * this.area.w;
421 var y = this.area.y + this.area.h;
422 ctx.beginPath();
423 ctx.moveTo(x, y);
424 ctx.lineTo(x, this.area.y);
425 ctx.closePath();
426 ctx.stroke();
427 }
428 }
429
430 // Do the ordinary rendering, as before
431 this._renderLineChart();
432 this._renderAxis();
433 this._renderAnnotations();
434 };
435
436
437 DygraphCanvasRenderer.prototype._renderAxis = function() {
438 if (!this.options.drawXAxis && !this.options.drawYAxis)
439 return;
440
441 var context = this.element.getContext("2d");
442
443 var labelStyle = {
444 "position": "absolute",
445 "fontSize": this.options.axisLabelFontSize + "px",
446 "zIndex": 10,
447 "color": this.options.axisLabelColor,
448 "width": this.options.axisLabelWidth + "px",
449 "overflow": "hidden"
450 };
451 var makeDiv = function(txt) {
452 var div = document.createElement("div");
453 for (var name in labelStyle) {
454 if (labelStyle.hasOwnProperty(name)) {
455 div.style[name] = labelStyle[name];
456 }
457 }
458 div.appendChild(document.createTextNode(txt));
459 return div;
460 };
461
462 // axis lines
463 context.save();
464 context.strokeStyle = this.options.axisLineColor;
465 context.lineWidth = this.options.axisLineWidth;
466
467 if (this.options.drawYAxis) {
468 if (this.layout.yticks && this.layout.yticks.length > 0) {
469 for (var i = 0; i < this.layout.yticks.length; i++) {
470 var tick = this.layout.yticks[i];
471 if (typeof(tick) == "function") return;
472 var x = this.area.x;
473 var sgn = 1;
474 if (tick[0] == 1) { // right-side y-axis
475 x = this.area.x + this.area.w;
476 sgn = -1;
477 }
478 var y = this.area.y + tick[1] * this.area.h;
479 context.beginPath();
480 context.moveTo(x, y);
481 context.lineTo(x - sgn * 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 if (this.dygraph_.numAxes() == 2) {
526 context.beginPath();
527 context.moveTo(this.area.x + this.area.w, this.area.y);
528 context.lineTo(this.area.x + this.area.w, this.area.y + this.area.h);
529 context.closePath();
530 context.stroke();
531 }
532 }
533
534 if (this.options.drawXAxis) {
535 if (this.layout.xticks) {
536 for (var i = 0; i < this.layout.xticks.length; i++) {
537 var tick = this.layout.xticks[i];
538 if (typeof(dataset) == "function") return;
539
540 var x = this.area.x + tick[0] * this.area.w;
541 var y = this.area.y + this.area.h;
542 context.beginPath();
543 context.moveTo(x, y);
544 context.lineTo(x, y + this.options.axisTickSize);
545 context.closePath();
546 context.stroke();
547
548 var label = makeDiv(tick[1]);
549 label.style.textAlign = "center";
550 label.style.bottom = "0px";
551
552 var left = (x - this.options.axisLabelWidth/2);
553 if (left + this.options.axisLabelWidth > this.width) {
554 left = this.width - this.options.xAxisLabelWidth;
555 label.style.textAlign = "right";
556 }
557 if (left < 0) {
558 left = 0;
559 label.style.textAlign = "left";
560 }
561
562 label.style.left = left + "px";
563 label.style.width = this.options.xAxisLabelWidth + "px";
564 this.container.appendChild(label);
565 this.xlabels.push(label);
566 }
567 }
568
569 context.beginPath();
570 context.moveTo(this.area.x, this.area.y + this.area.h);
571 context.lineTo(this.area.x + this.area.w, this.area.y + this.area.h);
572 context.closePath();
573 context.stroke();
574 }
575
576 context.restore();
577 };
578
579
580 DygraphCanvasRenderer.prototype._renderAnnotations = function() {
581 var annotationStyle = {
582 "position": "absolute",
583 "fontSize": this.options.axisLabelFontSize + "px",
584 "zIndex": 10,
585 "overflow": "hidden"
586 };
587
588 var bindEvt = function(eventName, classEventName, p, self) {
589 return function(e) {
590 var a = p.annotation;
591 if (a.hasOwnProperty(eventName)) {
592 a[eventName](a, p, self.dygraph_, e);
593 } else if (self.dygraph_.attr_(classEventName)) {
594 self.dygraph_.attr_(classEventName)(a, p, self.dygraph_,e );
595 }
596 };
597 }
598
599 // Get a list of point with annotations.
600 var points = this.layout.annotated_points;
601 for (var i = 0; i < points.length; i++) {
602 var p = points[i];
603 if (p.canvasx < this.area.x || p.canvasx > this.area.x + this.area.w) {
604 continue;
605 }
606
607 var a = p.annotation;
608 var tick_height = 6;
609 if (a.hasOwnProperty("tickHeight")) {
610 tick_height = a.tickHeight;
611 }
612
613 var div = document.createElement("div");
614 for (var name in annotationStyle) {
615 if (annotationStyle.hasOwnProperty(name)) {
616 div.style[name] = annotationStyle[name];
617 }
618 }
619 if (!a.hasOwnProperty('icon')) {
620 div.className = "dygraphDefaultAnnotation";
621 }
622 if (a.hasOwnProperty('cssClass')) {
623 div.className += " " + a.cssClass;
624 }
625
626 var width = a.hasOwnProperty('width') ? a.width : 16;
627 var height = a.hasOwnProperty('height') ? a.height : 16;
628 if (a.hasOwnProperty('icon')) {
629 var img = document.createElement("img");
630 img.src = a.icon;
631 img.width = width;
632 img.height = height;
633 div.appendChild(img);
634 } else if (p.annotation.hasOwnProperty('shortText')) {
635 div.appendChild(document.createTextNode(p.annotation.shortText));
636 }
637 div.style.left = (p.canvasx - width / 2) + "px";
638 if (a.attachAtBottom) {
639 div.style.top = (this.area.h - height - tick_height) + "px";
640 } else {
641 div.style.top = (p.canvasy - height - tick_height) + "px";
642 }
643 div.style.width = width + "px";
644 div.style.height = height + "px";
645 div.title = p.annotation.text;
646 div.style.color = this.colors[p.name];
647 div.style.borderColor = this.colors[p.name];
648 a.div = div;
649
650 Dygraph.addEvent(div, 'click',
651 bindEvt('clickHandler', 'annotationClickHandler', p, this));
652 Dygraph.addEvent(div, 'mouseover',
653 bindEvt('mouseOverHandler', 'annotationMouseOverHandler', p, this));
654 Dygraph.addEvent(div, 'mouseout',
655 bindEvt('mouseOutHandler', 'annotationMouseOutHandler', p, this));
656 Dygraph.addEvent(div, 'dblclick',
657 bindEvt('dblClickHandler', 'annotationDblClickHandler', p, this));
658
659 this.container.appendChild(div);
660 this.annotations.push(div);
661
662 var ctx = this.element.getContext("2d");
663 ctx.strokeStyle = this.colors[p.name];
664 ctx.beginPath();
665 if (!a.attachAtBottom) {
666 ctx.moveTo(p.canvasx, p.canvasy);
667 ctx.lineTo(p.canvasx, p.canvasy - 2 - tick_height);
668 } else {
669 ctx.moveTo(p.canvasx, this.area.h);
670 ctx.lineTo(p.canvasx, this.area.h - 2 - tick_height);
671 }
672 ctx.closePath();
673 ctx.stroke();
674 }
675 };
676
677
678 /**
679 * Overrides the CanvasRenderer method to draw error bars
680 */
681 DygraphCanvasRenderer.prototype._renderLineChart = function() {
682 // TODO(danvk): use this.attr_ for many of these.
683 var context = this.element.getContext("2d");
684 var colorCount = this.options.colorScheme.length;
685 var colorScheme = this.options.colorScheme;
686 var fillAlpha = this.options.fillAlpha;
687 var errorBars = this.layout.options.errorBars;
688 var fillGraph = this.attr_("fillGraph");
689 var stackedGraph = this.layout.options.stackedGraph;
690 var stepPlot = this.layout.options.stepPlot;
691
692 var setNames = [];
693 for (var name in this.layout.datasets) {
694 if (this.layout.datasets.hasOwnProperty(name)) {
695 setNames.push(name);
696 }
697 }
698 var setCount = setNames.length;
699
700 this.colors = {}
701 for (var i = 0; i < setCount; i++) {
702 this.colors[setNames[i]] = colorScheme[i % colorCount];
703 }
704
705 // Update Points
706 // TODO(danvk): here
707 for (var i = 0; i < this.layout.points.length; i++) {
708 var point = this.layout.points[i];
709 point.canvasx = this.area.w * point.x + this.area.x;
710 point.canvasy = this.area.h * point.y + this.area.y;
711 }
712
713 // create paths
714 var isOK = function(x) { return x && !isNaN(x); };
715
716 var ctx = context;
717 if (errorBars) {
718 if (fillGraph) {
719 this.dygraph_.warn("Can't use fillGraph option with error bars");
720 }
721
722 for (var i = 0; i < setCount; i++) {
723 var setName = setNames[i];
724 var axis = this.layout.options.yAxes[
725 this.layout.options.seriesToAxisMap[setName]];
726 var color = this.colors[setName];
727
728 // setup graphics context
729 ctx.save();
730 var prevX = NaN;
731 var prevY = NaN;
732 var prevYs = [-1, -1];
733 var yscale = axis.yscale;
734 // should be same color as the lines but only 15% opaque.
735 var rgb = new RGBColor(color);
736 var err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
737 fillAlpha + ')';
738 ctx.fillStyle = err_color;
739 ctx.beginPath();
740 for (var j = 0; j < this.layout.points.length; j++) {
741 var point = this.layout.points[j];
742 if (point.name == setName) {
743 if (!isOK(point.y)) {
744 prevX = NaN;
745 continue;
746 }
747
748 // TODO(danvk): here
749 if (stepPlot) {
750 var newYs = [ prevY - point.errorPlus * yscale,
751 prevY + point.errorMinus * yscale ];
752 prevY = point.y;
753 } else {
754 var newYs = [ point.y - point.errorPlus * yscale,
755 point.y + point.errorMinus * yscale ];
756 }
757 newYs[0] = this.area.h * newYs[0] + this.area.y;
758 newYs[1] = this.area.h * newYs[1] + this.area.y;
759 if (!isNaN(prevX)) {
760 if (stepPlot) {
761 ctx.moveTo(prevX, newYs[0]);
762 } else {
763 ctx.moveTo(prevX, prevYs[0]);
764 }
765 ctx.lineTo(point.canvasx, newYs[0]);
766 ctx.lineTo(point.canvasx, newYs[1]);
767 if (stepPlot) {
768 ctx.lineTo(prevX, newYs[1]);
769 } else {
770 ctx.lineTo(prevX, prevYs[1]);
771 }
772 ctx.closePath();
773 }
774 prevYs = newYs;
775 prevX = point.canvasx;
776 }
777 }
778 ctx.fill();
779 }
780 } else if (fillGraph) {
781 var baseline = [] // for stacked graphs: baseline for filling
782
783 // process sets in reverse order (needed for stacked graphs)
784 for (var i = setCount - 1; i >= 0; i--) {
785 var setName = setNames[i];
786 var color = this.colors[setName];
787 var axis = this.layout.options.yAxes[
788 this.layout.options.seriesToAxisMap[setName]];
789 var axisY = 1.0 + axis.minyval * axis.yscale;
790 if (axisY < 0.0) axisY = 0.0;
791 else if (axisY > 1.0) axisY = 1.0;
792 axisY = this.area.h * axisY + this.area.y;
793
794 // setup graphics context
795 ctx.save();
796 var prevX = NaN;
797 var prevYs = [-1, -1];
798 var yscale = axis.yscale;
799 // should be same color as the lines but only 15% opaque.
800 var rgb = new RGBColor(color);
801 var err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
802 fillAlpha + ')';
803 ctx.fillStyle = err_color;
804 ctx.beginPath();
805 for (var j = 0; j < this.layout.points.length; j++) {
806 var point = this.layout.points[j];
807 if (point.name == setName) {
808 if (!isOK(point.y)) {
809 prevX = NaN;
810 continue;
811 }
812 var newYs;
813 if (stackedGraph) {
814 lastY = baseline[point.canvasx];
815 if (lastY === undefined) lastY = axisY;
816 baseline[point.canvasx] = point.canvasy;
817 newYs = [ point.canvasy, lastY ];
818 } else {
819 newYs = [ point.canvasy, axisY ];
820 }
821 if (!isNaN(prevX)) {
822 ctx.moveTo(prevX, prevYs[0]);
823 if (stepPlot) {
824 ctx.lineTo(point.canvasx, prevYs[0]);
825 } else {
826 ctx.lineTo(point.canvasx, newYs[0]);
827 }
828 ctx.lineTo(point.canvasx, newYs[1]);
829 ctx.lineTo(prevX, prevYs[1]);
830 ctx.closePath();
831 }
832 prevYs = newYs;
833 prevX = point.canvasx;
834 }
835 }
836 ctx.fill();
837 }
838 }
839
840 for (var i = 0; i < setCount; i++) {
841 var setName = setNames[i];
842 var color = this.colors[setName];
843 var strokeWidth = this.dygraph_.attr_("strokeWidth", setName);
844
845 // setup graphics context
846 context.save();
847 var point = this.layout.points[0];
848 var pointSize = this.dygraph_.attr_("pointSize", setName);
849 var prevX = null, prevY = null;
850 var drawPoints = this.dygraph_.attr_("drawPoints", setName);
851 var points = this.layout.points;
852 for (var j = 0; j < points.length; j++) {
853 var point = points[j];
854 if (point.name == setName) {
855 if (!isOK(point.canvasy)) {
856 if (stepPlot && prevX != null) {
857 // Draw a horizontal line to the start of the missing data
858 ctx.beginPath();
859 ctx.strokeStyle = color;
860 ctx.lineWidth = this.options.strokeWidth;
861 ctx.moveTo(prevX, prevY);
862 ctx.lineTo(point.canvasx, prevY);
863 ctx.stroke();
864 }
865 // this will make us move to the next point, not draw a line to it.
866 prevX = prevY = null;
867 } else {
868 // A point is "isolated" if it is non-null but both the previous
869 // and next points are null.
870 var isIsolated = (!prevX && (j == points.length - 1 ||
871 !isOK(points[j+1].canvasy)));
872
873 if (!prevX) {
874 prevX = point.canvasx;
875 prevY = point.canvasy;
876 } else {
877 // TODO(danvk): figure out why this conditional is necessary.
878 if (strokeWidth) {
879 ctx.beginPath();
880 ctx.strokeStyle = color;
881 ctx.lineWidth = strokeWidth;
882 ctx.moveTo(prevX, prevY);
883 if (stepPlot) {
884 ctx.lineTo(point.canvasx, prevY);
885 }
886 prevX = point.canvasx;
887 prevY = point.canvasy;
888 ctx.lineTo(prevX, prevY);
889 ctx.stroke();
890 }
891 }
892
893 if (drawPoints || isIsolated) {
894 ctx.beginPath();
895 ctx.fillStyle = color;
896 ctx.arc(point.canvasx, point.canvasy, pointSize,
897 0, 2 * Math.PI, false);
898 ctx.fill();
899 }
900 }
901 }
902 }
903 }
904
905 context.restore();
906 };