Check for visible viewport width, not the plotter width
[dygraphs.git] / dygraph-canvas.js
CommitLineData
88e95c46
DV
1/**
2 * @license
3 * Copyright 2006 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
5 */
6a1aa64f
DV
6
7/**
74a5af31
DV
8 * @fileoverview Based on PlotKit.CanvasRenderer, but modified to meet the
9 * needs of dygraphs.
10 *
3df0ccf0 11 * In particular, support for:
0abfbd7e 12 * - grid overlays
3df0ccf0
DV
13 * - error bars
14 * - dygraphs attribute system
6a1aa64f
DV
15 */
16
6a1aa64f 17/**
423f5ed3
DV
18 * The DygraphCanvasRenderer class does the actual rendering of the chart onto
19 * a canvas. It's based on PlotKit.CanvasRenderer.
6a1aa64f 20 * @param {Object} element The canvas to attach to
2cf95fff
RK
21 * @param {Object} elementContext The 2d context of the canvas (injected so it
22 * can be mocked for testing.)
285a6bda 23 * @param {Layout} layout The DygraphLayout object for this graph.
74a5af31 24 * @constructor
6a1aa64f 25 */
c0f54d4f 26
758a629f 27/*jshint globalstrict: true */
464b5f50 28/*global Dygraph:false */
c0f54d4f
DV
29"use strict";
30
79253bd0 31
8cfe592f
DV
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 *
7b00a3cd 42 * @param {Dygraph} dygraph The chart to which this renderer belongs.
48fc4786 43 * @param {HTMLCanvasElement} element The <canvas> DOM element on which to draw.
8cfe592f
DV
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 */
c0f54d4f 49var DygraphCanvasRenderer = function(dygraph, element, elementContext, layout) {
9317362d 50 this.dygraph_ = dygraph;
fbe31dc8 51
fbe31dc8 52 this.layout = layout;
b0c3b730 53 this.element = element;
2cf95fff 54 this.elementContext = elementContext;
fbe31dc8
DV
55 this.container = this.element.parentNode;
56
fbe31dc8
DV
57 this.height = this.element.height;
58 this.width = this.element.width;
59
60 // --- check whether everything is ok before we return
48fc4786 61 // NOTE(konigsberg): isIE is never defined in this object. Bug of some sort.
55deb02f 62 if (!this.isIE && !(Dygraph.isCanvasSupported(this.element)))
fbe31dc8
DV
63 throw "Canvas is not supported.";
64
65 // internal state
70be5ed1 66 this.area = layout.getPlotArea();
423f5ed3
DV
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.
920208fb
PF
72 if (this.dygraph_.isUsingExcanvas_) {
73 this._createIEClipArea();
74 } else {
971870e5
DV
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();
920208fb 82
971870e5
DV
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 }
920208fb 88 }
423f5ed3
DV
89};
90
38e3d209 91/**
8cfe592f
DV
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 */
fbe31dc8 97DygraphCanvasRenderer.prototype.clear = function() {
758a629f 98 var context;
fbe31dc8
DV
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 }
758a629f 106 context = this.elementContext;
fbe31dc8
DV
107 }
108 catch (e) {
76171648 109 // TODO(danvk): this is broken, since MochiKit.Async is gone.
758a629f
DV
110 // this.clearDelay = MochiKit.Async.wait(this.IEDelay);
111 // this.clearDelay.addCallback(bind(this.clear, this));
fbe31dc8
DV
112 return;
113 }
114 }
115
758a629f 116 context = this.elementContext;
fbe31dc8 117 context.clearRect(0, 0, this.width, this.height);
fbe31dc8
DV
118};
119
8cfe592f 120/**
8cfe592f
DV
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
6a1aa64f 126 */
285a6bda 127DygraphCanvasRenderer.prototype.render = function() {
38e3d209
DV
128 // attaches point.canvas{x,y}
129 this._updatePoints();
130
131 // actually draws the chart.
2ce09b19 132 this._renderLineChart();
fbe31dc8
DV
133};
134
920208fb
PF
135DygraphCanvasRenderer.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) {
758a629f 159 if (area.w === 0 || area.h === 0) {
920208fb
PF
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
758a629f
DV
175 createClipDiv({
176 x:0, y:0,
177 w:plotArea.x,
178 h:this.height
179 });
180
920208fb 181 // Top
758a629f
DV
182 createClipDiv({
183 x: plotArea.x, y: 0,
184 w: this.width - plotArea.x,
185 h: plotArea.y
186 });
187
920208fb 188 // Right side
758a629f
DV
189 createClipDiv({
190 x: plotArea.x + plotArea.w, y: 0,
191 w: this.width-plotArea.x - plotArea.w,
192 h: this.height
193 });
194
920208fb 195 // Bottom
758a629f
DV
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};
fbe31dc8 203
fbe31dc8 204
ccb0001c 205/**
8722284b
RK
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.
ccb0001c 210 */
8722284b 211DygraphCanvasRenderer._getIteratorPredicate = function(connectSeparatedPoints) {
42a9ebb8
DV
212 return connectSeparatedPoints ?
213 DygraphCanvasRenderer._predicateThatSkipsEmptyPoints :
214 null;
0f20de1c 215};
8722284b
RK
216
217DygraphCanvasRenderer._predicateThatSkipsEmptyPoints =
0f20de1c
DV
218 function(array, idx) {
219 return array[idx].yval !== null;
220};
04c104d7 221
9f6db80e 222/**
38e3d209
DV
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.
9f6db80e
DV
225 * @private
226 */
38e3d209
DV
227DygraphCanvasRenderer._drawStyledLine = function(e,
228 color, strokeWidth, strokePattern, drawPoints,
5469113b 229 drawPointCallback, pointSize) {
38e3d209 230 var g = e.dygraph;
99a77a04 231 // TODO(konigsberg): Compute attributes outside this method call.
0e85a437 232 var stepPlot = g.getBooleanOption("stepPlot", e.setName);
2f56cd46 233
857a6931
KW
234 if (!Dygraph.isArrayLike(strokePattern)) {
235 strokePattern = null;
236 }
237
0e85a437 238 var drawGapPoints = g.getBooleanOption('drawGapEdgePoints', e.setName);
38e3d209
DV
239
240 var points = e.points;
b85358e2 241 var setName = e.setName;
a12a78ae 242 var iter = Dygraph.createIterator(points, 0, points.length,
9f6db80e 243 DygraphCanvasRenderer._getIteratorPredicate(
0e85a437 244 g.getBooleanOption("connectSeparatedPoints", setName)));
7d1afbb9 245
fb63bf1b
DV
246 var stroking = strokePattern && (strokePattern.length >= 2);
247
38e3d209 248 var ctx = e.drawingContext;
0140347d 249 ctx.save();
fb63bf1b
DV
250 if (stroking) {
251 ctx.installPattern(strokePattern);
b843b52c 252 }
fb63bf1b 253
38e3d209
DV
254 var pointsOnLine = DygraphCanvasRenderer._drawSeries(
255 e, iter, strokeWidth, pointSize, drawPoints, drawGapPoints, stepPlot, color);
256 DygraphCanvasRenderer._drawPointsOnLine(
257 e, pointsOnLine, drawPointCallback, color, pointSize);
31f8e58b 258
fb63bf1b
DV
259 if (stroking) {
260 ctx.uninstallPattern();
261 }
b843b52c 262
fb63bf1b 263 ctx.restore();
31f8e58b
RK
264};
265
38e3d209
DV
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 */
274DygraphCanvasRenderer._drawSeries = function(e,
275 iter, strokeWidth, pointSize, drawPoints, drawGapPoints, stepPlot, color) {
31f8e58b 276
31f8e58b
RK
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
b843b52c 282 var pointsOnLine = []; // Array of [canvasx, canvasy] pairs.
31f8e58b
RK
283 var first = true; // the first cycle through the while loop
284
38e3d209 285 var ctx = e.drawingContext;
0140347d
DV
286 ctx.beginPath();
287 ctx.strokeStyle = color;
288 ctx.lineWidth = strokeWidth;
31f8e58b 289
239454e2 290 // NOTE: we break the iterator's encapsulation here for about a 25% speedup.
c560c848
DV
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)) {
0f20de1c
DV
299 i++;
300 }
c560c848
DV
301 if (i == limit) break;
302 point = arr[i];
0f20de1c
DV
303 }
304
b7ec6c55
PH
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?
a02978e2 308 if (point.canvasy === null || point.canvasy != point.canvasy) {
31f8e58b 309 if (stepPlot && prevCanvasX !== null) {
857a6931 310 // Draw a horizontal line to the start of the missing data
42a9ebb8
DV
311 ctx.moveTo(prevCanvasX, prevCanvasY);
312 ctx.lineTo(point.canvasx, prevCanvasY);
857a6931 313 }
31f8e58b 314 prevCanvasX = prevCanvasY = null;
857a6931 315 } else {
0f20de1c
DV
316 isIsolated = false;
317 if (drawGapPoints || !prevCanvasX) {
0f20de1c 318 iter.nextIdx_ = i;
0cd1ad15 319 iter.next();
82f9b10f 320 nextCanvasY = iter.hasNext ? iter.peek.canvasy : null;
0f20de1c 321
0f20de1c
DV
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 }
19b84fe7
KW
332 }
333 }
0f20de1c 334
31f8e58b 335 if (prevCanvasX !== null) {
857a6931 336 if (strokeWidth) {
857a6931 337 if (stepPlot) {
0140347d
DV
338 ctx.moveTo(prevCanvasX, prevCanvasY);
339 ctx.lineTo(point.canvasx, prevCanvasY);
857a6931 340 }
239454e2 341
0140347d 342 ctx.lineTo(point.canvasx, point.canvasy);
b843b52c 343 }
9f636500
DV
344 } else {
345 ctx.moveTo(point.canvasx, point.canvasy);
b843b52c 346 }
b843b52c 347 if (drawPoints || isIsolated) {
b616fad1 348 pointsOnLine.push([point.canvasx, point.canvasy, point.idx]);
b843b52c 349 }
31f8e58b
RK
350 prevCanvasX = point.canvasx;
351 prevCanvasY = point.canvasy;
b843b52c 352 }
7d1afbb9 353 first = false;
b843b52c 354 }
0140347d 355 ctx.stroke();
31f8e58b 356 return pointsOnLine;
857a6931
KW
357};
358
38e3d209
DV
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 */
366DygraphCanvasRenderer._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(
ba697462 373 e.dygraph, e.setName, ctx, cb[0], cb[1], color, pointSize, cb[2]);
38e3d209 374 ctx.restore();
857a6931 375 }
42a9ebb8 376};
ce49c2fa 377
6a1aa64f 378/**
38e3d209 379 * Attaches canvas coordinates to the points array.
758a629f 380 * @private
6a1aa64f 381 */
38e3d209 382DygraphCanvasRenderer.prototype._updatePoints = function() {
ff00d3e2
DV
383 // Update Points
384 // TODO(danvk): here
b843b52c
RK
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.
e60234cd
DV
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%.
a12a78ae 395 var sets = this.layout.points;
38e3d209 396 for (var i = sets.length; i--;) {
a12a78ae
DV
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 }
6a1aa64f 403 }
38e3d209 404};
6a1aa64f 405
38e3d209
DV
406/**
407 * Add canvas Actually draw the lines chart, including error bars.
38e3d209
DV
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.
48fc4786
RK
412 *
413 * @param {string=} opt_seriesName when specified, only that series will
34655aba
RK
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.
38e3d209
DV
418 * @private
419 */
420DygraphCanvasRenderer.prototype._renderLineChart = function(opt_seriesName, opt_ctx) {
421 var ctx = opt_ctx || this.elementContext;
38e3d209 422 var i;
6a834bbb 423
38e3d209
DV
424 var sets = this.layout.points;
425 var setNames = this.layout.setNames;
42a9ebb8 426 var setName;
38e3d209
DV
427
428 this.colors = this.dygraph_.colorsMap_;
429
430 // Determine which series have specialized plotters.
0e85a437 431 var plotter_attr = this.dygraph_.getOption("plotter");
38e3d209
DV
432 var plotters = plotter_attr;
433 if (!Dygraph.isArrayLike(plotters)) {
434 plotters = [plotters];
80aaae18
DV
435 }
436
38e3d209
DV
437 var setPlotters = {}; // series name -> plotter fn.
438 for (i = 0; i < setNames.length; i++) {
42a9ebb8 439 setName = setNames[i];
0e85a437 440 var setPlotter = this.dygraph_.getOption("plotter", setName);
38e3d209
DV
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++) {
42a9ebb8 451 setName = setNames[j];
4b2e41a4 452 if (opt_seriesName && setName != opt_seriesName) continue;
38e3d209
DV
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,
3c080cd0 484 singleSeriesName: opt_seriesName,
38e3d209
DV
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 */
496DygraphCanvasRenderer._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);
80aaae18 507 }
6a1aa64f 508};
79253bd0 509
01a14b85 510/**
38e3d209
DV
511 * Plotter which draws the central lines for a series.
512 * @private
513 */
514DygraphCanvasRenderer._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.
0e85a437 522 var borderWidth = g.getNumericOption("strokeBorderWidth", setName);
38e3d209
DV
523 var drawPointCallback = g.getOption("drawPointCallback", setName) ||
524 Dygraph.Circles.DEFAULT;
525 var strokePattern = g.getOption("strokePattern", setName);
0e85a437
DV
526 var drawPoints = g.getBooleanOption("drawPoints", setName);
527 var pointSize = g.getNumericOption("pointSize", setName);
38e3d209
DV
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 );
42a9ebb8 548};
38e3d209
DV
549
550/**
01a14b85
DV
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.
01a14b85
DV
554 * @private
555 */
38e3d209
DV
556DygraphCanvasRenderer._errorPlotter = function(e) {
557 var g = e.dygraph;
e2d8db3a 558 var setName = e.setName;
0e85a437
DV
559 var errorBars = g.getBooleanOption("errorBars") ||
560 g.getBooleanOption("customBars");
38e3d209
DV
561 if (!errorBars) return;
562
0e85a437 563 var fillGraph = g.getBooleanOption("fillGraph", setName);
38e3d209 564 if (fillGraph) {
464b5f50 565 Dygraph.warn("Can't use fillGraph option with error bars");
38e3d209 566 }
6a6439da 567
38e3d209
DV
568 var ctx = e.drawingContext;
569 var color = e.color;
0e85a437
DV
570 var fillAlpha = g.getNumericOption('fillAlpha', setName);
571 var stepPlot = g.getBooleanOption("stepPlot", setName);
38e3d209 572 var points = e.points;
6a6439da 573
38e3d209
DV
574 var iter = Dygraph.createIterator(points, 0, points.length,
575 DygraphCanvasRenderer._getIteratorPredicate(
0e85a437 576 g.getBooleanOption("connectSeparatedPoints", setName)));
6a6439da 577
38e3d209 578 var newYs;
6a6439da 579
38e3d209
DV
580 // setup graphics context
581 var prevX = NaN;
582 var prevY = NaN;
583 var prevYs = [-1, -1];
38e3d209 584 // should be same color as the lines but only 15% opaque.
464b5f50 585 var rgb = Dygraph.toRGB_(color);
38e3d209
DV
586 var err_color =
587 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + fillAlpha + ')';
588 ctx.fillStyle = err_color;
589 ctx.beginPath();
cf89eeed
DV
590
591 var isNullUndefinedOrNaN = function(x) {
592 return (x === null ||
593 x === undefined ||
594 isNaN(x));
595 };
596
38e3d209
DV
597 while (iter.hasNext) {
598 var point = iter.next();
cf89eeed
DV
599 if ((!stepPlot && isNullUndefinedOrNaN(point.y)) ||
600 (stepPlot && !isNaN(prevY) && isNullUndefinedOrNaN(prevY))) {
38e3d209
DV
601 prevX = NaN;
602 continue;
603 }
6a6439da 604
38e3d209
DV
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)) {
a5701188 614 if (stepPlot) {
38e3d209 615 ctx.moveTo(prevX, prevYs[0]);
82dd90c5 616 ctx.lineTo(point.canvasx, prevYs[0]);
617 ctx.lineTo(point.canvasx, prevYs[1]);
38e3d209 618 } else {
82dd90c5 619 ctx.moveTo(prevX, prevYs[0]);
620 ctx.lineTo(point.canvasx, newYs[0]);
621 ctx.lineTo(point.canvasx, newYs[1]);
6a6439da 622 }
82dd90c5 623 ctx.lineTo(prevX, prevYs[1]);
38e3d209 624 ctx.closePath();
6a6439da 625 }
38e3d209
DV
626 prevYs = newYs;
627 prevX = point.canvasx;
6a6439da 628 }
38e3d209 629 ctx.fill();
42a9ebb8 630};
6a6439da 631
79253bd0 632/**
01a14b85
DV
633 * Draws the shaded regions when "fillGraph" is set. Not to be confused with
634 * error bars.
635 *
38e3d209
DV
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 *
01a14b85
DV
640 * @private
641 */
38e3d209 642DygraphCanvasRenderer._fillPlotter = function(e) {
3c080cd0
KW
643 // Skip if we're drawing a single series for interactive highlight overlay.
644 if (e.singleSeriesName) return;
645
38e3d209
DV
646 // We'll handle all the series at once, not one-by-one.
647 if (e.seriesIndex !== 0) return;
648
e2d8db3a 649 var g = e.dygraph;
38e3d209 650 var setNames = g.getLabels().slice(1); // remove x-axis
e2d8db3a 651
38e3d209
DV
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
e2d8db3a
DV
659 var anySeriesFilled = (function() {
660 for (var i = 0; i < setNames.length; i++) {
0e85a437 661 if (g.getBooleanOption("fillGraph", setNames[i])) return true;
e2d8db3a
DV
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
0e85a437
DV
673 var fillAlpha = g.getNumericOption('fillAlpha');
674 var stackedGraph = g.getBooleanOption("stackedGraph");
38e3d209 675 var colors = g.getColors();
01a14b85 676
30a5cfc6
KW
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 = {};
01a14b85 685 var currBaseline;
104d87c5 686 var prevStepPlot; // for different line drawing modes (line/step) per series
01a14b85
DV
687
688 // process sets in reverse order (needed for stacked graphs)
9e85a8f4
DV
689 for (var setIdx = setCount - 1; setIdx >= 0; setIdx--) {
690 var setName = setNames[setIdx];
0e85a437 691 if (!g.getBooleanOption('fillGraph', setName)) continue;
104d87c5 692
0e85a437 693 var stepPlot = g.getBooleanOption('stepPlot', setName);
38e3d209
DV
694 var color = colors[setIdx];
695 var axis = g.axisPropertiesForSeries(setName);
01a14b85
DV
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;
38e3d209 699 axisY = area.h * axisY + area.y;
01a14b85 700
38e3d209 701 var points = sets[setIdx];
9e85a8f4 702 var iter = Dygraph.createIterator(points, 0, points.length,
01a14b85 703 DygraphCanvasRenderer._getIteratorPredicate(
0e85a437 704 g.getBooleanOption("connectSeparatedPoints", setName)));
01a14b85
DV
705
706 // setup graphics context
707 var prevX = NaN;
708 var prevYs = [-1, -1];
709 var newYs;
01a14b85 710 // should be same color as the lines but only 15% opaque.
464b5f50 711 var rgb = Dygraph.toRGB_(color);
01a14b85
DV
712 var err_color =
713 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + fillAlpha + ')';
714 ctx.fillStyle = err_color;
715 ctx.beginPath();
12b879f4
DV
716 var last_x, is_first = true;
717 while (iter.hasNext) {
01a14b85 718 var point = iter.next();
16febe6b
DV
719 if (!Dygraph.isOK(point.y)) {
720 prevX = NaN;
30a5cfc6
KW
721 if (point.y_stacked !== null && !isNaN(point.y_stacked)) {
722 baseline[point.canvasx] = area.h * point.y_stacked + area.y;
723 }
16febe6b
DV
724 continue;
725 }
726 if (stackedGraph) {
12b879f4
DV
727 if (!is_first && last_x == point.xval) {
728 continue;
729 } else {
730 is_first = false;
731 last_x = point.xval;
732 }
733
16febe6b
DV
734 currBaseline = baseline[point.canvasx];
735 var lastY;
736 if (currBaseline === undefined) {
737 lastY = axisY;
738 } else {
104d87c5 739 if(prevStepPlot) {
16febe6b 740 lastY = currBaseline[0];
01a14b85 741 } else {
16febe6b 742 lastY = currBaseline;
01a14b85 743 }
16febe6b
DV
744 }
745 newYs = [ point.canvasy, lastY ];
01a14b85 746
16febe6b
DV
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 ];
01a14b85 752 } else {
16febe6b 753 baseline[point.canvasx] = [ point.canvasy, prevYs[0] ];
01a14b85 754 }
01a14b85 755 } else {
16febe6b 756 baseline[point.canvasx] = point.canvasy;
01a14b85 757 }
01a14b85 758
16febe6b
DV
759 } else {
760 newYs = [ point.canvasy, axisY ];
761 }
762 if (!isNaN(prevX)) {
763 ctx.moveTo(prevX, prevYs[0]);
104d87c5 764
765 // Move to top fill point
16febe6b
DV
766 if (stepPlot) {
767 ctx.lineTo(point.canvasx, prevYs[0]);
16febe6b
DV
768 } else {
769 ctx.lineTo(point.canvasx, newYs[0]);
104d87c5 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 {
16febe6b 776 ctx.lineTo(point.canvasx, newYs[1]);
01a14b85 777 }
16febe6b
DV
778
779 ctx.lineTo(prevX, prevYs[1]);
780 ctx.closePath();
01a14b85 781 }
16febe6b
DV
782 prevYs = newYs;
783 prevX = point.canvasx;
01a14b85 784 }
104d87c5 785 prevStepPlot = stepPlot;
01a14b85
DV
786 ctx.fill();
787 }
788};