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 /*jshint globalstrict: true */
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
;
55 this.container
= this.element
.parentNode
;
57 this.height
= this.element
.height
;
58 this.width
= this.element
.width
;
60 // --- check whether everything is ok before we return
61 // NOTE(konigsberg): isIE is never defined in this object. Bug of some sort.
62 if (!this.isIE
&& !(Dygraph
.isCanvasSupported(this.element
)))
63 throw "Canvas is not supported.";
66 this.area
= layout
.getPlotArea();
67 this.container
.style
.position
= "relative";
68 this.container
.style
.width
= this.width
+ "px";
70 // Set up a clipping area for the canvas (and the interaction canvas).
71 // This ensures that we don't overdraw.
72 if (this.dygraph_
.isUsingExcanvas_
) {
73 this._createIEClipArea();
75 // on Android 3 and 4, setting a clipping area on a canvas prevents it from
76 // displaying anything.
77 if (!Dygraph
.isAndroid()) {
78 var ctx
= this.dygraph_
.canvas_ctx_
;
80 ctx
.rect(this.area
.x
, this.area
.y
, this.area
.w
, this.area
.h
);
83 ctx
= this.dygraph_
.hidden_ctx_
;
85 ctx
.rect(this.area
.x
, this.area
.y
, this.area
.w
, this.area
.h
);
92 * Clears out all chart content and DOM elements.
93 * This is called immediately before render() on every frame, including
94 * during zooms and pans.
97 DygraphCanvasRenderer
.prototype.clear
= function() {
100 // VML takes a while to start up, so we just poll every this.IEDelay
102 if (this.clearDelay
) {
103 this.clearDelay
.cancel();
104 this.clearDelay
= null;
106 context
= this.elementContext
;
109 // TODO(danvk): this is broken, since MochiKit.Async is gone.
110 // this.clearDelay = MochiKit.Async.wait(this.IEDelay);
111 // this.clearDelay.addCallback(bind(this.clear, this));
116 context
= this.elementContext
;
117 context
.clearRect(0, 0, this.width
, this.height
);
121 * This method is responsible for drawing everything on the chart, including
122 * lines, error bars, fills and axes.
123 * It is called immediately after clear() on every frame, including during pans
127 DygraphCanvasRenderer
.prototype.render
= function() {
128 // attaches point.canvas{x,y}
129 this._updatePoints();
131 // actually draws the chart.
132 this._renderLineChart();
135 DygraphCanvasRenderer
.prototype._createIEClipArea
= function() {
136 var className
= 'dygraph-clip-div';
137 var graphDiv
= this.dygraph_
.graphDiv
;
139 // Remove old clip divs.
140 for (var i
= graphDiv
.childNodes
.length
-1; i
>= 0; i
--) {
141 if (graphDiv
.childNodes
[i
].className
== className
) {
142 graphDiv
.removeChild(graphDiv
.childNodes
[i
]);
146 // Determine background color to give clip divs.
147 var backgroundColor
= document
.bgColor
;
148 var element
= this.dygraph_
.graphDiv
;
149 while (element
!= document
) {
150 var bgcolor
= element
.currentStyle
.backgroundColor
;
151 if (bgcolor
&& bgcolor
!= 'transparent') {
152 backgroundColor
= bgcolor
;
155 element
= element
.parentNode
;
158 function createClipDiv(area
) {
159 if (area
.w
=== 0 || area
.h
=== 0) {
162 var elem
= document
.createElement('div');
163 elem
.className
= className
;
164 elem
.style
.backgroundColor
= backgroundColor
;
165 elem
.style
.position
= 'absolute';
166 elem
.style
.left
= area
.x
+ 'px';
167 elem
.style
.top
= area
.y
+ 'px';
168 elem
.style
.width
= area
.w
+ 'px';
169 elem
.style
.height
= area
.h
+ 'px';
170 graphDiv
.appendChild(elem
);
173 var plotArea
= this.area
;
184 w
: this.width
- plotArea
.x
,
190 x
: plotArea
.x
+ plotArea
.w
, y
: 0,
191 w
: this.width
-plotArea
.x
- plotArea
.w
,
198 y
: plotArea
.y
+ plotArea
.h
,
199 w
: this.width
- plotArea
.x
,
200 h
: this.height
- plotArea
.h
- plotArea
.y
206 * Returns a predicate to be used with an iterator, which will
207 * iterate over points appropriately, depending on whether
208 * connectSeparatedPoints is true. When it's false, the predicate will
209 * skip over points with missing yVals.
211 DygraphCanvasRenderer
._getIteratorPredicate
= function(connectSeparatedPoints
) {
212 return connectSeparatedPoints
?
213 DygraphCanvasRenderer
._predicateThatSkipsEmptyPoints
:
217 DygraphCanvasRenderer
._predicateThatSkipsEmptyPoints
=
218 function(array
, idx
) {
219 return array
[idx
].yval
!== null;
223 * Draws a line with the styles passed in and calls all the drawPointCallbacks.
224 * @param {Object} e The dictionary passed to the plotter function.
227 DygraphCanvasRenderer
._drawStyledLine
= function(e
,
228 color
, strokeWidth
, strokePattern
, drawPoints
,
229 drawPointCallback
, pointSize
) {
231 // TODO(konigsberg): Compute attributes outside this method call.
232 var stepPlot
= g
.getBooleanOption("stepPlot", e
.setName
);
234 if (!Dygraph
.isArrayLike(strokePattern
)) {
235 strokePattern
= null;
238 var drawGapPoints
= g
.getBooleanOption('drawGapEdgePoints', e
.setName
);
240 var points
= e
.points
;
241 var setName
= e
.setName
;
242 var iter
= Dygraph
.createIterator(points
, 0, points
.length
,
243 DygraphCanvasRenderer
._getIteratorPredicate(
244 g
.getBooleanOption("connectSeparatedPoints", setName
)));
246 var stroking
= strokePattern
&& (strokePattern
.length
>= 2);
248 var ctx
= e
.drawingContext
;
251 ctx
.installPattern(strokePattern
);
254 var pointsOnLine
= DygraphCanvasRenderer
._drawSeries(
255 e
, iter
, strokeWidth
, pointSize
, drawPoints
, drawGapPoints
, stepPlot
, color
);
256 DygraphCanvasRenderer
._drawPointsOnLine(
257 e
, pointsOnLine
, drawPointCallback
, color
, pointSize
);
260 ctx
.uninstallPattern();
267 * This does the actual drawing of lines on the canvas, for just one series.
268 * Returns a list of [canvasx, canvasy] pairs for points for which a
269 * drawPointCallback should be fired. These include isolated points, or all
270 * points if drawPoints=true.
271 * @param {Object} e The dictionary passed to the plotter function.
274 DygraphCanvasRenderer
._drawSeries
= function(e
,
275 iter
, strokeWidth
, pointSize
, drawPoints
, drawGapPoints
, stepPlot
, color
) {
277 var prevCanvasX
= null;
278 var prevCanvasY
= null;
279 var nextCanvasY
= null;
280 var isIsolated
; // true if this point is isolated (no line segments)
281 var point
; // the point being processed in the while loop
282 var pointsOnLine
= []; // Array of [canvasx, canvasy] pairs.
283 var first
= true; // the first cycle through the while loop
285 var ctx
= e
.drawingContext
;
287 ctx
.strokeStyle
= color
;
288 ctx
.lineWidth
= strokeWidth
;
290 // NOTE: we break the iterator's encapsulation here for about a 25% speedup.
291 var arr
= iter
.array_
;
292 var limit
= iter
.end_
;
293 var predicate
= iter
.predicate_
;
295 for (var i
= iter
.start_
; i
< limit
; i
++) {
298 while (i
< limit
&& !predicate(arr
, i
)) {
301 if (i
== limit
) break;
305 // FIXME: The 'canvasy != canvasy' test here catches NaN values but the test
306 // doesn't catch Infinity values. Could change this to
307 // !isFinite(point.canvasy), but I assume it avoids isNaN for performance?
308 if (point
.canvasy
=== null || point
.canvasy
!= point
.canvasy
) {
309 if (stepPlot
&& prevCanvasX
!== null) {
310 // Draw a horizontal line to the start of the missing data
311 ctx
.moveTo(prevCanvasX
, prevCanvasY
);
312 ctx
.lineTo(point
.canvasx
, prevCanvasY
);
314 prevCanvasX
= prevCanvasY
= null;
317 if (drawGapPoints
|| !prevCanvasX
) {
320 nextCanvasY
= iter
.hasNext
? iter
.peek
.canvasy
: null;
322 var isNextCanvasYNullOrNaN
= nextCanvasY
=== null ||
323 nextCanvasY
!= nextCanvasY
;
324 isIsolated
= (!prevCanvasX
&& isNextCanvasYNullOrNaN
);
326 // Also consider a point to be "isolated" if it's adjacent to a
327 // null point, excluding the graph edges.
328 if ((!first
&& !prevCanvasX
) ||
329 (iter
.hasNext
&& isNextCanvasYNullOrNaN
)) {
335 if (prevCanvasX
!== null) {
338 ctx
.moveTo(prevCanvasX
, prevCanvasY
);
339 ctx
.lineTo(point
.canvasx
, prevCanvasY
);
342 ctx
.lineTo(point
.canvasx
, point
.canvasy
);
345 ctx
.moveTo(point
.canvasx
, point
.canvasy
);
347 if (drawPoints
|| isIsolated
) {
348 pointsOnLine
.push([point
.canvasx
, point
.canvasy
, point
.idx
]);
350 prevCanvasX
= point
.canvasx
;
351 prevCanvasY
= point
.canvasy
;
360 * This fires the drawPointCallback functions, which draw dots on the points by
361 * default. This gets used when the "drawPoints" option is set, or when there
362 * are isolated points.
363 * @param {Object} e The dictionary passed to the plotter function.
366 DygraphCanvasRenderer
._drawPointsOnLine
= function(
367 e
, pointsOnLine
, drawPointCallback
, color
, pointSize
) {
368 var ctx
= e
.drawingContext
;
369 for (var idx
= 0; idx
< pointsOnLine
.length
; idx
++) {
370 var cb
= pointsOnLine
[idx
];
373 e
.dygraph
, e
.setName
, ctx
, cb
[0], cb
[1], color
, pointSize
, cb
[2]);
379 * Attaches canvas coordinates to the points array.
382 DygraphCanvasRenderer
.prototype._updatePoints
= function() {
386 // TODO(bhs): this loop is a hot-spot for high-point-count charts. These
387 // transformations can be pushed into the canvas via linear transformation
389 // NOTE(danvk): this is trickier than it sounds at first. The transformation
390 // needs to be done before the .moveTo() and .lineTo() calls, but must be
391 // undone before the .stroke() call to ensure that the stroke width is
392 // unaffected. An alternative is to reduce the stroke width in the
393 // transformed coordinate space, but you can't specify different values for
394 // each dimension (as you can with .scale()). The speedup here is ~12%.
395 var sets
= this.layout
.points
;
396 for (var i
= sets
.length
; i
--;) {
397 var points
= sets
[i
];
398 for (var j
= points
.length
; j
--;) {
399 var point
= points
[j
];
400 point
.canvasx
= this.area
.w
* point
.x
+ this.area
.x
;
401 point
.canvasy
= this.area
.h
* point
.y
+ this.area
.y
;
407 * Add canvas Actually draw the lines chart, including error bars.
409 * This function can only be called if DygraphLayout's points array has been
410 * updated with canvas{x,y} attributes, i.e. by
411 * DygraphCanvasRenderer._updatePoints.
413 * @param {string=} opt_seriesName when specified, only that series will
414 * be drawn. (This is used for expedited redrawing with highlightSeriesOpts)
415 * @param {CanvasRenderingContext2D} opt_ctx when specified, the drawing
416 * context. However, lines are typically drawn on the object's
420 DygraphCanvasRenderer
.prototype._renderLineChart
= function(opt_seriesName
, opt_ctx
) {
421 var ctx
= opt_ctx
|| this.elementContext
;
424 var sets
= this.layout
.points
;
425 var setNames
= this.layout
.setNames
;
428 this.colors
= this.dygraph_
.colorsMap_
;
430 // Determine which series have specialized plotters.
431 var plotter_attr
= this.dygraph_
.getOption("plotter");
432 var plotters
= plotter_attr
;
433 if (!Dygraph
.isArrayLike(plotters
)) {
434 plotters
= [plotters
];
437 var setPlotters
= {}; // series name -> plotter fn.
438 for (i
= 0; i
< setNames
.length
; i
++) {
439 setName
= setNames
[i
];
440 var setPlotter
= this.dygraph_
.getOption("plotter", setName
);
441 if (setPlotter
== plotter_attr
) continue; // not specialized.
443 setPlotters
[setName
] = setPlotter
;
446 for (i
= 0; i
< plotters
.length
; i
++) {
447 var plotter
= plotters
[i
];
448 var is_last
= (i
== plotters
.length
- 1);
450 for (var j
= 0; j
< sets
.length
; j
++) {
451 setName
= setNames
[j
];
452 if (opt_seriesName
&& setName
!= opt_seriesName
) continue;
454 var points
= sets
[j
];
456 // Only throw in the specialized plotters on the last iteration.
458 if (setName
in setPlotters
) {
460 p
= setPlotters
[setName
];
462 // Don't use the standard plotters in this case.
467 var color
= this.colors
[setName
];
468 var strokeWidth
= this.dygraph_
.getOption("strokeWidth", setName
);
471 ctx
.strokeStyle
= color
;
472 ctx
.lineWidth
= strokeWidth
;
478 strokeWidth
: strokeWidth
,
479 dygraph
: this.dygraph_
,
480 axis
: this.dygraph_
.axisPropertiesForSeries(setName
),
483 seriesCount
: sets
.length
,
484 singleSeriesName
: opt_seriesName
,
485 allSeriesPoints
: sets
493 * Standard plotters. These may be used by clients via Dygraph.Plotters.
494 * See comments there for more details.
496 DygraphCanvasRenderer
._Plotters
= {
497 linePlotter
: function(e
) {
498 DygraphCanvasRenderer
._linePlotter(e
);
501 fillPlotter
: function(e
) {
502 DygraphCanvasRenderer
._fillPlotter(e
);
505 errorPlotter
: function(e
) {
506 DygraphCanvasRenderer
._errorPlotter(e
);
511 * Plotter which draws the central lines for a series.
514 DygraphCanvasRenderer
._linePlotter
= function(e
) {
516 var setName
= e
.setName
;
517 var strokeWidth
= e
.strokeWidth
;
519 // TODO(danvk): Check if there's any performance impact of just calling
520 // getOption() inside of _drawStyledLine. Passing in so many parameters makes
521 // this code a bit nasty.
522 var borderWidth
= g
.getNumericOption("strokeBorderWidth", setName
);
523 var drawPointCallback
= g
.getOption("drawPointCallback", setName
) ||
524 Dygraph
.Circles
.DEFAULT
;
525 var strokePattern
= g
.getOption("strokePattern", setName
);
526 var drawPoints
= g
.getBooleanOption("drawPoints", setName
);
527 var pointSize
= g
.getNumericOption("pointSize", setName
);
529 if (borderWidth
&& strokeWidth
) {
530 DygraphCanvasRenderer
._drawStyledLine(e
,
531 g
.getOption("strokeBorderColor", setName
),
532 strokeWidth
+ 2 * borderWidth
,
540 DygraphCanvasRenderer
._drawStyledLine(e
,
551 * Draws the shaded error bars/confidence intervals for each series.
552 * This happens before the center lines are drawn, since the center lines
553 * need to be drawn on top of the error bars for all series.
556 DygraphCanvasRenderer
._errorPlotter
= function(e
) {
558 var setName
= e
.setName
;
559 var errorBars
= g
.getBooleanOption("errorBars") ||
560 g
.getBooleanOption("customBars");
561 if (!errorBars
) return;
563 var fillGraph
= g
.getBooleanOption("fillGraph", setName
);
565 Dygraph
.warn("Can't use fillGraph option with error bars");
568 var ctx
= e
.drawingContext
;
570 var fillAlpha
= g
.getNumericOption('fillAlpha', setName
);
571 var stepPlot
= g
.getBooleanOption("stepPlot", setName
);
572 var points
= e
.points
;
574 var iter
= Dygraph
.createIterator(points
, 0, points
.length
,
575 DygraphCanvasRenderer
._getIteratorPredicate(
576 g
.getBooleanOption("connectSeparatedPoints", setName
)));
580 // setup graphics context
583 var prevYs
= [-1, -1];
584 // should be same color as the lines but only 15% opaque.
585 var rgb
= Dygraph
.toRGB_(color
);
587 'rgba(' + rgb
.r
+ ',' + rgb
.g
+ ',' + rgb
.b
+ ',' + fillAlpha
+ ')';
588 ctx
.fillStyle
= err_color
;
591 var isNullUndefinedOrNaN
= function(x
) {
592 return (x
=== null ||
597 while (iter
.hasNext
) {
598 var point
= iter
.next();
599 if ((!stepPlot
&& isNullUndefinedOrNaN(point
.y
)) ||
600 (stepPlot
&& !isNaN(prevY
) && isNullUndefinedOrNaN(prevY
))) {
606 newYs
= [ point
.y_bottom
, point
.y_top
];
609 newYs
= [ point
.y_bottom
, point
.y_top
];
611 newYs
[0] = e
.plotArea
.h
* newYs
[0] + e
.plotArea
.y
;
612 newYs
[1] = e
.plotArea
.h
* newYs
[1] + e
.plotArea
.y
;
615 ctx
.moveTo(prevX
, prevYs
[0]);
616 ctx
.lineTo(point
.canvasx
, prevYs
[0]);
617 ctx
.lineTo(point
.canvasx
, prevYs
[1]);
619 ctx
.moveTo(prevX
, prevYs
[0]);
620 ctx
.lineTo(point
.canvasx
, newYs
[0]);
621 ctx
.lineTo(point
.canvasx
, newYs
[1]);
623 ctx
.lineTo(prevX
, prevYs
[1]);
627 prevX
= point
.canvasx
;
633 * Draws the shaded regions when "fillGraph" is set. Not to be confused with
636 * For stacked charts, it's more convenient to handle all the series
637 * simultaneously. So this plotter plots all the points on the first series
638 * it's asked to draw, then ignores all the other series.
642 DygraphCanvasRenderer
._fillPlotter
= function(e
) {
643 // Skip if we're drawing a single series for interactive highlight overlay.
644 if (e
.singleSeriesName
) return;
646 // We'll handle all the series at once, not one-by-one.
647 if (e
.seriesIndex
!== 0) return;
650 var setNames
= g
.getLabels().slice(1); // remove x-axis
652 // getLabels() includes names for invisible series, which are not included in
653 // allSeriesPoints. We remove those to make the two match.
654 // TODO(danvk): provide a simpler way to get this information.
655 for (var i
= setNames
.length
; i
>= 0; i
--) {
656 if (!g
.visibility()[i
]) setNames
.splice(i
, 1);
659 var anySeriesFilled
= (function() {
660 for (var i
= 0; i
< setNames
.length
; i
++) {
661 if (g
.getBooleanOption("fillGraph", setNames
[i
])) return true;
666 if (!anySeriesFilled
) return;
668 var ctx
= e
.drawingContext
;
669 var area
= e
.plotArea
;
670 var sets
= e
.allSeriesPoints
;
671 var setCount
= sets
.length
;
673 var fillAlpha
= g
.getNumericOption('fillAlpha');
674 var stackedGraph
= g
.getBooleanOption("stackedGraph");
675 var colors
= g
.getColors();
677 // For stacked graphs, track the baseline for filling.
679 // The filled areas below graph lines are trapezoids with two
680 // vertical edges. The top edge is the line segment being drawn, and
681 // the baseline is the bottom edge. Each baseline corresponds to the
682 // top line segment from the previous stacked line. In the case of
683 // step plots, the trapezoids are rectangles.
686 var prevStepPlot
; // for different line drawing modes (line/step) per series
688 // process sets in reverse order (needed for stacked graphs)
689 for (var setIdx
= setCount
- 1; setIdx
>= 0; setIdx
--) {
690 var setName
= setNames
[setIdx
];
691 if (!g
.getBooleanOption('fillGraph', setName
)) continue;
693 var stepPlot
= g
.getBooleanOption('stepPlot', setName
);
694 var fillStepPlot
= stepPlot
&& g
.getBooleanOption("fillStepPlot", setName
);
695 var color
= colors
[setIdx
];
696 var axis
= g
.axisPropertiesForSeries(setName
);
697 var axisY
= 1.0 + axis
.minyval
* axis
.yscale
;
698 if (axisY
< 0.0) axisY
= 0.0;
699 else if (axisY
> 1.0) axisY
= 1.0;
700 axisY
= area
.h
* axisY
+ area
.y
;
702 var points
= sets
[setIdx
];
703 var iter
= Dygraph
.createIterator(points
, 0, points
.length
,
704 DygraphCanvasRenderer
._getIteratorPredicate(
705 g
.getBooleanOption("connectSeparatedPoints", setName
)));
707 // setup graphics context
709 var prevYs
= [-1, -1];
711 // should be same color as the lines but only 15% opaque.
712 var rgb
= Dygraph
.toRGB_(color
);
714 'rgba(' + rgb
.r
+ ',' + rgb
.g
+ ',' + rgb
.b
+ ',' + fillAlpha
+ ')';
715 ctx
.fillStyle
= err_color
;
717 var last_x
, is_first
= true;
718 while (iter
.hasNext
) {
719 var point
= iter
.next();
720 if (!Dygraph
.isOK(point
.y
) && !fillStepPlot
) {
722 if (point
.y_stacked
!== null && !isNaN(point
.y_stacked
)) {
723 baseline
[point
.canvasx
] = area
.h
* point
.y_stacked
+ area
.y
;
728 if (!is_first
&& last_x
== point
.xval
) {
735 currBaseline
= baseline
[point
.canvasx
];
737 if (currBaseline
=== undefined
) {
741 lastY
= currBaseline
[0];
743 lastY
= currBaseline
;
746 newYs
= [ point
.canvasy
, lastY
];
749 // Step plots must keep track of the top and bottom of
750 // the baseline at each point.
751 if(prevYs
[0] === -1) {
752 baseline
[point
.canvasx
] = [ point
.canvasy
, axisY
];
754 baseline
[point
.canvasx
] = [ point
.canvasy
, prevYs
[0] ];
757 baseline
[point
.canvasx
] = point
.canvasy
;
761 if (isNaN(point
.canvasy
) && fillStepPlot
)
763 newYs
= [ area
.y
+ area
.h
, axisY
];
767 newYs
= [ point
.canvasy
, axisY
];
771 ctx
.moveTo(prevX
, prevYs
[0]);
773 // Move to top fill point
775 ctx
.lineTo(point
.canvasx
, prevYs
[0]);
777 ctx
.lineTo(point
.canvasx
, newYs
[0]);
779 // Move to bottom fill point
780 if (prevStepPlot
&& currBaseline
) {
781 // Draw to the bottom of the baseline
782 ctx
.lineTo(point
.canvasx
, currBaseline
[1]);
784 ctx
.lineTo(point
.canvasx
, newYs
[1]);
787 ctx
.lineTo(prevX
, prevYs
[1]);
791 prevX
= point
.canvasx
;
793 prevStepPlot
= stepPlot
;