Merge pull request #207 from kberg/master
[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 /*jshint globalstrict: true */
28 /*global Dygraph:false,RGBColorParser:false */
29 "use strict";
30
31
32 /**
33 * @constructor
34 *
35 * This gets called when there are "new points" to chart. This is generally the
36 * case when the underlying data being charted has changed. It is _not_ called
37 * in the common case that the user has zoomed or is panning the view.
38 *
39 * The chart canvas has already been created by the Dygraph object. The
40 * renderer simply gets a drawing context.
41 *
42 * @param {Dyraph} dygraph The chart to which this renderer belongs.
43 * @param {Canvas} element The <canvas> DOM element on which to draw.
44 * @param {CanvasRenderingContext2D} elementContext The drawing context.
45 * @param {DygraphLayout} layout The chart's DygraphLayout object.
46 *
47 * TODO(danvk): remove the elementContext property.
48 */
49 var DygraphCanvasRenderer = function(dygraph, element, elementContext, layout) {
50 this.dygraph_ = dygraph;
51
52 this.layout = layout;
53 this.element = element;
54 this.elementContext = elementContext;
55 this.container = this.element.parentNode;
56
57 this.height = this.element.height;
58 this.width = this.element.width;
59
60 // --- check whether everything is ok before we return
61 if (!this.isIE && !(DygraphCanvasRenderer.isSupported(this.element)))
62 throw "Canvas is not supported.";
63
64 // internal state
65 this.area = layout.getPlotArea();
66 this.container.style.position = "relative";
67 this.container.style.width = this.width + "px";
68
69 // Set up a clipping area for the canvas (and the interaction canvas).
70 // This ensures that we don't overdraw.
71 if (this.dygraph_.isUsingExcanvas_) {
72 this._createIEClipArea();
73 } else {
74 // on Android 3 and 4, setting a clipping area on a canvas prevents it from
75 // displaying anything.
76 if (!Dygraph.isAndroid()) {
77 var ctx = this.dygraph_.canvas_ctx_;
78 ctx.beginPath();
79 ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h);
80 ctx.clip();
81
82 ctx = this.dygraph_.hidden_ctx_;
83 ctx.beginPath();
84 ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h);
85 ctx.clip();
86 }
87 }
88 };
89
90 /**
91 * This just forwards to dygraph.attr_.
92 * TODO(danvk): remove this?
93 * @private
94 */
95 DygraphCanvasRenderer.prototype.attr_ = function(name, opt_seriesName) {
96 return this.dygraph_.attr_(name, opt_seriesName);
97 };
98
99 /**
100 * Clears out all chart content and DOM elements.
101 * This is called immediately before render() on every frame, including
102 * during zooms and pans.
103 * @private
104 */
105 DygraphCanvasRenderer.prototype.clear = function() {
106 var context;
107 if (this.isIE) {
108 // VML takes a while to start up, so we just poll every this.IEDelay
109 try {
110 if (this.clearDelay) {
111 this.clearDelay.cancel();
112 this.clearDelay = null;
113 }
114 context = this.elementContext;
115 }
116 catch (e) {
117 // TODO(danvk): this is broken, since MochiKit.Async is gone.
118 // this.clearDelay = MochiKit.Async.wait(this.IEDelay);
119 // this.clearDelay.addCallback(bind(this.clear, this));
120 return;
121 }
122 }
123
124 context = this.elementContext;
125 context.clearRect(0, 0, this.width, this.height);
126 };
127
128 /**
129 * Checks whether the browser supports the <canvas> tag.
130 * @private
131 */
132 DygraphCanvasRenderer.isSupported = function(canvasName) {
133 var canvas = null;
134 try {
135 if (typeof(canvasName) == 'undefined' || canvasName === null) {
136 canvas = document.createElement("canvas");
137 } else {
138 canvas = canvasName;
139 }
140 canvas.getContext("2d");
141 }
142 catch (e) {
143 var ie = navigator.appVersion.match(/MSIE (\d\.\d)/);
144 var opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
145 if ((!ie) || (ie[1] < 6) || (opera))
146 return false;
147 return true;
148 }
149 return true;
150 };
151
152 /**
153 * This method is responsible for drawing everything on the chart, including
154 * lines, error bars, fills and axes.
155 * It is called immediately after clear() on every frame, including during pans
156 * and zooms.
157 * @private
158 */
159 DygraphCanvasRenderer.prototype.render = function() {
160 // attaches point.canvas{x,y}
161 this._updatePoints();
162
163 // actually draws the chart.
164 this._renderLineChart();
165 };
166
167 DygraphCanvasRenderer.prototype._createIEClipArea = function() {
168 var className = 'dygraph-clip-div';
169 var graphDiv = this.dygraph_.graphDiv;
170
171 // Remove old clip divs.
172 for (var i = graphDiv.childNodes.length-1; i >= 0; i--) {
173 if (graphDiv.childNodes[i].className == className) {
174 graphDiv.removeChild(graphDiv.childNodes[i]);
175 }
176 }
177
178 // Determine background color to give clip divs.
179 var backgroundColor = document.bgColor;
180 var element = this.dygraph_.graphDiv;
181 while (element != document) {
182 var bgcolor = element.currentStyle.backgroundColor;
183 if (bgcolor && bgcolor != 'transparent') {
184 backgroundColor = bgcolor;
185 break;
186 }
187 element = element.parentNode;
188 }
189
190 function createClipDiv(area) {
191 if (area.w === 0 || area.h === 0) {
192 return;
193 }
194 var elem = document.createElement('div');
195 elem.className = className;
196 elem.style.backgroundColor = backgroundColor;
197 elem.style.position = 'absolute';
198 elem.style.left = area.x + 'px';
199 elem.style.top = area.y + 'px';
200 elem.style.width = area.w + 'px';
201 elem.style.height = area.h + 'px';
202 graphDiv.appendChild(elem);
203 }
204
205 var plotArea = this.area;
206 // Left side
207 createClipDiv({
208 x:0, y:0,
209 w:plotArea.x,
210 h:this.height
211 });
212
213 // Top
214 createClipDiv({
215 x: plotArea.x, y: 0,
216 w: this.width - plotArea.x,
217 h: plotArea.y
218 });
219
220 // Right side
221 createClipDiv({
222 x: plotArea.x + plotArea.w, y: 0,
223 w: this.width-plotArea.x - plotArea.w,
224 h: this.height
225 });
226
227 // Bottom
228 createClipDiv({
229 x: plotArea.x,
230 y: plotArea.y + plotArea.h,
231 w: this.width - plotArea.x,
232 h: this.height - plotArea.h - plotArea.y
233 });
234 };
235
236
237 /**
238 * Returns a predicate to be used with an iterator, which will
239 * iterate over points appropriately, depending on whether
240 * connectSeparatedPoints is true. When it's false, the predicate will
241 * skip over points with missing yVals.
242 */
243 DygraphCanvasRenderer._getIteratorPredicate = function(connectSeparatedPoints) {
244 return connectSeparatedPoints ?
245 DygraphCanvasRenderer._predicateThatSkipsEmptyPoints :
246 null;
247 };
248
249 DygraphCanvasRenderer._predicateThatSkipsEmptyPoints =
250 function(array, idx) {
251 return array[idx].yval !== null;
252 };
253
254 /**
255 * Draws a line with the styles passed in and calls all the drawPointCallbacks.
256 * @param {Object} e The dictionary passed to the plotter function.
257 * @private
258 */
259 DygraphCanvasRenderer._drawStyledLine = function(e,
260 color, strokeWidth, strokePattern, drawPoints,
261 drawPointCallback, pointSize) {
262 var g = e.dygraph;
263 // TODO(konigsberg): Compute attributes outside this method call.
264 var stepPlot = g.getOption("stepPlot"); // TODO(danvk): per-series
265 if (!Dygraph.isArrayLike(strokePattern)) {
266 strokePattern = null;
267 }
268
269 var drawGapPoints = g.getOption('drawGapEdgePoints', e.setName);
270
271 var points = e.points;
272 var iter = Dygraph.createIterator(points, 0, points.length,
273 DygraphCanvasRenderer._getIteratorPredicate(
274 g.getOption("connectSeparatedPoints"))); // TODO(danvk): per-series?
275
276 var stroking = strokePattern && (strokePattern.length >= 2);
277
278 var ctx = e.drawingContext;
279 ctx.save();
280 if (stroking) {
281 ctx.installPattern(strokePattern);
282 }
283
284 var pointsOnLine = DygraphCanvasRenderer._drawSeries(
285 e, iter, strokeWidth, pointSize, drawPoints, drawGapPoints, stepPlot, color);
286 DygraphCanvasRenderer._drawPointsOnLine(
287 e, pointsOnLine, drawPointCallback, color, pointSize);
288
289 if (stroking) {
290 ctx.uninstallPattern();
291 }
292
293 ctx.restore();
294 };
295
296 /**
297 * This does the actual drawing of lines on the canvas, for just one series.
298 * Returns a list of [canvasx, canvasy] pairs for points for which a
299 * drawPointCallback should be fired. These include isolated points, or all
300 * points if drawPoints=true.
301 * @param {Object} e The dictionary passed to the plotter function.
302 * @private
303 */
304 DygraphCanvasRenderer._drawSeries = function(e,
305 iter, strokeWidth, pointSize, drawPoints, drawGapPoints, stepPlot, color) {
306
307 var prevCanvasX = null;
308 var prevCanvasY = null;
309 var nextCanvasY = null;
310 var isIsolated; // true if this point is isolated (no line segments)
311 var point; // the point being processed in the while loop
312 var pointsOnLine = []; // Array of [canvasx, canvasy] pairs.
313 var first = true; // the first cycle through the while loop
314
315 var ctx = e.drawingContext;
316 ctx.beginPath();
317 ctx.strokeStyle = color;
318 ctx.lineWidth = strokeWidth;
319
320 // NOTE: we break the iterator's encapsulation here for about a 25% speedup.
321 var arr = iter.array_;
322 var limit = iter.end_;
323 var predicate = iter.predicate_;
324
325 for (var i = iter.start_; i < limit; i++) {
326 point = arr[i];
327 if (predicate) {
328 while (i < limit && !predicate(arr, i)) {
329 i++;
330 }
331 if (i == limit) break;
332 point = arr[i];
333 }
334
335 if (point.canvasy === null || point.canvasy != point.canvasy) {
336 if (stepPlot && prevCanvasX !== null) {
337 // Draw a horizontal line to the start of the missing data
338 ctx.moveTo(prevCanvasX, prevCanvasY);
339 ctx.lineTo(point.canvasx, prevCanvasY);
340 }
341 prevCanvasX = prevCanvasY = null;
342 } else {
343 isIsolated = false;
344 if (drawGapPoints || !prevCanvasX) {
345 iter.nextIdx_ = i;
346 iter.next();
347 nextCanvasY = iter.hasNext ? iter.peek.canvasy : null;
348
349 var isNextCanvasYNullOrNaN = nextCanvasY === null ||
350 nextCanvasY != nextCanvasY;
351 isIsolated = (!prevCanvasX && isNextCanvasYNullOrNaN);
352 if (drawGapPoints) {
353 // Also consider a point to be "isolated" if it's adjacent to a
354 // null point, excluding the graph edges.
355 if ((!first && !prevCanvasX) ||
356 (iter.hasNext && isNextCanvasYNullOrNaN)) {
357 isIsolated = true;
358 }
359 }
360 }
361
362 if (prevCanvasX !== null) {
363 if (strokeWidth) {
364 if (stepPlot) {
365 ctx.moveTo(prevCanvasX, prevCanvasY);
366 ctx.lineTo(point.canvasx, prevCanvasY);
367 }
368
369 ctx.lineTo(point.canvasx, point.canvasy);
370 }
371 } else {
372 ctx.moveTo(point.canvasx, point.canvasy);
373 }
374 if (drawPoints || isIsolated) {
375 pointsOnLine.push([point.canvasx, point.canvasy]);
376 }
377 prevCanvasX = point.canvasx;
378 prevCanvasY = point.canvasy;
379 }
380 first = false;
381 }
382 ctx.stroke();
383 return pointsOnLine;
384 };
385
386 /**
387 * This fires the drawPointCallback functions, which draw dots on the points by
388 * default. This gets used when the "drawPoints" option is set, or when there
389 * are isolated points.
390 * @param {Object} e The dictionary passed to the plotter function.
391 * @private
392 */
393 DygraphCanvasRenderer._drawPointsOnLine = function(
394 e, pointsOnLine, drawPointCallback, color, pointSize) {
395 var ctx = e.drawingContext;
396 for (var idx = 0; idx < pointsOnLine.length; idx++) {
397 var cb = pointsOnLine[idx];
398 ctx.save();
399 drawPointCallback(
400 e.dygraph, e.setName, ctx, cb[0], cb[1], color, pointSize);
401 ctx.restore();
402 }
403 };
404
405 /**
406 * Attaches canvas coordinates to the points array.
407 * @private
408 */
409 DygraphCanvasRenderer.prototype._updatePoints = function() {
410 // Update Points
411 // TODO(danvk): here
412 //
413 // TODO(bhs): this loop is a hot-spot for high-point-count charts. These
414 // transformations can be pushed into the canvas via linear transformation
415 // matrices.
416 // NOTE(danvk): this is trickier than it sounds at first. The transformation
417 // needs to be done before the .moveTo() and .lineTo() calls, but must be
418 // undone before the .stroke() call to ensure that the stroke width is
419 // unaffected. An alternative is to reduce the stroke width in the
420 // transformed coordinate space, but you can't specify different values for
421 // each dimension (as you can with .scale()). The speedup here is ~12%.
422 var sets = this.layout.points;
423 for (var i = sets.length; i--;) {
424 var points = sets[i];
425 for (var j = points.length; j--;) {
426 var point = points[j];
427 point.canvasx = this.area.w * point.x + this.area.x;
428 point.canvasy = this.area.h * point.y + this.area.y;
429 }
430 }
431 };
432
433 /**
434 * Add canvas Actually draw the lines chart, including error bars.
435 * If opt_seriesName is specified, only that series will be drawn.
436 * (This is used for expedited redrawing with highlightSeriesOpts)
437 * Lines are typically drawn in the non-interactive dygraph canvas. If opt_ctx
438 * is specified, they can be drawn elsewhere.
439 *
440 * This function can only be called if DygraphLayout's points array has been
441 * updated with canvas{x,y} attributes, i.e. by
442 * DygraphCanvasRenderer._updatePoints.
443 * @private
444 */
445 DygraphCanvasRenderer.prototype._renderLineChart = function(opt_seriesName, opt_ctx) {
446 var ctx = opt_ctx || this.elementContext;
447 var i;
448
449 var sets = this.layout.points;
450 var setNames = this.layout.setNames;
451 var setName;
452
453 this.colors = this.dygraph_.colorsMap_;
454
455 // Determine which series have specialized plotters.
456 var plotter_attr = this.attr_("plotter");
457 var plotters = plotter_attr;
458 if (!Dygraph.isArrayLike(plotters)) {
459 plotters = [plotters];
460 }
461
462 var setPlotters = {}; // series name -> plotter fn.
463 for (i = 0; i < setNames.length; i++) {
464 setName = setNames[i];
465 var setPlotter = this.attr_("plotter", setName);
466 if (setPlotter == plotter_attr) continue; // not specialized.
467
468 setPlotters[setName] = setPlotter;
469 }
470
471 for (i = 0; i < plotters.length; i++) {
472 var plotter = plotters[i];
473 var is_last = (i == plotters.length - 1);
474
475 for (var j = 0; j < sets.length; j++) {
476 setName = setNames[j];
477 if (opt_seriesName && setName != opt_seriesName) continue;
478
479 var points = sets[j];
480
481 // Only throw in the specialized plotters on the last iteration.
482 var p = plotter;
483 if (setName in setPlotters) {
484 if (is_last) {
485 p = setPlotters[setName];
486 } else {
487 // Don't use the standard plotters in this case.
488 continue;
489 }
490 }
491
492 var color = this.colors[setName];
493 var strokeWidth = this.dygraph_.getOption("strokeWidth", setName);
494
495 ctx.save();
496 ctx.strokeStyle = color;
497 ctx.lineWidth = strokeWidth;
498 p({
499 points: points,
500 setName: setName,
501 drawingContext: ctx,
502 color: color,
503 strokeWidth: strokeWidth,
504 dygraph: this.dygraph_,
505 axis: this.dygraph_.axisPropertiesForSeries(setName),
506 plotArea: this.area,
507 seriesIndex: j,
508 seriesCount: sets.length,
509 allSeriesPoints: sets
510 });
511 ctx.restore();
512 }
513 }
514 };
515
516 /**
517 * Standard plotters. These may be used by clients via Dygraph.Plotters.
518 * See comments there for more details.
519 */
520 DygraphCanvasRenderer._Plotters = {
521 linePlotter: function(e) {
522 DygraphCanvasRenderer._linePlotter(e);
523 },
524
525 fillPlotter: function(e) {
526 DygraphCanvasRenderer._fillPlotter(e);
527 },
528
529 errorPlotter: function(e) {
530 DygraphCanvasRenderer._errorPlotter(e);
531 }
532 };
533
534 /**
535 * Plotter which draws the central lines for a series.
536 * @private
537 */
538 DygraphCanvasRenderer._linePlotter = function(e) {
539 var g = e.dygraph;
540 var setName = e.setName;
541 var strokeWidth = e.strokeWidth;
542
543 // TODO(danvk): Check if there's any performance impact of just calling
544 // getOption() inside of _drawStyledLine. Passing in so many parameters makes
545 // this code a bit nasty.
546 var borderWidth = g.getOption("strokeBorderWidth", setName);
547 var drawPointCallback = g.getOption("drawPointCallback", setName) ||
548 Dygraph.Circles.DEFAULT;
549 var strokePattern = g.getOption("strokePattern", setName);
550 var drawPoints = g.getOption("drawPoints", setName);
551 var pointSize = g.getOption("pointSize", setName);
552
553 if (borderWidth && strokeWidth) {
554 DygraphCanvasRenderer._drawStyledLine(e,
555 g.getOption("strokeBorderColor", setName),
556 strokeWidth + 2 * borderWidth,
557 strokePattern,
558 drawPoints,
559 drawPointCallback,
560 pointSize
561 );
562 }
563
564 DygraphCanvasRenderer._drawStyledLine(e,
565 e.color,
566 strokeWidth,
567 strokePattern,
568 drawPoints,
569 drawPointCallback,
570 pointSize
571 );
572 };
573
574 /**
575 * Draws the shaded error bars/confidence intervals for each series.
576 * This happens before the center lines are drawn, since the center lines
577 * need to be drawn on top of the error bars for all series.
578 * @private
579 */
580 DygraphCanvasRenderer._errorPlotter = function(e) {
581 var g = e.dygraph;
582 var setName = e.setName;
583 var errorBars = g.getOption("errorBars") || g.getOption("customBars");
584 if (!errorBars) return;
585
586 var fillGraph = g.getOption("fillGraph", setName);
587 if (fillGraph) {
588 g.warn("Can't use fillGraph option with error bars");
589 }
590
591 var ctx = e.drawingContext;
592 var color = e.color;
593 var fillAlpha = g.getOption('fillAlpha', setName);
594 var stepPlot = g.getOption('stepPlot'); // TODO(danvk): per-series
595 var points = e.points;
596
597 var iter = Dygraph.createIterator(points, 0, points.length,
598 DygraphCanvasRenderer._getIteratorPredicate(
599 g.getOption("connectSeparatedPoints")));
600
601 var newYs;
602
603 // setup graphics context
604 var prevX = NaN;
605 var prevY = NaN;
606 var prevYs = [-1, -1];
607 // should be same color as the lines but only 15% opaque.
608 var rgb = new RGBColorParser(color);
609 var err_color =
610 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + fillAlpha + ')';
611 ctx.fillStyle = err_color;
612 ctx.beginPath();
613
614 var isNullUndefinedOrNaN = function(x) {
615 return (x === null ||
616 x === undefined ||
617 isNaN(x));
618 };
619
620 while (iter.hasNext) {
621 var point = iter.next();
622 if ((!stepPlot && isNullUndefinedOrNaN(point.y)) ||
623 (stepPlot && !isNaN(prevY) && isNullUndefinedOrNaN(prevY))) {
624 prevX = NaN;
625 continue;
626 }
627
628 if (stepPlot) {
629 newYs = [ point.y_bottom, point.y_top ];
630 prevY = point.y;
631 } else {
632 newYs = [ point.y_bottom, point.y_top ];
633 }
634 newYs[0] = e.plotArea.h * newYs[0] + e.plotArea.y;
635 newYs[1] = e.plotArea.h * newYs[1] + e.plotArea.y;
636 if (!isNaN(prevX)) {
637 if (stepPlot) {
638 ctx.moveTo(prevX, prevYs[0]);
639 ctx.lineTo(point.canvasx, prevYs[0]);
640 ctx.lineTo(point.canvasx, prevYs[1]);
641 } else {
642 ctx.moveTo(prevX, prevYs[0]);
643 ctx.lineTo(point.canvasx, newYs[0]);
644 ctx.lineTo(point.canvasx, newYs[1]);
645 }
646 ctx.lineTo(prevX, prevYs[1]);
647 ctx.closePath();
648 }
649 prevYs = newYs;
650 prevX = point.canvasx;
651 }
652 ctx.fill();
653 };
654
655 /**
656 * Draws the shaded regions when "fillGraph" is set. Not to be confused with
657 * error bars.
658 *
659 * For stacked charts, it's more convenient to handle all the series
660 * simultaneously. So this plotter plots all the points on the first series
661 * it's asked to draw, then ignores all the other series.
662 *
663 * @private
664 */
665 DygraphCanvasRenderer._fillPlotter = function(e) {
666 // We'll handle all the series at once, not one-by-one.
667 if (e.seriesIndex !== 0) return;
668
669 var g = e.dygraph;
670 var setNames = g.getLabels().slice(1); // remove x-axis
671
672 // getLabels() includes names for invisible series, which are not included in
673 // allSeriesPoints. We remove those to make the two match.
674 // TODO(danvk): provide a simpler way to get this information.
675 for (var i = setNames.length; i >= 0; i--) {
676 if (!g.visibility()[i]) setNames.splice(i, 1);
677 }
678
679 var anySeriesFilled = (function() {
680 for (var i = 0; i < setNames.length; i++) {
681 if (g.getOption("fillGraph", setNames[i])) return true;
682 }
683 return false;
684 })();
685
686 if (!anySeriesFilled) return;
687
688 var ctx = e.drawingContext;
689 var area = e.plotArea;
690 var sets = e.allSeriesPoints;
691 var setCount = sets.length;
692
693 var fillAlpha = g.getOption('fillAlpha');
694 var stepPlot = g.getOption('stepPlot');
695 var stackedGraph = g.getOption("stackedGraph");
696 var colors = g.getColors();
697
698 var baseline = {}; // for stacked graphs: baseline for filling
699 var currBaseline;
700
701 // process sets in reverse order (needed for stacked graphs)
702 for (var setIdx = setCount - 1; setIdx >= 0; setIdx--) {
703 var setName = setNames[setIdx];
704 if (!g.getOption('fillGraph', setName)) continue;
705
706 var color = colors[setIdx];
707 var axis = g.axisPropertiesForSeries(setName);
708 var axisY = 1.0 + axis.minyval * axis.yscale;
709 if (axisY < 0.0) axisY = 0.0;
710 else if (axisY > 1.0) axisY = 1.0;
711 axisY = area.h * axisY + area.y;
712
713 var points = sets[setIdx];
714 var iter = Dygraph.createIterator(points, 0, points.length,
715 DygraphCanvasRenderer._getIteratorPredicate(
716 g.getOption("connectSeparatedPoints")));
717
718 // setup graphics context
719 var prevX = NaN;
720 var prevYs = [-1, -1];
721 var newYs;
722 // should be same color as the lines but only 15% opaque.
723 var rgb = new RGBColorParser(color);
724 var err_color =
725 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + fillAlpha + ')';
726 ctx.fillStyle = err_color;
727 ctx.beginPath();
728 while(iter.hasNext) {
729 var point = iter.next();
730 if (!Dygraph.isOK(point.y)) {
731 prevX = NaN;
732 continue;
733 }
734 if (stackedGraph) {
735 currBaseline = baseline[point.canvasx];
736 var lastY;
737 if (currBaseline === undefined) {
738 lastY = axisY;
739 } else {
740 if(stepPlot) {
741 lastY = currBaseline[0];
742 } else {
743 lastY = currBaseline;
744 }
745 }
746 newYs = [ point.canvasy, lastY ];
747
748 if(stepPlot) {
749 // Step plots must keep track of the top and bottom of
750 // the baseline at each point.
751 if(prevYs[0] === -1) {
752 baseline[point.canvasx] = [ point.canvasy, axisY ];
753 } else {
754 baseline[point.canvasx] = [ point.canvasy, prevYs[0] ];
755 }
756 } else {
757 baseline[point.canvasx] = point.canvasy;
758 }
759
760 } else {
761 newYs = [ point.canvasy, axisY ];
762 }
763 if (!isNaN(prevX)) {
764 ctx.moveTo(prevX, prevYs[0]);
765
766 if (stepPlot) {
767 ctx.lineTo(point.canvasx, prevYs[0]);
768 if(currBaseline) {
769 // Draw to the bottom of the baseline
770 ctx.lineTo(point.canvasx, currBaseline[1]);
771 } else {
772 ctx.lineTo(point.canvasx, newYs[1]);
773 }
774 } else {
775 ctx.lineTo(point.canvasx, newYs[0]);
776 ctx.lineTo(point.canvasx, newYs[1]);
777 }
778
779 ctx.lineTo(prevX, prevYs[1]);
780 ctx.closePath();
781 }
782 prevYs = newYs;
783 prevX = point.canvasx;
784 }
785 ctx.fill();
786 }
787 };