3 * Copyright 2006 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
8 * @fileoverview Based on PlotKit.CanvasRenderer, but modified to meet the
11 * In particular, support for:
14 * - dygraphs attribute system
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.
27 var DygraphCanvasRenderer
= (function() {
28 /*global Dygraph:false */
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.
39 * The chart canvas has already been created by the Dygraph object. The
40 * renderer simply gets a drawing context.
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.
47 * TODO(danvk): remove the elementContext property.
49 var DygraphCanvasRenderer
= function(dygraph
, element
, elementContext
, layout
) {
50 this.dygraph_
= dygraph
;
53 this.element
= element
;
54 this.elementContext
= elementContext
;
56 this.height
= dygraph
.height_
;
57 this.width
= dygraph
.width_
;
59 // --- check whether everything is ok before we return
60 // NOTE(konigsberg): isIE is never defined in this object. Bug of some sort.
61 if (!this.isIE
&& !(Dygraph
.isCanvasSupported(this.element
)))
62 throw "Canvas is not supported.";
65 this.area
= layout
.getPlotArea();
67 // Set up a clipping area for the canvas (and the interaction canvas).
68 // This ensures that we don't overdraw.
69 if (this.dygraph_
.isUsingExcanvas_
) {
70 this._createIEClipArea();
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_
;
77 ctx
.rect(this.area
.x
, this.area
.y
, this.area
.w
, this.area
.h
);
80 ctx
= this.dygraph_
.hidden_ctx_
;
82 ctx
.rect(this.area
.x
, this.area
.y
, this.area
.w
, this.area
.h
);
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.
94 DygraphCanvasRenderer
.prototype.clear
= function() {
97 // VML takes a while to start up, so we just poll every this.IEDelay
99 if (this.clearDelay
) {
100 this.clearDelay
.cancel();
101 this.clearDelay
= null;
103 context
= this.elementContext
;
106 // TODO(danvk): this is broken, since MochiKit.Async is gone.
107 // this.clearDelay = MochiKit.Async.wait(this.IEDelay);
108 // this.clearDelay.addCallback(bind(this.clear, this));
113 context
= this.elementContext
;
114 context
.clearRect(0, 0, this.width
, this.height
);
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
124 DygraphCanvasRenderer
.prototype.render
= function() {
125 // attaches point.canvas{x,y}
126 this._updatePoints();
128 // actually draws the chart.
129 this._renderLineChart();
132 DygraphCanvasRenderer
.prototype._createIEClipArea
= function() {
133 var className
= 'dygraph-clip-div';
134 var graphDiv
= this.dygraph_
.graphDiv
;
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
]);
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
;
152 element
= element
.parentNode
;
155 function createClipDiv(area
) {
156 if (area
.w
=== 0 || area
.h
=== 0) {
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
);
170 var plotArea
= this.area
;
181 w
: this.width
- plotArea
.x
,
187 x
: plotArea
.x
+ plotArea
.w
, y
: 0,
188 w
: this.width
- plotArea
.x
- plotArea
.w
,
195 y
: plotArea
.y
+ plotArea
.h
,
196 w
: this.width
- plotArea
.x
,
197 h
: this.height
- plotArea
.h
- plotArea
.y
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.
208 DygraphCanvasRenderer
._getIteratorPredicate
= function(connectSeparatedPoints
) {
209 return connectSeparatedPoints
?
210 DygraphCanvasRenderer
._predicateThatSkipsEmptyPoints
:
214 DygraphCanvasRenderer
._predicateThatSkipsEmptyPoints
=
215 function(array
, idx
) {
216 return array
[idx
].yval
!== null;
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.
224 DygraphCanvasRenderer
._drawStyledLine
= function(e
,
225 color
, strokeWidth
, strokePattern
, drawPoints
,
226 drawPointCallback
, pointSize
) {
228 // TODO(konigsberg): Compute attributes outside this method call.
229 var stepPlot
= g
.getBooleanOption("stepPlot", e
.setName
);
231 if (!Dygraph
.isArrayLike(strokePattern
)) {
232 strokePattern
= null;
235 var drawGapPoints
= g
.getBooleanOption('drawGapEdgePoints', e
.setName
);
237 var points
= e
.points
;
238 var setName
= e
.setName
;
239 var iter
= Dygraph
.createIterator(points
, 0, points
.length
,
240 DygraphCanvasRenderer
._getIteratorPredicate(
241 g
.getBooleanOption("connectSeparatedPoints", setName
)));
243 var stroking
= strokePattern
&& (strokePattern
.length
>= 2);
245 var ctx
= e
.drawingContext
;
248 ctx
.installPattern(strokePattern
);
251 var pointsOnLine
= DygraphCanvasRenderer
._drawSeries(
252 e
, iter
, strokeWidth
, pointSize
, drawPoints
, drawGapPoints
, stepPlot
, color
);
253 DygraphCanvasRenderer
._drawPointsOnLine(
254 e
, pointsOnLine
, drawPointCallback
, color
, pointSize
);
257 ctx
.uninstallPattern();
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.
271 DygraphCanvasRenderer
._drawSeries
= function(e
,
272 iter
, strokeWidth
, pointSize
, drawPoints
, drawGapPoints
, stepPlot
, color
) {
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
279 var pointsOnLine
= []; // Array of [canvasx, canvasy] pairs.
280 var first
= true; // the first cycle through the while loop
282 var ctx
= e
.drawingContext
;
284 ctx
.strokeStyle
= color
;
285 ctx
.lineWidth
= strokeWidth
;
287 // NOTE: we break the iterator's encapsulation here for about a 25% speedup.
288 var arr
= iter
.array_
;
289 var limit
= iter
.end_
;
290 var predicate
= iter
.predicate_
;
292 for (var i
= iter
.start_
; i
< limit
; i
++) {
295 while (i
< limit
&& !predicate(arr
, i
)) {
298 if (i
== limit
) break;
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?
305 if (point
.canvasy
=== null || point
.canvasy
!= point
.canvasy
) {
306 if (stepPlot
&& prevCanvasX
!== null) {
307 // Draw a horizontal line to the start of the missing data
308 ctx
.moveTo(prevCanvasX
, prevCanvasY
);
309 ctx
.lineTo(point
.canvasx
, prevCanvasY
);
311 prevCanvasX
= prevCanvasY
= null;
314 if (drawGapPoints
|| !prevCanvasX
) {
317 nextCanvasY
= iter
.hasNext
? iter
.peek
.canvasy
: null;
319 var isNextCanvasYNullOrNaN
= nextCanvasY
=== null ||
320 nextCanvasY
!= nextCanvasY
;
321 isIsolated
= (!prevCanvasX
&& isNextCanvasYNullOrNaN
);
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
)) {
332 if (prevCanvasX
!== null) {
335 ctx
.moveTo(prevCanvasX
, prevCanvasY
);
336 ctx
.lineTo(point
.canvasx
, prevCanvasY
);
339 ctx
.lineTo(point
.canvasx
, point
.canvasy
);
342 ctx
.moveTo(point
.canvasx
, point
.canvasy
);
344 if (drawPoints
|| isIsolated
) {
345 pointsOnLine
.push([point
.canvasx
, point
.canvasy
, point
.idx
]);
347 prevCanvasX
= point
.canvasx
;
348 prevCanvasY
= point
.canvasy
;
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.
363 DygraphCanvasRenderer
._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
];
369 drawPointCallback
.call(e
.dygraph
,
370 e
.dygraph
, e
.setName
, ctx
, cb
[0], cb
[1], color
, pointSize
, cb
[2]);
376 * Attaches canvas coordinates to the points array.
379 DygraphCanvasRenderer
.prototype._updatePoints
= function() {
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
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%.
392 var sets
= this.layout
.points
;
393 for (var i
= sets
.length
; i
--;) {
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
;
404 * Add canvas Actually draw the lines chart, including error bars.
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.
410 * @param {string=} opt_seriesName when specified, only that series will
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
417 DygraphCanvasRenderer
.prototype._renderLineChart
= function(opt_seriesName
, opt_ctx
) {
418 var ctx
= opt_ctx
|| this.elementContext
;
421 var sets
= this.layout
.points
;
422 var setNames
= this.layout
.setNames
;
425 this.colors
= this.dygraph_
.colorsMap_
;
427 // Determine which series have specialized plotters.
428 var plotter_attr
= this.dygraph_
.getOption("plotter");
429 var plotters
= plotter_attr
;
430 if (!Dygraph
.isArrayLike(plotters
)) {
431 plotters
= [plotters
];
434 var setPlotters
= {}; // series name -> plotter fn.
435 for (i
= 0; i
< setNames
.length
; i
++) {
436 setName
= setNames
[i
];
437 var setPlotter
= this.dygraph_
.getOption("plotter", setName
);
438 if (setPlotter
== plotter_attr
) continue; // not specialized.
440 setPlotters
[setName
] = setPlotter
;
443 for (i
= 0; i
< plotters
.length
; i
++) {
444 var plotter
= plotters
[i
];
445 var is_last
= (i
== plotters
.length
- 1);
447 for (var j
= 0; j
< sets
.length
; j
++) {
448 setName
= setNames
[j
];
449 if (opt_seriesName
&& setName
!= opt_seriesName
) continue;
451 var points
= sets
[j
];
453 // Only throw in the specialized plotters on the last iteration.
455 if (setName
in setPlotters
) {
457 p
= setPlotters
[setName
];
459 // Don't use the standard plotters in this case.
464 var color
= this.colors
[setName
];
465 var strokeWidth
= this.dygraph_
.getOption("strokeWidth", setName
);
468 ctx
.strokeStyle
= color
;
469 ctx
.lineWidth
= strokeWidth
;
475 strokeWidth
: strokeWidth
,
476 dygraph
: this.dygraph_
,
477 axis
: this.dygraph_
.axisPropertiesForSeries(setName
),
480 seriesCount
: sets
.length
,
481 singleSeriesName
: opt_seriesName
,
482 allSeriesPoints
: sets
490 * Standard plotters. These may be used by clients via Dygraph.Plotters.
491 * See comments there for more details.
493 DygraphCanvasRenderer
._Plotters
= {
494 linePlotter
: function(e
) {
495 DygraphCanvasRenderer
._linePlotter(e
);
498 fillPlotter
: function(e
) {
499 DygraphCanvasRenderer
._fillPlotter(e
);
502 errorPlotter
: function(e
) {
503 DygraphCanvasRenderer
._errorPlotter(e
);
508 * Plotter which draws the central lines for a series.
511 DygraphCanvasRenderer
._linePlotter
= function(e
) {
513 var setName
= e
.setName
;
514 var strokeWidth
= e
.strokeWidth
;
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.
519 var borderWidth
= g
.getNumericOption("strokeBorderWidth", setName
);
520 var drawPointCallback
= g
.getOption("drawPointCallback", setName
) ||
521 Dygraph
.Circles
.DEFAULT
;
522 var strokePattern
= g
.getOption("strokePattern", setName
);
523 var drawPoints
= g
.getBooleanOption("drawPoints", setName
);
524 var pointSize
= g
.getNumericOption("pointSize", setName
);
526 if (borderWidth
&& strokeWidth
) {
527 DygraphCanvasRenderer
._drawStyledLine(e
,
528 g
.getOption("strokeBorderColor", setName
),
529 strokeWidth
+ 2 * borderWidth
,
537 DygraphCanvasRenderer
._drawStyledLine(e
,
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.
553 DygraphCanvasRenderer
._errorPlotter
= function(e
) {
555 var setName
= e
.setName
;
556 var errorBars
= g
.getBooleanOption("errorBars") ||
557 g
.getBooleanOption("customBars");
558 if (!errorBars
) return;
560 var fillGraph
= g
.getBooleanOption("fillGraph", setName
);
562 console
.warn("Can't use fillGraph option with error bars");
565 var ctx
= e
.drawingContext
;
567 var fillAlpha
= g
.getNumericOption('fillAlpha', setName
);
568 var stepPlot
= g
.getBooleanOption("stepPlot", setName
);
569 var points
= e
.points
;
571 var iter
= Dygraph
.createIterator(points
, 0, points
.length
,
572 DygraphCanvasRenderer
._getIteratorPredicate(
573 g
.getBooleanOption("connectSeparatedPoints", setName
)));
577 // setup graphics context
580 var prevYs
= [-1, -1];
581 // should be same color as the lines but only 15% opaque.
582 var rgb
= Dygraph
.toRGB_(color
);
584 'rgba(' + rgb
.r
+ ',' + rgb
.g
+ ',' + rgb
.b
+ ',' + fillAlpha
+ ')';
585 ctx
.fillStyle
= err_color
;
588 var isNullUndefinedOrNaN
= function(x
) {
589 return (x
=== null ||
594 while (iter
.hasNext
) {
595 var point
= iter
.next();
596 if ((!stepPlot
&& isNullUndefinedOrNaN(point
.y
)) ||
597 (stepPlot
&& !isNaN(prevY
) && isNullUndefinedOrNaN(prevY
))) {
602 newYs
= [ point
.y_bottom
, point
.y_top
];
607 // The documentation specifically disallows nulls inside the point arrays,
608 // but in case it happens we should do something sensible.
609 if (isNaN(newYs
[0])) newYs
[0] = point
.y
;
610 if (isNaN(newYs
[1])) newYs
[1] = point
.y
;
612 newYs
[0] = e
.plotArea
.h
* newYs
[0] + e
.plotArea
.y
;
613 newYs
[1] = e
.plotArea
.h
* newYs
[1] + e
.plotArea
.y
;
616 ctx
.moveTo(prevX
, prevYs
[0]);
617 ctx
.lineTo(point
.canvasx
, prevYs
[0]);
618 ctx
.lineTo(point
.canvasx
, prevYs
[1]);
620 ctx
.moveTo(prevX
, prevYs
[0]);
621 ctx
.lineTo(point
.canvasx
, newYs
[0]);
622 ctx
.lineTo(point
.canvasx
, newYs
[1]);
624 ctx
.lineTo(prevX
, prevYs
[1]);
628 prevX
= point
.canvasx
;
635 * Proxy for CanvasRenderingContext2D which drops moveTo/lineTo calls which are
636 * superfluous. It accumulates all movements which haven't changed the x-value
637 * and only applies the two with the most extreme y-values.
639 * Calls to lineTo/moveTo must have non-decreasing x-values.
641 DygraphCanvasRenderer
._fastCanvasProxy
= function(context
) {
642 var pendingActions
= []; // array of [type, x, y] tuples
643 var lastRoundedX
= null;
648 var actionCount
= 0; // number of moveTos and lineTos passed to context.
650 // Drop superfluous motions
651 // Assumes all pendingActions have the same (rounded) x-value.
652 var compressActions
= function(opt_losslessOnly
) {
653 if (pendingActions
.length
<= 1) return;
655 // Lossless compression: drop inconsequential moveTos.
656 for (var i
= pendingActions
.length
- 1; i
> 0; i
--) {
657 var action
= pendingActions
[i
];
658 if (action
[0] == MOVE_TO
) {
659 var prevAction
= pendingActions
[i
- 1];
660 if (prevAction
[1] == action
[1] && prevAction
[2] == action
[2]) {
661 pendingActions
.splice(i
, 1);
666 // Lossless compression: ... drop consecutive moveTos ...
667 for (var i
= 0; i
< pendingActions
.length
- 1; /* incremented internally */) {
668 var action
= pendingActions
[i
];
669 if (action
[0] == MOVE_TO
&& pendingActions
[i
+ 1][0] == MOVE_TO
) {
670 pendingActions
.splice(i
, 1);
676 // Lossy compression: ... drop all but the extreme y-values ...
677 if (pendingActions
.length
> 2 && !opt_losslessOnly
) {
678 // keep an initial moveTo, but drop all others.
680 if (pendingActions
[0][0] == MOVE_TO
) startIdx
++;
681 var minIdx
= null, maxIdx
= null;
682 for (var i
= startIdx
; i
< pendingActions
.length
; i
++) {
683 var action
= pendingActions
[i
];
684 if (action
[0] != LINE_TO
) continue;
685 if (minIdx
=== null && maxIdx
=== null) {
690 if (y
< pendingActions
[minIdx
][2]) {
692 } else if (y
> pendingActions
[maxIdx
][2]) {
697 var minAction
= pendingActions
[minIdx
],
698 maxAction
= pendingActions
[maxIdx
];
699 pendingActions
.splice(startIdx
, pendingActions
.length
- startIdx
);
700 if (minIdx
< maxIdx
) {
701 pendingActions
.push(minAction
);
702 pendingActions
.push(maxAction
);
703 } else if (minIdx
> maxIdx
) {
704 pendingActions
.push(maxAction
);
705 pendingActions
.push(minAction
);
707 pendingActions
.push(minAction
);
712 var flushActions
= function(opt_noLossyCompression
) {
713 compressActions(opt_noLossyCompression
);
714 for (var i
= 0, len
= pendingActions
.length
; i
< len
; i
++) {
715 var action
= pendingActions
[i
];
716 if (action
[0] == LINE_TO
) {
717 context
.lineTo(action
[1], action
[2]);
718 } else if (action
[0] == MOVE_TO
) {
719 context
.moveTo(action
[1], action
[2]);
722 actionCount
+= pendingActions
.length
;
726 var addAction
= function(action
, x
, y
) {
727 var rx
= Math
.round(x
);
728 if (lastRoundedX
=== null || rx
!= lastRoundedX
) {
732 pendingActions
.push([action
, x
, y
]);
736 moveTo
: function(x
, y
) {
737 addAction(MOVE_TO
, x
, y
);
739 lineTo
: function(x
, y
) {
740 addAction(LINE_TO
, x
, y
);
743 // for major operations like stroke/fill
, we skip compression to ensure
744 // that there are no artifacts at the right edge.
745 stroke
: function() { flushActions(true); context
.stroke(); },
746 fill
: function() { flushActions(true); context
.fill(); },
747 beginPath
: function() { flushActions(true); context
.beginPath(); },
748 closePath
: function() { flushActions(true); context
.closePath(); },
750 _count
: function() { return actionCount
; }
755 * Draws the shaded regions when "fillGraph" is set. Not to be confused with
758 * For stacked charts, it's more convenient to handle all the series
759 * simultaneously. So this plotter plots all the points on the first series
760 * it's asked to draw, then ignores all the other series.
764 DygraphCanvasRenderer
._fillPlotter
= function(e
) {
765 // Skip if we're drawing a single series for interactive highlight overlay.
766 if (e
.singleSeriesName
) return;
768 // We'll handle all the series at once, not one-by-one.
769 if (e
.seriesIndex
!== 0) return;
772 var setNames
= g
.getLabels().slice(1); // remove x-axis
774 // getLabels() includes names for invisible series, which are not included in
775 // allSeriesPoints. We remove those to make the two match.
776 // TODO(danvk): provide a simpler way to get this information.
777 for (var i
= setNames
.length
; i
>= 0; i
--) {
778 if (!g
.visibility()[i
]) setNames
.splice(i
, 1);
781 var anySeriesFilled
= (function() {
782 for (var i
= 0; i
< setNames
.length
; i
++) {
783 if (g
.getBooleanOption("fillGraph", setNames
[i
])) return true;
788 if (!anySeriesFilled
) return;
790 var area
= e
.plotArea
;
791 var sets
= e
.allSeriesPoints
;
792 var setCount
= sets
.length
;
794 var fillAlpha
= g
.getNumericOption('fillAlpha');
795 var stackedGraph
= g
.getBooleanOption("stackedGraph");
796 var colors
= g
.getColors();
798 // For stacked graphs, track the baseline for filling.
800 // The filled areas below graph lines are trapezoids with two
801 // vertical edges. The top edge is the line segment being drawn, and
802 // the baseline is the bottom edge. Each baseline corresponds to the
803 // top line segment from the previous stacked line. In the case of
804 // step plots, the trapezoids are rectangles.
807 var prevStepPlot
; // for different line drawing modes (line/step) per series
809 // Helper function to trace a line back along the baseline.
810 var traceBackPath
= function(ctx
, baselineX
, baselineY
, pathBack
) {
811 ctx
.lineTo(baselineX
, baselineY
);
813 for (var i
= pathBack
.length
- 1; i
>= 0; i
--) {
814 var pt
= pathBack
[i
];
815 ctx
.lineTo(pt
[0], pt
[1]);
820 // process sets in reverse order (needed for stacked graphs)
821 for (var setIdx
= setCount
- 1; setIdx
>= 0; setIdx
--) {
822 var ctx
= e
.drawingContext
;
823 var setName
= setNames
[setIdx
];
824 if (!g
.getBooleanOption('fillGraph', setName
)) continue;
826 var stepPlot
= g
.getBooleanOption('stepPlot', setName
);
827 var color
= colors
[setIdx
];
828 var axis
= g
.axisPropertiesForSeries(setName
);
829 var axisY
= 1.0 + axis
.minyval
* axis
.yscale
;
830 if (axisY
< 0.0) axisY
= 0.0;
831 else if (axisY
> 1.0) axisY
= 1.0;
832 axisY
= area
.h
* axisY
+ area
.y
;
834 var points
= sets
[setIdx
];
835 var iter
= Dygraph
.createIterator(points
, 0, points
.length
,
836 DygraphCanvasRenderer
._getIteratorPredicate(
837 g
.getBooleanOption("connectSeparatedPoints", setName
)));
839 // setup graphics context
841 var prevYs
= [-1, -1];
843 // should be same color as the lines but only 15% opaque.
844 var rgb
= Dygraph
.toRGB_(color
);
846 'rgba(' + rgb
.r
+ ',' + rgb
.g
+ ',' + rgb
.b
+ ',' + fillAlpha
+ ')';
847 ctx
.fillStyle
= err_color
;
849 var last_x
, is_first
= true;
851 // If the point density is high enough, dropping segments on their way to
852 // the canvas justifies the overhead of doing so.
853 if (points
.length
> 2 * g
.width_
) {
854 ctx
= DygraphCanvasRenderer
._fastCanvasProxy(ctx
);
857 // For filled charts, we draw points from left to right, then back along
858 // the x-axis to complete a shape for filling.
859 // For stacked plots, this "back path" is a more complex shape. This array
860 // stores the [x, y] values needed to trace that shape.
863 // TODO(danvk): there are a lot of options at play in this loop.
864 // The logic would be much clearer if some (e.g. stackGraph and
865 // stepPlot) were split off into separate sub-plotters.
867 while (iter
.hasNext
) {
869 if (!Dygraph
.isOK(point
.y
) && !stepPlot
) {
870 traceBackPath(ctx
, prevX
, prevYs
[1], pathBack
);
873 if (point
.y_stacked
!== null && !isNaN(point
.y_stacked
)) {
874 baseline
[point
.canvasx
] = area
.h
* point
.y_stacked
+ area
.y
;
879 if (!is_first
&& last_x
== point
.xval
) {
886 currBaseline
= baseline
[point
.canvasx
];
888 if (currBaseline
=== undefined
) {
892 lastY
= currBaseline
[0];
894 lastY
= currBaseline
;
897 newYs
= [ point
.canvasy
, lastY
];
900 // Step plots must keep track of the top and bottom of
901 // the baseline at each point.
902 if (prevYs
[0] === -1) {
903 baseline
[point
.canvasx
] = [ point
.canvasy
, axisY
];
905 baseline
[point
.canvasx
] = [ point
.canvasy
, prevYs
[0] ];
908 baseline
[point
.canvasx
] = point
.canvasy
;
912 if (isNaN(point
.canvasy
) && stepPlot
) {
913 newYs
= [ area
.y
+ area
.h
, axisY
];
915 newYs
= [ point
.canvasy
, axisY
];
919 // Move to top fill point
921 ctx
.lineTo(point
.canvasx
, prevYs
[0]);
922 ctx
.lineTo(point
.canvasx
, newYs
[0]);
924 ctx
.lineTo(point
.canvasx
, newYs
[0]);
927 // Record the baseline for the reverse path.
929 pathBack
.push([prevX
, prevYs
[1]]);
930 if (prevStepPlot
&& currBaseline
) {
931 // Draw to the bottom of the baseline
932 pathBack
.push([point
.canvasx
, currBaseline
[1]]);
934 pathBack
.push([point
.canvasx
, newYs
[1]]);
938 ctx
.moveTo(point
.canvasx
, newYs
[1]);
939 ctx
.lineTo(point
.canvasx
, newYs
[0]);
942 prevX
= point
.canvasx
;
944 prevStepPlot
= stepPlot
;
945 if (newYs
&& point
) {
946 traceBackPath(ctx
, point
.canvasx
, newYs
[1], pathBack
);
953 return DygraphCanvasRenderer
;