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