Merge
[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
3ce712e6 27var DygraphCanvasRenderer = (function() {
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 55
7c39bb3a
DV
56 this.height = dygraph.height_;
57 this.width = dygraph.width_;
fbe31dc8
DV
58
59 // --- check whether everything is ok before we return
48fc4786 60 // NOTE(konigsberg): isIE is never defined in this object. Bug of some sort.
55deb02f 61 if (!this.isIE && !(Dygraph.isCanvasSupported(this.element)))
fbe31dc8
DV
62 throw "Canvas is not supported.";
63
64 // internal state
70be5ed1 65 this.area = layout.getPlotArea();
423f5ed3
DV
66
67 // Set up a clipping area for the canvas (and the interaction canvas).
68 // This ensures that we don't overdraw.
920208fb
PF
69 if (this.dygraph_.isUsingExcanvas_) {
70 this._createIEClipArea();
71 } else {
971870e5
DV
72 // on Android 3 and 4, setting a clipping area on a canvas prevents it from
73 // displaying anything.
74 if (!Dygraph.isAndroid()) {
75 var ctx = this.dygraph_.canvas_ctx_;
76 ctx.beginPath();
77 ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h);
78 ctx.clip();
920208fb 79
971870e5
DV
80 ctx = this.dygraph_.hidden_ctx_;
81 ctx.beginPath();
82 ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h);
83 ctx.clip();
84 }
920208fb 85 }
423f5ed3
DV
86};
87
38e3d209 88/**
8cfe592f
DV
89 * Clears out all chart content and DOM elements.
90 * This is called immediately before render() on every frame, including
91 * during zooms and pans.
92 * @private
93 */
fbe31dc8 94DygraphCanvasRenderer.prototype.clear = function() {
758a629f 95 var context;
fbe31dc8
DV
96 if (this.isIE) {
97 // VML takes a while to start up, so we just poll every this.IEDelay
98 try {
99 if (this.clearDelay) {
100 this.clearDelay.cancel();
101 this.clearDelay = null;
102 }
758a629f 103 context = this.elementContext;
fbe31dc8
DV
104 }
105 catch (e) {
76171648 106 // TODO(danvk): this is broken, since MochiKit.Async is gone.
758a629f
DV
107 // this.clearDelay = MochiKit.Async.wait(this.IEDelay);
108 // this.clearDelay.addCallback(bind(this.clear, this));
fbe31dc8
DV
109 return;
110 }
111 }
112
758a629f 113 context = this.elementContext;
fbe31dc8 114 context.clearRect(0, 0, this.width, this.height);
fbe31dc8
DV
115};
116
8cfe592f 117/**
8cfe592f
DV
118 * This method is responsible for drawing everything on the chart, including
119 * lines, error bars, fills and axes.
120 * It is called immediately after clear() on every frame, including during pans
121 * and zooms.
122 * @private
6a1aa64f 123 */
285a6bda 124DygraphCanvasRenderer.prototype.render = function() {
38e3d209
DV
125 // attaches point.canvas{x,y}
126 this._updatePoints();
127
128 // actually draws the chart.
2ce09b19 129 this._renderLineChart();
fbe31dc8
DV
130};
131
920208fb
PF
132DygraphCanvasRenderer.prototype._createIEClipArea = function() {
133 var className = 'dygraph-clip-div';
134 var graphDiv = this.dygraph_.graphDiv;
135
136 // Remove old clip divs.
137 for (var i = graphDiv.childNodes.length-1; i >= 0; i--) {
138 if (graphDiv.childNodes[i].className == className) {
139 graphDiv.removeChild(graphDiv.childNodes[i]);
140 }
141 }
142
143 // Determine background color to give clip divs.
144 var backgroundColor = document.bgColor;
145 var element = this.dygraph_.graphDiv;
146 while (element != document) {
147 var bgcolor = element.currentStyle.backgroundColor;
148 if (bgcolor && bgcolor != 'transparent') {
149 backgroundColor = bgcolor;
150 break;
151 }
152 element = element.parentNode;
153 }
154
155 function createClipDiv(area) {
758a629f 156 if (area.w === 0 || area.h === 0) {
920208fb
PF
157 return;
158 }
159 var elem = document.createElement('div');
160 elem.className = className;
161 elem.style.backgroundColor = backgroundColor;
162 elem.style.position = 'absolute';
163 elem.style.left = area.x + 'px';
164 elem.style.top = area.y + 'px';
165 elem.style.width = area.w + 'px';
166 elem.style.height = area.h + 'px';
167 graphDiv.appendChild(elem);
168 }
169
170 var plotArea = this.area;
171 // Left side
758a629f
DV
172 createClipDiv({
173 x:0, y:0,
174 w:plotArea.x,
175 h:this.height
176 });
177
920208fb 178 // Top
758a629f
DV
179 createClipDiv({
180 x: plotArea.x, y: 0,
181 w: this.width - plotArea.x,
182 h: plotArea.y
183 });
184
920208fb 185 // Right side
758a629f
DV
186 createClipDiv({
187 x: plotArea.x + plotArea.w, y: 0,
7c39bb3a 188 w: this.width - plotArea.x - plotArea.w,
758a629f
DV
189 h: this.height
190 });
191
920208fb 192 // Bottom
758a629f
DV
193 createClipDiv({
194 x: plotArea.x,
195 y: plotArea.y + plotArea.h,
196 w: this.width - plotArea.x,
197 h: this.height - plotArea.h - plotArea.y
198 });
199};
fbe31dc8 200
fbe31dc8 201
ccb0001c 202/**
8722284b
RK
203 * Returns a predicate to be used with an iterator, which will
204 * iterate over points appropriately, depending on whether
205 * connectSeparatedPoints is true. When it's false, the predicate will
206 * skip over points with missing yVals.
ccb0001c 207 */
8722284b 208DygraphCanvasRenderer._getIteratorPredicate = function(connectSeparatedPoints) {
42a9ebb8
DV
209 return connectSeparatedPoints ?
210 DygraphCanvasRenderer._predicateThatSkipsEmptyPoints :
211 null;
0f20de1c 212};
8722284b
RK
213
214DygraphCanvasRenderer._predicateThatSkipsEmptyPoints =
0f20de1c
DV
215 function(array, idx) {
216 return array[idx].yval !== null;
217};
04c104d7 218
9f6db80e 219/**
38e3d209
DV
220 * Draws a line with the styles passed in and calls all the drawPointCallbacks.
221 * @param {Object} e The dictionary passed to the plotter function.
9f6db80e
DV
222 * @private
223 */
38e3d209
DV
224DygraphCanvasRenderer._drawStyledLine = function(e,
225 color, strokeWidth, strokePattern, drawPoints,
5469113b 226 drawPointCallback, pointSize) {
38e3d209 227 var g = e.dygraph;
99a77a04 228 // TODO(konigsberg): Compute attributes outside this method call.
0e85a437 229 var stepPlot = g.getBooleanOption("stepPlot", e.setName);
2f56cd46 230
857a6931
KW
231 if (!Dygraph.isArrayLike(strokePattern)) {
232 strokePattern = null;
233 }
234
0e85a437 235 var drawGapPoints = g.getBooleanOption('drawGapEdgePoints', e.setName);
38e3d209
DV
236
237 var points = e.points;
b85358e2 238 var setName = e.setName;
a12a78ae 239 var iter = Dygraph.createIterator(points, 0, points.length,
9f6db80e 240 DygraphCanvasRenderer._getIteratorPredicate(
0e85a437 241 g.getBooleanOption("connectSeparatedPoints", setName)));
7d1afbb9 242
fb63bf1b
DV
243 var stroking = strokePattern && (strokePattern.length >= 2);
244
38e3d209 245 var ctx = e.drawingContext;
0140347d 246 ctx.save();
fb63bf1b
DV
247 if (stroking) {
248 ctx.installPattern(strokePattern);
b843b52c 249 }
fb63bf1b 250
38e3d209
DV
251 var pointsOnLine = DygraphCanvasRenderer._drawSeries(
252 e, iter, strokeWidth, pointSize, drawPoints, drawGapPoints, stepPlot, color);
253 DygraphCanvasRenderer._drawPointsOnLine(
254 e, pointsOnLine, drawPointCallback, color, pointSize);
31f8e58b 255
fb63bf1b
DV
256 if (stroking) {
257 ctx.uninstallPattern();
258 }
b843b52c 259
fb63bf1b 260 ctx.restore();
31f8e58b
RK
261};
262
38e3d209
DV
263/**
264 * This does the actual drawing of lines on the canvas, for just one series.
265 * Returns a list of [canvasx, canvasy] pairs for points for which a
266 * drawPointCallback should be fired. These include isolated points, or all
267 * points if drawPoints=true.
268 * @param {Object} e The dictionary passed to the plotter function.
269 * @private
270 */
271DygraphCanvasRenderer._drawSeries = function(e,
272 iter, strokeWidth, pointSize, drawPoints, drawGapPoints, stepPlot, color) {
31f8e58b 273
31f8e58b
RK
274 var prevCanvasX = null;
275 var prevCanvasY = null;
276 var nextCanvasY = null;
277 var isIsolated; // true if this point is isolated (no line segments)
278 var point; // the point being processed in the while loop
b843b52c 279 var pointsOnLine = []; // Array of [canvasx, canvasy] pairs.
31f8e58b
RK
280 var first = true; // the first cycle through the while loop
281
38e3d209 282 var ctx = e.drawingContext;
0140347d
DV
283 ctx.beginPath();
284 ctx.strokeStyle = color;
285 ctx.lineWidth = strokeWidth;
31f8e58b 286
239454e2 287 // NOTE: we break the iterator's encapsulation here for about a 25% speedup.
c560c848
DV
288 var arr = iter.array_;
289 var limit = iter.end_;
290 var predicate = iter.predicate_;
291
292 for (var i = iter.start_; i < limit; i++) {
293 point = arr[i];
294 if (predicate) {
295 while (i < limit && !predicate(arr, i)) {
0f20de1c
DV
296 i++;
297 }
c560c848
DV
298 if (i == limit) break;
299 point = arr[i];
0f20de1c
DV
300 }
301
b7ec6c55
PH
302 // FIXME: The 'canvasy != canvasy' test here catches NaN values but the test
303 // doesn't catch Infinity values. Could change this to
304 // !isFinite(point.canvasy), but I assume it avoids isNaN for performance?
a02978e2 305 if (point.canvasy === null || point.canvasy != point.canvasy) {
31f8e58b 306 if (stepPlot && prevCanvasX !== null) {
857a6931 307 // Draw a horizontal line to the start of the missing data
42a9ebb8
DV
308 ctx.moveTo(prevCanvasX, prevCanvasY);
309 ctx.lineTo(point.canvasx, prevCanvasY);
857a6931 310 }
31f8e58b 311 prevCanvasX = prevCanvasY = null;
857a6931 312 } else {
0f20de1c
DV
313 isIsolated = false;
314 if (drawGapPoints || !prevCanvasX) {
0f20de1c 315 iter.nextIdx_ = i;
0cd1ad15 316 iter.next();
82f9b10f 317 nextCanvasY = iter.hasNext ? iter.peek.canvasy : null;
0f20de1c 318
0f20de1c
DV
319 var isNextCanvasYNullOrNaN = nextCanvasY === null ||
320 nextCanvasY != nextCanvasY;
321 isIsolated = (!prevCanvasX && isNextCanvasYNullOrNaN);
322 if (drawGapPoints) {
323 // Also consider a point to be "isolated" if it's adjacent to a
324 // null point, excluding the graph edges.
325 if ((!first && !prevCanvasX) ||
326 (iter.hasNext && isNextCanvasYNullOrNaN)) {
327 isIsolated = true;
328 }
19b84fe7
KW
329 }
330 }
0f20de1c 331
31f8e58b 332 if (prevCanvasX !== null) {
857a6931 333 if (strokeWidth) {
857a6931 334 if (stepPlot) {
0140347d
DV
335 ctx.moveTo(prevCanvasX, prevCanvasY);
336 ctx.lineTo(point.canvasx, prevCanvasY);
857a6931 337 }
239454e2 338
0140347d 339 ctx.lineTo(point.canvasx, point.canvasy);
b843b52c 340 }
9f636500
DV
341 } else {
342 ctx.moveTo(point.canvasx, point.canvasy);
b843b52c 343 }
b843b52c 344 if (drawPoints || isIsolated) {
b616fad1 345 pointsOnLine.push([point.canvasx, point.canvasy, point.idx]);
b843b52c 346 }
31f8e58b
RK
347 prevCanvasX = point.canvasx;
348 prevCanvasY = point.canvasy;
b843b52c 349 }
7d1afbb9 350 first = false;
b843b52c 351 }
0140347d 352 ctx.stroke();
31f8e58b 353 return pointsOnLine;
857a6931
KW
354};
355
38e3d209
DV
356/**
357 * This fires the drawPointCallback functions, which draw dots on the points by
358 * default. This gets used when the "drawPoints" option is set, or when there
359 * are isolated points.
360 * @param {Object} e The dictionary passed to the plotter function.
361 * @private
362 */
363DygraphCanvasRenderer._drawPointsOnLine = function(
364 e, pointsOnLine, drawPointCallback, color, pointSize) {
365 var ctx = e.drawingContext;
366 for (var idx = 0; idx < pointsOnLine.length; idx++) {
367 var cb = pointsOnLine[idx];
368 ctx.save();
4ee251cb 369 drawPointCallback.call(e.dygraph,
ba697462 370 e.dygraph, e.setName, ctx, cb[0], cb[1], color, pointSize, cb[2]);
38e3d209 371 ctx.restore();
857a6931 372 }
42a9ebb8 373};
ce49c2fa 374
6a1aa64f 375/**
38e3d209 376 * Attaches canvas coordinates to the points array.
758a629f 377 * @private
6a1aa64f 378 */
38e3d209 379DygraphCanvasRenderer.prototype._updatePoints = function() {
ff00d3e2
DV
380 // Update Points
381 // TODO(danvk): here
b843b52c
RK
382 //
383 // TODO(bhs): this loop is a hot-spot for high-point-count charts. These
384 // transformations can be pushed into the canvas via linear transformation
385 // matrices.
e60234cd
DV
386 // NOTE(danvk): this is trickier than it sounds at first. The transformation
387 // needs to be done before the .moveTo() and .lineTo() calls, but must be
388 // undone before the .stroke() call to ensure that the stroke width is
389 // unaffected. An alternative is to reduce the stroke width in the
390 // transformed coordinate space, but you can't specify different values for
391 // each dimension (as you can with .scale()). The speedup here is ~12%.
a12a78ae 392 var sets = this.layout.points;
38e3d209 393 for (var i = sets.length; i--;) {
a12a78ae
DV
394 var points = sets[i];
395 for (var j = points.length; j--;) {
396 var point = points[j];
397 point.canvasx = this.area.w * point.x + this.area.x;
398 point.canvasy = this.area.h * point.y + this.area.y;
399 }
6a1aa64f 400 }
38e3d209 401};
6a1aa64f 402
38e3d209
DV
403/**
404 * Add canvas Actually draw the lines chart, including error bars.
38e3d209
DV
405 *
406 * This function can only be called if DygraphLayout's points array has been
407 * updated with canvas{x,y} attributes, i.e. by
408 * DygraphCanvasRenderer._updatePoints.
48fc4786
RK
409 *
410 * @param {string=} opt_seriesName when specified, only that series will
34655aba
RK
411 * be drawn. (This is used for expedited redrawing with highlightSeriesOpts)
412 * @param {CanvasRenderingContext2D} opt_ctx when specified, the drawing
413 * context. However, lines are typically drawn on the object's
414 * elementContext.
38e3d209
DV
415 * @private
416 */
417DygraphCanvasRenderer.prototype._renderLineChart = function(opt_seriesName, opt_ctx) {
418 var ctx = opt_ctx || this.elementContext;
38e3d209 419 var i;
6a834bbb 420
38e3d209
DV
421 var sets = this.layout.points;
422 var setNames = this.layout.setNames;
42a9ebb8 423 var setName;
38e3d209
DV
424
425 this.colors = this.dygraph_.colorsMap_;
426
427 // Determine which series have specialized plotters.
0e85a437 428 var plotter_attr = this.dygraph_.getOption("plotter");
38e3d209
DV
429 var plotters = plotter_attr;
430 if (!Dygraph.isArrayLike(plotters)) {
431 plotters = [plotters];
80aaae18
DV
432 }
433
38e3d209
DV
434 var setPlotters = {}; // series name -> plotter fn.
435 for (i = 0; i < setNames.length; i++) {
42a9ebb8 436 setName = setNames[i];
0e85a437 437 var setPlotter = this.dygraph_.getOption("plotter", setName);
38e3d209
DV
438 if (setPlotter == plotter_attr) continue; // not specialized.
439
440 setPlotters[setName] = setPlotter;
441 }
442
443 for (i = 0; i < plotters.length; i++) {
444 var plotter = plotters[i];
445 var is_last = (i == plotters.length - 1);
446
447 for (var j = 0; j < sets.length; j++) {
42a9ebb8 448 setName = setNames[j];
4b2e41a4 449 if (opt_seriesName && setName != opt_seriesName) continue;
38e3d209
DV
450
451 var points = sets[j];
452
453 // Only throw in the specialized plotters on the last iteration.
454 var p = plotter;
455 if (setName in setPlotters) {
456 if (is_last) {
457 p = setPlotters[setName];
458 } else {
459 // Don't use the standard plotters in this case.
460 continue;
461 }
462 }
463
464 var color = this.colors[setName];
465 var strokeWidth = this.dygraph_.getOption("strokeWidth", setName);
466
467 ctx.save();
468 ctx.strokeStyle = color;
469 ctx.lineWidth = strokeWidth;
470 p({
471 points: points,
472 setName: setName,
473 drawingContext: ctx,
474 color: color,
475 strokeWidth: strokeWidth,
476 dygraph: this.dygraph_,
477 axis: this.dygraph_.axisPropertiesForSeries(setName),
478 plotArea: this.area,
479 seriesIndex: j,
480 seriesCount: sets.length,
3c080cd0 481 singleSeriesName: opt_seriesName,
38e3d209
DV
482 allSeriesPoints: sets
483 });
484 ctx.restore();
485 }
486 }
487};
488
489/**
490 * Standard plotters. These may be used by clients via Dygraph.Plotters.
491 * See comments there for more details.
492 */
493DygraphCanvasRenderer._Plotters = {
494 linePlotter: function(e) {
495 DygraphCanvasRenderer._linePlotter(e);
496 },
497
498 fillPlotter: function(e) {
499 DygraphCanvasRenderer._fillPlotter(e);
500 },
501
502 errorPlotter: function(e) {
503 DygraphCanvasRenderer._errorPlotter(e);
80aaae18 504 }
6a1aa64f 505};
79253bd0 506
01a14b85 507/**
38e3d209
DV
508 * Plotter which draws the central lines for a series.
509 * @private
510 */
511DygraphCanvasRenderer._linePlotter = function(e) {
512 var g = e.dygraph;
513 var setName = e.setName;
514 var strokeWidth = e.strokeWidth;
515
516 // TODO(danvk): Check if there's any performance impact of just calling
517 // getOption() inside of _drawStyledLine. Passing in so many parameters makes
518 // this code a bit nasty.
0e85a437 519 var borderWidth = g.getNumericOption("strokeBorderWidth", setName);
38e3d209
DV
520 var drawPointCallback = g.getOption("drawPointCallback", setName) ||
521 Dygraph.Circles.DEFAULT;
522 var strokePattern = g.getOption("strokePattern", setName);
0e85a437
DV
523 var drawPoints = g.getBooleanOption("drawPoints", setName);
524 var pointSize = g.getNumericOption("pointSize", setName);
38e3d209
DV
525
526 if (borderWidth && strokeWidth) {
527 DygraphCanvasRenderer._drawStyledLine(e,
528 g.getOption("strokeBorderColor", setName),
529 strokeWidth + 2 * borderWidth,
530 strokePattern,
531 drawPoints,
532 drawPointCallback,
533 pointSize
534 );
535 }
536
537 DygraphCanvasRenderer._drawStyledLine(e,
538 e.color,
539 strokeWidth,
540 strokePattern,
541 drawPoints,
542 drawPointCallback,
543 pointSize
544 );
42a9ebb8 545};
38e3d209
DV
546
547/**
01a14b85
DV
548 * Draws the shaded error bars/confidence intervals for each series.
549 * This happens before the center lines are drawn, since the center lines
550 * need to be drawn on top of the error bars for all series.
01a14b85
DV
551 * @private
552 */
38e3d209
DV
553DygraphCanvasRenderer._errorPlotter = function(e) {
554 var g = e.dygraph;
e2d8db3a 555 var setName = e.setName;
0e85a437
DV
556 var errorBars = g.getBooleanOption("errorBars") ||
557 g.getBooleanOption("customBars");
38e3d209
DV
558 if (!errorBars) return;
559
0e85a437 560 var fillGraph = g.getBooleanOption("fillGraph", setName);
38e3d209 561 if (fillGraph) {
8a68db7d 562 console.warn("Can't use fillGraph option with error bars");
38e3d209 563 }
6a6439da 564
38e3d209
DV
565 var ctx = e.drawingContext;
566 var color = e.color;
0e85a437
DV
567 var fillAlpha = g.getNumericOption('fillAlpha', setName);
568 var stepPlot = g.getBooleanOption("stepPlot", setName);
38e3d209 569 var points = e.points;
6a6439da 570
38e3d209
DV
571 var iter = Dygraph.createIterator(points, 0, points.length,
572 DygraphCanvasRenderer._getIteratorPredicate(
0e85a437 573 g.getBooleanOption("connectSeparatedPoints", setName)));
6a6439da 574
38e3d209 575 var newYs;
6a6439da 576
38e3d209
DV
577 // setup graphics context
578 var prevX = NaN;
579 var prevY = NaN;
580 var prevYs = [-1, -1];
38e3d209 581 // should be same color as the lines but only 15% opaque.
464b5f50 582 var rgb = Dygraph.toRGB_(color);
38e3d209
DV
583 var err_color =
584 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + fillAlpha + ')';
585 ctx.fillStyle = err_color;
586 ctx.beginPath();
cf89eeed
DV
587
588 var isNullUndefinedOrNaN = function(x) {
589 return (x === null ||
590 x === undefined ||
591 isNaN(x));
592 };
593
38e3d209
DV
594 while (iter.hasNext) {
595 var point = iter.next();
cf89eeed
DV
596 if ((!stepPlot && isNullUndefinedOrNaN(point.y)) ||
597 (stepPlot && !isNaN(prevY) && isNullUndefinedOrNaN(prevY))) {
38e3d209
DV
598 prevX = NaN;
599 continue;
600 }
6a6439da 601
38e3d209
DV
602 if (stepPlot) {
603 newYs = [ point.y_bottom, point.y_top ];
604 prevY = point.y;
605 } else {
606 newYs = [ point.y_bottom, point.y_top ];
607 }
608 newYs[0] = e.plotArea.h * newYs[0] + e.plotArea.y;
609 newYs[1] = e.plotArea.h * newYs[1] + e.plotArea.y;
610 if (!isNaN(prevX)) {
a5701188 611 if (stepPlot) {
38e3d209 612 ctx.moveTo(prevX, prevYs[0]);
82dd90c5 613 ctx.lineTo(point.canvasx, prevYs[0]);
614 ctx.lineTo(point.canvasx, prevYs[1]);
38e3d209 615 } else {
82dd90c5 616 ctx.moveTo(prevX, prevYs[0]);
617 ctx.lineTo(point.canvasx, newYs[0]);
618 ctx.lineTo(point.canvasx, newYs[1]);
6a6439da 619 }
82dd90c5 620 ctx.lineTo(prevX, prevYs[1]);
38e3d209 621 ctx.closePath();
6a6439da 622 }
38e3d209
DV
623 prevYs = newYs;
624 prevX = point.canvasx;
6a6439da 625 }
38e3d209 626 ctx.fill();
42a9ebb8 627};
6a6439da 628
20b87d28
DV
629
630/**
631 * Proxy for CanvasRenderingContext2D which drops moveTo/lineTo calls which are
632 * superfluous. It accumulates all movements which haven't changed the x-value
633 * and only applies the two with the most extreme y-values.
634 *
635 * Calls to lineTo/moveTo must have non-decreasing x-values.
636 */
637DygraphCanvasRenderer._fastCanvasProxy = function(context) {
638 var pendingActions = []; // array of [type, x, y] tuples
639 var lastRoundedX = null;
20b87d28
DV
640
641 var LINE_TO = 1,
642 MOVE_TO = 2;
643
644 var actionCount = 0; // number of moveTos and lineTos passed to context.
645
646 // Drop superfluous motions
647 // Assumes all pendingActions have the same (rounded) x-value.
648 var compressActions = function(opt_losslessOnly) {
649 if (pendingActions.length <= 1) return;
650
651 // Lossless compression: drop inconsequential moveTos.
652 for (var i = pendingActions.length - 1; i > 0; i--) {
653 var action = pendingActions[i];
654 if (action[0] == MOVE_TO) {
655 var prevAction = pendingActions[i - 1];
656 if (prevAction[1] == action[1] && prevAction[2] == action[2]) {
657 pendingActions.splice(i, 1);
658 }
659 }
660 }
661
662 // Lossless compression: ... drop consecutive moveTos ...
663 for (var i = 0; i < pendingActions.length - 1; /* incremented internally */) {
664 var action = pendingActions[i];
665 if (action[0] == MOVE_TO && pendingActions[i + 1][0] == MOVE_TO) {
666 pendingActions.splice(i, 1);
667 } else {
668 i++;
669 }
670 }
671
672 // Lossy compression: ... drop all but the extreme y-values ...
673 if (pendingActions.length > 2 && !opt_losslessOnly) {
674 // keep an initial moveTo, but drop all others.
675 var startIdx = 0;
676 if (pendingActions[0][0] == MOVE_TO) startIdx++;
677 var minIdx = null, maxIdx = null;
678 for (var i = startIdx; i < pendingActions.length; i++) {
679 var action = pendingActions[i];
680 if (action[0] != LINE_TO) continue;
681 if (minIdx === null && maxIdx === null) {
682 minIdx = i;
683 maxIdx = i;
684 } else {
685 var y = action[2];
686 if (y < pendingActions[minIdx][2]) {
687 minIdx = i;
688 } else if (y > pendingActions[maxIdx][2]) {
689 maxIdx = i;
690 }
691 }
692 }
693 var minAction = pendingActions[minIdx],
694 maxAction = pendingActions[maxIdx];
695 pendingActions.splice(startIdx, pendingActions.length - startIdx);
696 if (minIdx < maxIdx) {
697 pendingActions.push(minAction);
698 pendingActions.push(maxAction);
699 } else if (minIdx > maxIdx) {
700 pendingActions.push(maxAction);
701 pendingActions.push(minAction);
702 } else {
703 pendingActions.push(minAction);
704 }
705 }
706 };
707
708 var flushActions = function(opt_noLossyCompression) {
709 compressActions(opt_noLossyCompression);
710 for (var i = 0, len = pendingActions.length; i < len; i++) {
711 var action = pendingActions[i];
712 if (action[0] == LINE_TO) {
713 context.lineTo(action[1], action[2]);
714 } else if (action[0] == MOVE_TO) {
715 context.moveTo(action[1], action[2]);
716 }
717 }
718 actionCount += pendingActions.length;
719 pendingActions = [];
720 };
721
722 var addAction = function(action, x, y) {
723 var rx = Math.round(x);
724 if (lastRoundedX === null || rx != lastRoundedX) {
725 flushActions();
726 lastRoundedX = rx;
727 }
728 pendingActions.push([action, x, y]);
729 };
730
731 return {
732 moveTo: function(x, y) {
733 addAction(MOVE_TO, x, y);
734 },
735 lineTo: function(x, y) {
736 addAction(LINE_TO, x, y);
737 },
738
739 // for major operations like stroke/fill, we skip compression to ensure
740 // that there are no artifacts at the right edge.
741 stroke: function() { flushActions(true); context.stroke(); },
742 fill: function() { flushActions(true); context.fill(); },
743 beginPath: function() { flushActions(true); context.beginPath(); },
744 closePath: function() { flushActions(true); context.closePath(); },
745
746 _count: function() { return actionCount; }
747 };
46fd9089 748};
20b87d28 749
79253bd0 750/**
01a14b85
DV
751 * Draws the shaded regions when "fillGraph" is set. Not to be confused with
752 * error bars.
753 *
38e3d209
DV
754 * For stacked charts, it's more convenient to handle all the series
755 * simultaneously. So this plotter plots all the points on the first series
756 * it's asked to draw, then ignores all the other series.
757 *
01a14b85
DV
758 * @private
759 */
38e3d209 760DygraphCanvasRenderer._fillPlotter = function(e) {
3c080cd0
KW
761 // Skip if we're drawing a single series for interactive highlight overlay.
762 if (e.singleSeriesName) return;
763
38e3d209
DV
764 // We'll handle all the series at once, not one-by-one.
765 if (e.seriesIndex !== 0) return;
766
e2d8db3a 767 var g = e.dygraph;
38e3d209 768 var setNames = g.getLabels().slice(1); // remove x-axis
e2d8db3a 769
38e3d209
DV
770 // getLabels() includes names for invisible series, which are not included in
771 // allSeriesPoints. We remove those to make the two match.
772 // TODO(danvk): provide a simpler way to get this information.
773 for (var i = setNames.length; i >= 0; i--) {
774 if (!g.visibility()[i]) setNames.splice(i, 1);
775 }
776
e2d8db3a
DV
777 var anySeriesFilled = (function() {
778 for (var i = 0; i < setNames.length; i++) {
0e85a437 779 if (g.getBooleanOption("fillGraph", setNames[i])) return true;
e2d8db3a
DV
780 }
781 return false;
782 })();
783
784 if (!anySeriesFilled) return;
785
e2d8db3a
DV
786 var area = e.plotArea;
787 var sets = e.allSeriesPoints;
788 var setCount = sets.length;
789
0e85a437
DV
790 var fillAlpha = g.getNumericOption('fillAlpha');
791 var stackedGraph = g.getBooleanOption("stackedGraph");
38e3d209 792 var colors = g.getColors();
01a14b85 793
30a5cfc6
KW
794 // For stacked graphs, track the baseline for filling.
795 //
796 // The filled areas below graph lines are trapezoids with two
797 // vertical edges. The top edge is the line segment being drawn, and
798 // the baseline is the bottom edge. Each baseline corresponds to the
799 // top line segment from the previous stacked line. In the case of
800 // step plots, the trapezoids are rectangles.
801 var baseline = {};
01a14b85 802 var currBaseline;
104d87c5 803 var prevStepPlot; // for different line drawing modes (line/step) per series
01a14b85 804
46fd9089
DV
805 // Helper function to trace a line back along the baseline.
806 var traceBackPath = function(ctx, baselineX, baselineY, pathBack) {
807 ctx.lineTo(baselineX, baselineY);
808 if (stackedGraph) {
809 for (var i = pathBack.length - 1; i >= 0; i--) {
810 var pt = pathBack[i];
811 ctx.lineTo(pt[0], pt[1]);
812 }
813 }
814 };
815
01a14b85 816 // process sets in reverse order (needed for stacked graphs)
9e85a8f4 817 for (var setIdx = setCount - 1; setIdx >= 0; setIdx--) {
20b87d28 818 var ctx = e.drawingContext;
9e85a8f4 819 var setName = setNames[setIdx];
0e85a437 820 if (!g.getBooleanOption('fillGraph', setName)) continue;
20b87d28 821
0e85a437 822 var stepPlot = g.getBooleanOption('stepPlot', setName);
38e3d209
DV
823 var color = colors[setIdx];
824 var axis = g.axisPropertiesForSeries(setName);
01a14b85
DV
825 var axisY = 1.0 + axis.minyval * axis.yscale;
826 if (axisY < 0.0) axisY = 0.0;
827 else if (axisY > 1.0) axisY = 1.0;
38e3d209 828 axisY = area.h * axisY + area.y;
01a14b85 829
38e3d209 830 var points = sets[setIdx];
9e85a8f4 831 var iter = Dygraph.createIterator(points, 0, points.length,
01a14b85 832 DygraphCanvasRenderer._getIteratorPredicate(
0e85a437 833 g.getBooleanOption("connectSeparatedPoints", setName)));
01a14b85
DV
834
835 // setup graphics context
836 var prevX = NaN;
837 var prevYs = [-1, -1];
838 var newYs;
01a14b85 839 // should be same color as the lines but only 15% opaque.
464b5f50 840 var rgb = Dygraph.toRGB_(color);
01a14b85
DV
841 var err_color =
842 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + fillAlpha + ')';
843 ctx.fillStyle = err_color;
844 ctx.beginPath();
12b879f4 845 var last_x, is_first = true;
20b87d28
DV
846
847 // If the point density is high enough, dropping segments on their way to
848 // the canvas justifies the overhead of doing so.
849 if (points.length > 2 * g.width_) {
850 ctx = DygraphCanvasRenderer._fastCanvasProxy(ctx);
851 }
852
853 // For filled charts, we draw points from left to right, then back along
854 // the x-axis to complete a shape for filling.
855 // For stacked plots, this "back path" is a more complex shape. This array
856 // stores the [x, y] values needed to trace that shape.
857 var pathBack = [];
858
20b87d28
DV
859 // TODO(danvk): there are a lot of options at play in this loop.
860 // The logic would be much clearer if some (e.g. stackGraph and
861 // stepPlot) were split off into separate sub-plotters.
46fd9089 862 var point;
12b879f4 863 while (iter.hasNext) {
46fd9089 864 point = iter.next();
8c31c7db 865 if (!Dygraph.isOK(point.y) && !stepPlot) {
46fd9089
DV
866 traceBackPath(ctx, prevX, prevYs[1], pathBack);
867 pathBack = [];
16febe6b 868 prevX = NaN;
30a5cfc6
KW
869 if (point.y_stacked !== null && !isNaN(point.y_stacked)) {
870 baseline[point.canvasx] = area.h * point.y_stacked + area.y;
871 }
16febe6b
DV
872 continue;
873 }
874 if (stackedGraph) {
12b879f4
DV
875 if (!is_first && last_x == point.xval) {
876 continue;
877 } else {
878 is_first = false;
879 last_x = point.xval;
880 }
881
16febe6b
DV
882 currBaseline = baseline[point.canvasx];
883 var lastY;
884 if (currBaseline === undefined) {
885 lastY = axisY;
886 } else {
104d87c5 887 if(prevStepPlot) {
16febe6b 888 lastY = currBaseline[0];
01a14b85 889 } else {
16febe6b 890 lastY = currBaseline;
01a14b85 891 }
16febe6b
DV
892 }
893 newYs = [ point.canvasy, lastY ];
01a14b85 894
20b87d28 895 if (stepPlot) {
16febe6b
DV
896 // Step plots must keep track of the top and bottom of
897 // the baseline at each point.
20b87d28 898 if (prevYs[0] === -1) {
16febe6b 899 baseline[point.canvasx] = [ point.canvasy, axisY ];
01a14b85 900 } else {
16febe6b 901 baseline[point.canvasx] = [ point.canvasy, prevYs[0] ];
01a14b85 902 }
01a14b85 903 } else {
16febe6b 904 baseline[point.canvasx] = point.canvasy;
01a14b85 905 }
01a14b85 906
16febe6b 907 } else {
8c31c7db 908 if (isNaN(point.canvasy) && stepPlot) {
e988d192 909 newYs = [ area.y + area.h, axisY ];
8c31c7db 910 } else {
e988d192
BB
911 newYs = [ point.canvasy, axisY ];
912 }
16febe6b
DV
913 }
914 if (!isNaN(prevX)) {
104d87c5 915 // Move to top fill point
16febe6b
DV
916 if (stepPlot) {
917 ctx.lineTo(point.canvasx, prevYs[0]);
16febe6b 918 ctx.lineTo(point.canvasx, newYs[0]);
104d87c5 919 } else {
20b87d28 920 ctx.lineTo(point.canvasx, newYs[0]);
01a14b85 921 }
16febe6b 922
20b87d28
DV
923 // Record the baseline for the reverse path.
924 if (stackedGraph) {
925 pathBack.push([prevX, prevYs[1]]);
926 if (prevStepPlot && currBaseline) {
927 // Draw to the bottom of the baseline
928 pathBack.push([point.canvasx, currBaseline[1]]);
929 } else {
930 pathBack.push([point.canvasx, newYs[1]]);
931 }
932 }
933 } else {
934 ctx.moveTo(point.canvasx, newYs[1]);
935 ctx.lineTo(point.canvasx, newYs[0]);
01a14b85 936 }
16febe6b
DV
937 prevYs = newYs;
938 prevX = point.canvasx;
01a14b85 939 }
104d87c5 940 prevStepPlot = stepPlot;
46fd9089
DV
941 if (newYs && point) {
942 traceBackPath(ctx, point.canvasx, newYs[1], pathBack);
943 pathBack = [];
20b87d28 944 }
01a14b85
DV
945 ctx.fill();
946 }
947};
3ce712e6
DV
948
949return DygraphCanvasRenderer;
950
951})();