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