Enable "strict" mode -- and fix one missing "var" declaration.
[dygraphs.git] / dygraph-canvas.js
1 /**
2 * @license
3 * Copyright 2006 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
5 */
6
7 /**
8 * @fileoverview Based on PlotKit.CanvasRenderer, but modified to meet the
9 * needs of dygraphs.
10 *
11 * In particular, support for:
12 * - grid overlays
13 * - error bars
14 * - dygraphs attribute system
15 */
16
17 /**
18 * The DygraphCanvasRenderer class does the actual rendering of the chart onto
19 * a canvas. It's based on PlotKit.CanvasRenderer.
20 * @param {Object} element The canvas to attach to
21 * @param {Object} elementContext The 2d context of the canvas (injected so it
22 * can be mocked for testing.)
23 * @param {Layout} layout The DygraphLayout object for this graph.
24 * @constructor
25 */
26
27 "use strict";
28
29 var DygraphCanvasRenderer = function(dygraph, element, elementContext, layout) {
30 this.dygraph_ = dygraph;
31
32 this.layout = layout;
33 this.element = element;
34 this.elementContext = elementContext;
35 this.container = this.element.parentNode;
36
37 this.height = this.element.height;
38 this.width = this.element.width;
39
40 // --- check whether everything is ok before we return
41 if (!this.isIE && !(DygraphCanvasRenderer.isSupported(this.element)))
42 throw "Canvas is not supported.";
43
44 // internal state
45 this.xlabels = new Array();
46 this.ylabels = new Array();
47 this.annotations = new Array();
48 this.chartLabels = {};
49
50 this.area = layout.getPlotArea();
51 this.container.style.position = "relative";
52 this.container.style.width = this.width + "px";
53
54 // Set up a clipping area for the canvas (and the interaction canvas).
55 // This ensures that we don't overdraw.
56 if (this.dygraph_.isUsingExcanvas_) {
57 this._createIEClipArea();
58 } else {
59 var ctx = this.dygraph_.canvas_ctx_;
60 ctx.beginPath();
61 ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h);
62 ctx.clip();
63
64 ctx = this.dygraph_.hidden_ctx_;
65 ctx.beginPath();
66 ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h);
67 ctx.clip();
68 }
69 };
70
71 DygraphCanvasRenderer.prototype.attr_ = function(x) {
72 return this.dygraph_.attr_(x);
73 };
74
75 DygraphCanvasRenderer.prototype.clear = function() {
76 if (this.isIE) {
77 // VML takes a while to start up, so we just poll every this.IEDelay
78 try {
79 if (this.clearDelay) {
80 this.clearDelay.cancel();
81 this.clearDelay = null;
82 }
83 var context = this.elementContext;
84 }
85 catch (e) {
86 // TODO(danvk): this is broken, since MochiKit.Async is gone.
87 this.clearDelay = MochiKit.Async.wait(this.IEDelay);
88 this.clearDelay.addCallback(bind(this.clear, this));
89 return;
90 }
91 }
92
93 var context = this.elementContext;
94 context.clearRect(0, 0, this.width, this.height);
95
96 for (var i = 0; i < this.xlabels.length; i++) {
97 var el = this.xlabels[i];
98 if (el.parentNode) el.parentNode.removeChild(el);
99 }
100 for (var i = 0; i < this.ylabels.length; i++) {
101 var el = this.ylabels[i];
102 if (el.parentNode) el.parentNode.removeChild(el);
103 }
104 for (var i = 0; i < this.annotations.length; i++) {
105 var el = this.annotations[i];
106 if (el.parentNode) el.parentNode.removeChild(el);
107 }
108 for (var k in this.chartLabels) {
109 if (!this.chartLabels.hasOwnProperty(k)) continue;
110 var el = this.chartLabels[k];
111 if (el.parentNode) el.parentNode.removeChild(el);
112 }
113 this.xlabels = new Array();
114 this.ylabels = new Array();
115 this.annotations = new Array();
116 this.chartLabels = {};
117 };
118
119
120 DygraphCanvasRenderer.isSupported = function(canvasName) {
121 var canvas = null;
122 try {
123 if (typeof(canvasName) == 'undefined' || canvasName == null)
124 canvas = document.createElement("canvas");
125 else
126 canvas = canvasName;
127 var context = canvas.getContext("2d");
128 }
129 catch (e) {
130 var ie = navigator.appVersion.match(/MSIE (\d\.\d)/);
131 var opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
132 if ((!ie) || (ie[1] < 6) || (opera))
133 return false;
134 return true;
135 }
136 return true;
137 };
138
139 /**
140 * @param { [String] } colors Array of color strings. Should have one entry for
141 * each series to be rendered.
142 */
143 DygraphCanvasRenderer.prototype.setColors = function(colors) {
144 this.colorScheme_ = colors;
145 };
146
147 /**
148 * Draw an X/Y grid on top of the existing plot
149 */
150 DygraphCanvasRenderer.prototype.render = function() {
151 // Draw the new X/Y grid. Lines appear crisper when pixels are rounded to
152 // half-integers. This prevents them from drawing in two rows/cols.
153 var ctx = this.elementContext;
154 function halfUp(x){return Math.round(x)+0.5};
155 function halfDown(y){return Math.round(y)-0.5};
156
157 if (this.attr_('underlayCallback')) {
158 // NOTE: we pass the dygraph object to this callback twice to avoid breaking
159 // users who expect a deprecated form of this callback.
160 this.attr_('underlayCallback')(ctx, this.area, this.dygraph_, this.dygraph_);
161 }
162
163 if (this.attr_('drawYGrid')) {
164 var ticks = this.layout.yticks;
165 // TODO(konigsberg): I don't think these calls to save() have a corresponding restore().
166 ctx.save();
167 ctx.strokeStyle = this.attr_('gridLineColor');
168 ctx.lineWidth = this.attr_('gridLineWidth');
169 for (var i = 0; i < ticks.length; i++) {
170 // TODO(danvk): allow secondary axes to draw a grid, too.
171 if (ticks[i][0] != 0) continue;
172 var x = halfUp(this.area.x);
173 var y = halfDown(this.area.y + ticks[i][1] * this.area.h);
174 ctx.beginPath();
175 ctx.moveTo(x, y);
176 ctx.lineTo(x + this.area.w, y);
177 ctx.closePath();
178 ctx.stroke();
179 }
180 }
181
182 if (this.attr_('drawXGrid')) {
183 var ticks = this.layout.xticks;
184 ctx.save();
185 ctx.strokeStyle = this.attr_('gridLineColor');
186 ctx.lineWidth = this.attr_('gridLineWidth');
187 for (var i=0; i<ticks.length; i++) {
188 var x = halfUp(this.area.x + ticks[i][0] * this.area.w);
189 var y = halfDown(this.area.y + this.area.h);
190 ctx.beginPath();
191 ctx.moveTo(x, y);
192 ctx.lineTo(x, this.area.y);
193 ctx.closePath();
194 ctx.stroke();
195 }
196 }
197
198 // Do the ordinary rendering, as before
199 this._renderLineChart();
200 this._renderAxis();
201 this._renderChartLabels();
202 this._renderAnnotations();
203 };
204
205 DygraphCanvasRenderer.prototype._createIEClipArea = function() {
206 var className = 'dygraph-clip-div';
207 var graphDiv = this.dygraph_.graphDiv;
208
209 // Remove old clip divs.
210 for (var i = graphDiv.childNodes.length-1; i >= 0; i--) {
211 if (graphDiv.childNodes[i].className == className) {
212 graphDiv.removeChild(graphDiv.childNodes[i]);
213 }
214 }
215
216 // Determine background color to give clip divs.
217 var backgroundColor = document.bgColor;
218 var element = this.dygraph_.graphDiv;
219 while (element != document) {
220 var bgcolor = element.currentStyle.backgroundColor;
221 if (bgcolor && bgcolor != 'transparent') {
222 backgroundColor = bgcolor;
223 break;
224 }
225 element = element.parentNode;
226 }
227
228 function createClipDiv(area) {
229 if (area.w == 0 || area.h == 0) {
230 return;
231 }
232 var elem = document.createElement('div');
233 elem.className = className;
234 elem.style.backgroundColor = backgroundColor;
235 elem.style.position = 'absolute';
236 elem.style.left = area.x + 'px';
237 elem.style.top = area.y + 'px';
238 elem.style.width = area.w + 'px';
239 elem.style.height = area.h + 'px';
240 graphDiv.appendChild(elem);
241 }
242
243 var plotArea = this.area;
244 // Left side
245 createClipDiv({x:0, y:0, w:plotArea.x, h:this.height});
246 // Top
247 createClipDiv({x:plotArea.x, y:0, w:this.width-plotArea.x, h:plotArea.y});
248 // Right side
249 createClipDiv({x:plotArea.x+plotArea.w, y:0, w:this.width-plotArea.x-plotArea.w, h:this.height});
250 // Bottom
251 createClipDiv({x:plotArea.x, y:plotArea.y+plotArea.h, w:this.width-plotArea.x, h:this.height-plotArea.h-plotArea.y});
252 }
253
254 DygraphCanvasRenderer.prototype._renderAxis = function() {
255 if (!this.attr_('drawXAxis') && !this.attr_('drawYAxis')) return;
256
257 // Round pixels to half-integer boundaries for crisper drawing.
258 function halfUp(x){return Math.round(x)+0.5};
259 function halfDown(y){return Math.round(y)-0.5};
260
261 var context = this.elementContext;
262
263 var labelStyle = {
264 position: "absolute",
265 fontSize: this.attr_('axisLabelFontSize') + "px",
266 zIndex: 10,
267 color: this.attr_('axisLabelColor'),
268 width: this.attr_('axisLabelWidth') + "px",
269 // height: this.attr_('axisLabelFontSize') + 2 + "px",
270 lineHeight: "normal", // Something other than "normal" line-height screws up label positioning.
271 overflow: "hidden"
272 };
273 var makeDiv = function(txt, axis, prec_axis) {
274 var div = document.createElement("div");
275 for (var name in labelStyle) {
276 if (labelStyle.hasOwnProperty(name)) {
277 div.style[name] = labelStyle[name];
278 }
279 }
280 var inner_div = document.createElement("div");
281 inner_div.className = 'dygraph-axis-label' +
282 ' dygraph-axis-label-' + axis +
283 (prec_axis ? ' dygraph-axis-label-' + prec_axis : '');
284 inner_div.appendChild(document.createTextNode(txt));
285 div.appendChild(inner_div);
286 return div;
287 };
288
289 // axis lines
290 context.save();
291 context.strokeStyle = this.attr_('axisLineColor');
292 context.lineWidth = this.attr_('axisLineWidth');
293
294 if (this.attr_('drawYAxis')) {
295 if (this.layout.yticks && this.layout.yticks.length > 0) {
296 var num_axes = this.dygraph_.numAxes();
297 for (var i = 0; i < this.layout.yticks.length; i++) {
298 var tick = this.layout.yticks[i];
299 if (typeof(tick) == "function") return;
300 var x = this.area.x;
301 var sgn = 1;
302 var prec_axis = 'y1';
303 if (tick[0] == 1) { // right-side y-axis
304 x = this.area.x + this.area.w;
305 sgn = -1;
306 prec_axis = 'y2';
307 }
308 var y = this.area.y + tick[1] * this.area.h;
309
310 /* Tick marks are currently clipped, so don't bother drawing them.
311 context.beginPath();
312 context.moveTo(halfUp(x), halfDown(y));
313 context.lineTo(halfUp(x - sgn * this.attr_('axisTickSize')), halfDown(y));
314 context.closePath();
315 context.stroke();
316 */
317
318 var label = makeDiv(tick[2], 'y', num_axes == 2 ? prec_axis : null);
319 var top = (y - this.attr_('axisLabelFontSize') / 2);
320 if (top < 0) top = 0;
321
322 if (top + this.attr_('axisLabelFontSize') + 3 > this.height) {
323 label.style.bottom = "0px";
324 } else {
325 label.style.top = top + "px";
326 }
327 if (tick[0] == 0) {
328 label.style.left = (this.area.x - this.attr_('yAxisLabelWidth') - this.attr_('axisTickSize')) + "px";
329 label.style.textAlign = "right";
330 } else if (tick[0] == 1) {
331 label.style.left = (this.area.x + this.area.w +
332 this.attr_('axisTickSize')) + "px";
333 label.style.textAlign = "left";
334 }
335 label.style.width = this.attr_('yAxisLabelWidth') + "px";
336 this.container.appendChild(label);
337 this.ylabels.push(label);
338 }
339
340 // The lowest tick on the y-axis often overlaps with the leftmost
341 // tick on the x-axis. Shift the bottom tick up a little bit to
342 // compensate if necessary.
343 var bottomTick = this.ylabels[0];
344 var fontSize = this.attr_('axisLabelFontSize');
345 var bottom = parseInt(bottomTick.style.top) + fontSize;
346 if (bottom > this.height - fontSize) {
347 bottomTick.style.top = (parseInt(bottomTick.style.top) -
348 fontSize / 2) + "px";
349 }
350 }
351
352 // draw a vertical line on the left to separate the chart from the labels.
353 context.beginPath();
354 context.moveTo(halfUp(this.area.x), halfDown(this.area.y));
355 context.lineTo(halfUp(this.area.x), halfDown(this.area.y + this.area.h));
356 context.closePath();
357 context.stroke();
358
359 // if there's a secondary y-axis, draw a vertical line for that, too.
360 if (this.dygraph_.numAxes() == 2) {
361 context.beginPath();
362 context.moveTo(halfDown(this.area.x + this.area.w), halfDown(this.area.y));
363 context.lineTo(halfDown(this.area.x + this.area.w), halfDown(this.area.y + this.area.h));
364 context.closePath();
365 context.stroke();
366 }
367 }
368
369 if (this.attr_('drawXAxis')) {
370 if (this.layout.xticks) {
371 for (var i = 0; i < this.layout.xticks.length; i++) {
372 var tick = this.layout.xticks[i];
373 if (typeof(dataset) == "function") return;
374
375 var x = this.area.x + tick[0] * this.area.w;
376 var y = this.area.y + this.area.h;
377
378 /* Tick marks are currently clipped, so don't bother drawing them.
379 context.beginPath();
380 context.moveTo(halfUp(x), halfDown(y));
381 context.lineTo(halfUp(x), halfDown(y + this.attr_('axisTickSize')));
382 context.closePath();
383 context.stroke();
384 */
385
386 var label = makeDiv(tick[1], 'x');
387 label.style.textAlign = "center";
388 label.style.top = (y + this.attr_('axisTickSize')) + 'px';
389
390 var left = (x - this.attr_('axisLabelWidth')/2);
391 if (left + this.attr_('axisLabelWidth') > this.width) {
392 left = this.width - this.attr_('xAxisLabelWidth');
393 label.style.textAlign = "right";
394 }
395 if (left < 0) {
396 left = 0;
397 label.style.textAlign = "left";
398 }
399
400 label.style.left = left + "px";
401 label.style.width = this.attr_('xAxisLabelWidth') + "px";
402 this.container.appendChild(label);
403 this.xlabels.push(label);
404 }
405 }
406
407 context.beginPath();
408 context.moveTo(halfUp(this.area.x), halfDown(this.area.y + this.area.h));
409 context.lineTo(halfUp(this.area.x + this.area.w), halfDown(this.area.y + this.area.h));
410 context.closePath();
411 context.stroke();
412 }
413
414 context.restore();
415 };
416
417
418 DygraphCanvasRenderer.prototype._renderChartLabels = function() {
419 // Generate divs for the chart title, xlabel and ylabel.
420 // Space for these divs has already been taken away from the charting area in
421 // the DygraphCanvasRenderer constructor.
422 if (this.attr_('title')) {
423 var div = document.createElement("div");
424 div.style.position = 'absolute';
425 div.style.top = '0px';
426 div.style.left = this.area.x + 'px';
427 div.style.width = this.area.w + 'px';
428 div.style.height = this.attr_('titleHeight') + 'px';
429 div.style.textAlign = 'center';
430 div.style.fontSize = (this.attr_('titleHeight') - 8) + 'px';
431 div.style.fontWeight = 'bold';
432 var class_div = document.createElement("div");
433 class_div.className = 'dygraph-label dygraph-title';
434 class_div.innerHTML = this.attr_('title');
435 div.appendChild(class_div);
436 this.container.appendChild(div);
437 this.chartLabels.title = div;
438 }
439
440 if (this.attr_('xlabel')) {
441 var div = document.createElement("div");
442 div.style.position = 'absolute';
443 div.style.bottom = 0; // TODO(danvk): this is lazy. Calculate style.top.
444 div.style.left = this.area.x + 'px';
445 div.style.width = this.area.w + 'px';
446 div.style.height = this.attr_('xLabelHeight') + 'px';
447 div.style.textAlign = 'center';
448 div.style.fontSize = (this.attr_('xLabelHeight') - 2) + 'px';
449
450 var class_div = document.createElement("div");
451 class_div.className = 'dygraph-label dygraph-xlabel';
452 class_div.innerHTML = this.attr_('xlabel');
453 div.appendChild(class_div);
454 this.container.appendChild(div);
455 this.chartLabels.xlabel = div;
456 }
457
458 if (this.attr_('ylabel')) {
459 var box = {
460 left: 0,
461 top: this.area.y,
462 width: this.attr_('yLabelWidth'),
463 height: this.area.h
464 };
465 // TODO(danvk): is this outer div actually necessary?
466 var div = document.createElement("div");
467 div.style.position = 'absolute';
468 div.style.left = box.left;
469 div.style.top = box.top + 'px';
470 div.style.width = box.width + 'px';
471 div.style.height = box.height + 'px';
472 div.style.fontSize = (this.attr_('yLabelWidth') - 2) + 'px';
473
474 var inner_div = document.createElement("div");
475 inner_div.style.position = 'absolute';
476 inner_div.style.width = box.height + 'px';
477 inner_div.style.height = box.width + 'px';
478 inner_div.style.top = (box.height / 2 - box.width / 2) + 'px';
479 inner_div.style.left = (box.width / 2 - box.height / 2) + 'px';
480 inner_div.style.textAlign = 'center';
481
482 // CSS rotation is an HTML5 feature which is not standardized. Hence every
483 // browser has its own name for the CSS style.
484 inner_div.style.transform = 'rotate(-90deg)'; // HTML5
485 inner_div.style.WebkitTransform = 'rotate(-90deg)'; // Safari/Chrome
486 inner_div.style.MozTransform = 'rotate(-90deg)'; // Firefox
487 inner_div.style.OTransform = 'rotate(-90deg)'; // Opera
488 inner_div.style.msTransform = 'rotate(-90deg)'; // IE9
489
490 if (typeof(document.documentMode) !== 'undefined' &&
491 document.documentMode < 9) {
492 // We're dealing w/ an old version of IE, so we have to rotate the text
493 // using a BasicImage transform. This uses a different origin of rotation
494 // than HTML5 rotation (top left of div vs. its center).
495 inner_div.style.filter =
496 'progid:DXImageTransform.Microsoft.BasicImage(rotation=3)';
497 inner_div.style.left = '0px';
498 inner_div.style.top = '0px';
499 }
500
501 var class_div = document.createElement("div");
502 class_div.className = 'dygraph-label dygraph-ylabel';
503 class_div.innerHTML = this.attr_('ylabel');
504
505 inner_div.appendChild(class_div);
506 div.appendChild(inner_div);
507 this.container.appendChild(div);
508 this.chartLabels.ylabel = div;
509 }
510 };
511
512
513 DygraphCanvasRenderer.prototype._renderAnnotations = function() {
514 var annotationStyle = {
515 "position": "absolute",
516 "fontSize": this.attr_('axisLabelFontSize') + "px",
517 "zIndex": 10,
518 "overflow": "hidden"
519 };
520
521 var bindEvt = function(eventName, classEventName, p, self) {
522 return function(e) {
523 var a = p.annotation;
524 if (a.hasOwnProperty(eventName)) {
525 a[eventName](a, p, self.dygraph_, e);
526 } else if (self.dygraph_.attr_(classEventName)) {
527 self.dygraph_.attr_(classEventName)(a, p, self.dygraph_,e );
528 }
529 };
530 }
531
532 // Get a list of point with annotations.
533 var points = this.layout.annotated_points;
534 for (var i = 0; i < points.length; i++) {
535 var p = points[i];
536 if (p.canvasx < this.area.x || p.canvasx > this.area.x + this.area.w) {
537 continue;
538 }
539
540 var a = p.annotation;
541 var tick_height = 6;
542 if (a.hasOwnProperty("tickHeight")) {
543 tick_height = a.tickHeight;
544 }
545
546 var div = document.createElement("div");
547 for (var name in annotationStyle) {
548 if (annotationStyle.hasOwnProperty(name)) {
549 div.style[name] = annotationStyle[name];
550 }
551 }
552 if (!a.hasOwnProperty('icon')) {
553 div.className = "dygraphDefaultAnnotation";
554 }
555 if (a.hasOwnProperty('cssClass')) {
556 div.className += " " + a.cssClass;
557 }
558
559 var width = a.hasOwnProperty('width') ? a.width : 16;
560 var height = a.hasOwnProperty('height') ? a.height : 16;
561 if (a.hasOwnProperty('icon')) {
562 var img = document.createElement("img");
563 img.src = a.icon;
564 img.width = width;
565 img.height = height;
566 div.appendChild(img);
567 } else if (p.annotation.hasOwnProperty('shortText')) {
568 div.appendChild(document.createTextNode(p.annotation.shortText));
569 }
570 div.style.left = (p.canvasx - width / 2) + "px";
571 if (a.attachAtBottom) {
572 div.style.top = (this.area.h - height - tick_height) + "px";
573 } else {
574 div.style.top = (p.canvasy - height - tick_height) + "px";
575 }
576 div.style.width = width + "px";
577 div.style.height = height + "px";
578 div.title = p.annotation.text;
579 div.style.color = this.colors[p.name];
580 div.style.borderColor = this.colors[p.name];
581 a.div = div;
582
583 Dygraph.addEvent(div, 'click',
584 bindEvt('clickHandler', 'annotationClickHandler', p, this));
585 Dygraph.addEvent(div, 'mouseover',
586 bindEvt('mouseOverHandler', 'annotationMouseOverHandler', p, this));
587 Dygraph.addEvent(div, 'mouseout',
588 bindEvt('mouseOutHandler', 'annotationMouseOutHandler', p, this));
589 Dygraph.addEvent(div, 'dblclick',
590 bindEvt('dblClickHandler', 'annotationDblClickHandler', p, this));
591
592 this.container.appendChild(div);
593 this.annotations.push(div);
594
595 var ctx = this.elementContext;
596 ctx.strokeStyle = this.colors[p.name];
597 ctx.beginPath();
598 if (!a.attachAtBottom) {
599 ctx.moveTo(p.canvasx, p.canvasy);
600 ctx.lineTo(p.canvasx, p.canvasy - 2 - tick_height);
601 } else {
602 ctx.moveTo(p.canvasx, this.area.h);
603 ctx.lineTo(p.canvasx, this.area.h - 2 - tick_height);
604 }
605 ctx.closePath();
606 ctx.stroke();
607 }
608 };
609
610
611 /**
612 * Overrides the CanvasRenderer method to draw error bars
613 */
614 DygraphCanvasRenderer.prototype._renderLineChart = function() {
615 var isNullOrNaN = function(x) {
616 return (x === null || isNaN(x));
617 };
618
619 // TODO(danvk): use this.attr_ for many of these.
620 var context = this.elementContext;
621 var fillAlpha = this.attr_('fillAlpha');
622 var errorBars = this.attr_("errorBars") || this.attr_("customBars");
623 var fillGraph = this.attr_("fillGraph");
624 var stackedGraph = this.attr_("stackedGraph");
625 var stepPlot = this.attr_("stepPlot");
626 var points = this.layout.points;
627 var pointsLength = points.length;
628
629 var setNames = [];
630 for (var name in this.layout.datasets) {
631 if (this.layout.datasets.hasOwnProperty(name)) {
632 setNames.push(name);
633 }
634 }
635 var setCount = setNames.length;
636
637 // TODO(danvk): Move this mapping into Dygraph and get it out of here.
638 this.colors = {}
639 for (var i = 0; i < setCount; i++) {
640 this.colors[setNames[i]] = this.colorScheme_[i % this.colorScheme_.length];
641 }
642
643 // Update Points
644 // TODO(danvk): here
645 for (var i = pointsLength; i--;) {
646 var point = points[i];
647 point.canvasx = this.area.w * point.x + this.area.x;
648 point.canvasy = this.area.h * point.y + this.area.y;
649 }
650
651 // create paths
652 var ctx = context;
653 if (errorBars) {
654 if (fillGraph) {
655 this.dygraph_.warn("Can't use fillGraph option with error bars");
656 }
657
658 for (var i = 0; i < setCount; i++) {
659 var setName = setNames[i];
660 var axis = this.dygraph_.axisPropertiesForSeries(setName);
661 var color = this.colors[setName];
662
663 // setup graphics context
664 ctx.save();
665 var prevX = NaN;
666 var prevY = NaN;
667 var prevYs = [-1, -1];
668 var yscale = axis.yscale;
669 // should be same color as the lines but only 15% opaque.
670 var rgb = new RGBColor(color);
671 var err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
672 fillAlpha + ')';
673 ctx.fillStyle = err_color;
674 ctx.beginPath();
675 for (var j = 0; j < pointsLength; j++) {
676 var point = points[j];
677 if (point.name == setName) {
678 if (!Dygraph.isOK(point.y)) {
679 prevX = NaN;
680 continue;
681 }
682
683 // TODO(danvk): here
684 if (stepPlot) {
685 var newYs = [ point.y_bottom, point.y_top ];
686 prevY = point.y;
687 } else {
688 var newYs = [ point.y_bottom, point.y_top ];
689 }
690 newYs[0] = this.area.h * newYs[0] + this.area.y;
691 newYs[1] = this.area.h * newYs[1] + this.area.y;
692 if (!isNaN(prevX)) {
693 if (stepPlot) {
694 ctx.moveTo(prevX, newYs[0]);
695 } else {
696 ctx.moveTo(prevX, prevYs[0]);
697 }
698 ctx.lineTo(point.canvasx, newYs[0]);
699 ctx.lineTo(point.canvasx, newYs[1]);
700 if (stepPlot) {
701 ctx.lineTo(prevX, newYs[1]);
702 } else {
703 ctx.lineTo(prevX, prevYs[1]);
704 }
705 ctx.closePath();
706 }
707 prevYs = newYs;
708 prevX = point.canvasx;
709 }
710 }
711 ctx.fill();
712 }
713 } else if (fillGraph) {
714 var baseline = [] // for stacked graphs: baseline for filling
715
716 // process sets in reverse order (needed for stacked graphs)
717 for (var i = setCount - 1; i >= 0; i--) {
718 var setName = setNames[i];
719 var color = this.colors[setName];
720 var axis = this.dygraph_.axisPropertiesForSeries(setName);
721 var axisY = 1.0 + axis.minyval * axis.yscale;
722 if (axisY < 0.0) axisY = 0.0;
723 else if (axisY > 1.0) axisY = 1.0;
724 axisY = this.area.h * axisY + this.area.y;
725
726 // setup graphics context
727 ctx.save();
728 var prevX = NaN;
729 var prevYs = [-1, -1];
730 var yscale = axis.yscale;
731 // should be same color as the lines but only 15% opaque.
732 var rgb = new RGBColor(color);
733 var err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
734 fillAlpha + ')';
735 ctx.fillStyle = err_color;
736 ctx.beginPath();
737 for (var j = 0; j < pointsLength; j++) {
738 var point = points[j];
739 if (point.name == setName) {
740 if (!Dygraph.isOK(point.y)) {
741 prevX = NaN;
742 continue;
743 }
744 var newYs;
745 if (stackedGraph) {
746 lastY = baseline[point.canvasx];
747 if (lastY === undefined) lastY = axisY;
748 baseline[point.canvasx] = point.canvasy;
749 newYs = [ point.canvasy, lastY ];
750 } else {
751 newYs = [ point.canvasy, axisY ];
752 }
753 if (!isNaN(prevX)) {
754 ctx.moveTo(prevX, prevYs[0]);
755 if (stepPlot) {
756 ctx.lineTo(point.canvasx, prevYs[0]);
757 } else {
758 ctx.lineTo(point.canvasx, newYs[0]);
759 }
760 ctx.lineTo(point.canvasx, newYs[1]);
761 ctx.lineTo(prevX, prevYs[1]);
762 ctx.closePath();
763 }
764 prevYs = newYs;
765 prevX = point.canvasx;
766 }
767 }
768 ctx.fill();
769 }
770 }
771
772 // Drawing the lines.
773 var firstIndexInSet = 0;
774 var afterLastIndexInSet = 0;
775 var setLength = 0;
776 for (var i = 0; i < setCount; i += 1) {
777 setLength = this.layout.setPointsLengths[i];
778 afterLastIndexInSet += setLength;
779 var setName = setNames[i];
780 var color = this.colors[setName];
781 var strokeWidth = this.dygraph_.attr_("strokeWidth", setName);
782
783 // setup graphics context
784 context.save();
785 var pointSize = this.dygraph_.attr_("pointSize", setName);
786 var prevX = null, prevY = null;
787 var drawPoints = this.dygraph_.attr_("drawPoints", setName);
788 for (var j = firstIndexInSet; j < afterLastIndexInSet; j++) {
789 var point = points[j];
790 if (isNullOrNaN(point.canvasy)) {
791 if (stepPlot && prevX != null) {
792 // Draw a horizontal line to the start of the missing data
793 ctx.beginPath();
794 ctx.strokeStyle = color;
795 ctx.lineWidth = this.attr_('strokeWidth');
796 ctx.moveTo(prevX, prevY);
797 ctx.lineTo(point.canvasx, prevY);
798 ctx.stroke();
799 }
800 // this will make us move to the next point, not draw a line to it.
801 prevX = prevY = null;
802 } else {
803 // A point is "isolated" if it is non-null but both the previous
804 // and next points are null.
805 var isIsolated = (!prevX && (j == points.length - 1 ||
806 isNullOrNaN(points[j+1].canvasy)));
807 if (prevX === null) {
808 prevX = point.canvasx;
809 prevY = point.canvasy;
810 } else {
811 // Skip over points that will be drawn in the same pixel.
812 if (Math.round(prevX) == Math.round(point.canvasx) &&
813 Math.round(prevY) == Math.round(point.canvasy)) {
814 continue;
815 }
816 // TODO(antrob): skip over points that lie on a line that is already
817 // going to be drawn. There is no need to have more than 2
818 // consecutive points that are collinear.
819 if (strokeWidth) {
820 ctx.beginPath();
821 ctx.strokeStyle = color;
822 ctx.lineWidth = strokeWidth;
823 ctx.moveTo(prevX, prevY);
824 if (stepPlot) {
825 ctx.lineTo(point.canvasx, prevY);
826 }
827 prevX = point.canvasx;
828 prevY = point.canvasy;
829 ctx.lineTo(prevX, prevY);
830 ctx.stroke();
831 }
832 }
833
834 if (drawPoints || isIsolated) {
835 ctx.beginPath();
836 ctx.fillStyle = color;
837 ctx.arc(point.canvasx, point.canvasy, pointSize,
838 0, 2 * Math.PI, false);
839 ctx.fill();
840 }
841 }
842 }
843 firstIndexInSet = afterLastIndexInSet;
844 }
845
846 context.restore();
847 };