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