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