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