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