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