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,RGBColor: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 {Dyraph} dygraph The chart to which this renderer belongs.
43 * @param {Canvas} 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 if (!this.isIE
&& !(DygraphCanvasRenderer
.isSupported(this.element
)))
62 throw "Canvas is not supported.";
65 this.area
= layout
.getPlotArea();
66 this.container
.style
.position
= "relative";
67 this.container
.style
.width
= this.width
+ "px";
69 // Set up a clipping area for the canvas (and the interaction canvas).
70 // This ensures that we don't overdraw.
71 if (this.dygraph_
.isUsingExcanvas_
) {
72 this._createIEClipArea();
74 // on Android 3 and 4, setting a clipping area on a canvas prevents it from
75 // displaying anything.
76 if (!Dygraph
.isAndroid()) {
77 var ctx
= this.dygraph_
.canvas_ctx_
;
79 ctx
.rect(this.area
.x
, this.area
.y
, this.area
.w
, this.area
.h
);
82 ctx
= this.dygraph_
.hidden_ctx_
;
84 ctx
.rect(this.area
.x
, this.area
.y
, this.area
.w
, this.area
.h
);
91 * This just forwards to dygraph.attr_.
92 * TODO(danvk): remove this?
95 DygraphCanvasRenderer
.prototype.attr_
= function(name
, opt_seriesName
) {
96 return this.dygraph_
.attr_(name
, opt_seriesName
);
100 * Clears out all chart content and DOM elements.
101 * This is called immediately before render() on every frame, including
102 * during zooms and pans.
105 DygraphCanvasRenderer
.prototype.clear
= function() {
108 // VML takes a while to start up, so we just poll every this.IEDelay
110 if (this.clearDelay
) {
111 this.clearDelay
.cancel();
112 this.clearDelay
= null;
114 context
= this.elementContext
;
117 // TODO(danvk): this is broken, since MochiKit.Async is gone.
118 // this.clearDelay = MochiKit.Async.wait(this.IEDelay);
119 // this.clearDelay.addCallback(bind(this.clear, this));
124 context
= this.elementContext
;
125 context
.clearRect(0, 0, this.width
, this.height
);
129 * Checks whether the browser supports the <canvas> tag.
132 DygraphCanvasRenderer
.isSupported
= function(canvasName
) {
135 if (typeof(canvasName
) == 'undefined' || canvasName
=== null) {
136 canvas
= document
.createElement("canvas");
140 canvas
.getContext("2d");
143 var ie
= navigator
.appVersion
.match(/MSIE (\d\.\d)/);
144 var opera
= (navigator
.userAgent
.toLowerCase().indexOf("opera") != -1);
145 if ((!ie
) || (ie
[1] < 6) || (opera
))
153 * This method is responsible for drawing everything on the chart, including
154 * lines, error bars, fills and axes.
155 * It is called immediately after clear() on every frame, including during pans
159 DygraphCanvasRenderer
.prototype.render
= function() {
160 // attaches point.canvas{x,y}
161 this._updatePoints();
163 // actually draws the chart.
164 this._renderLineChart();
167 DygraphCanvasRenderer
.prototype._createIEClipArea
= function() {
168 var className
= 'dygraph-clip-div';
169 var graphDiv
= this.dygraph_
.graphDiv
;
171 // Remove old clip divs.
172 for (var i
= graphDiv
.childNodes
.length
-1; i
>= 0; i
--) {
173 if (graphDiv
.childNodes
[i
].className
== className
) {
174 graphDiv
.removeChild(graphDiv
.childNodes
[i
]);
178 // Determine background color to give clip divs.
179 var backgroundColor
= document
.bgColor
;
180 var element
= this.dygraph_
.graphDiv
;
181 while (element
!= document
) {
182 var bgcolor
= element
.currentStyle
.backgroundColor
;
183 if (bgcolor
&& bgcolor
!= 'transparent') {
184 backgroundColor
= bgcolor
;
187 element
= element
.parentNode
;
190 function createClipDiv(area
) {
191 if (area
.w
=== 0 || area
.h
=== 0) {
194 var elem
= document
.createElement('div');
195 elem
.className
= className
;
196 elem
.style
.backgroundColor
= backgroundColor
;
197 elem
.style
.position
= 'absolute';
198 elem
.style
.left
= area
.x
+ 'px';
199 elem
.style
.top
= area
.y
+ 'px';
200 elem
.style
.width
= area
.w
+ 'px';
201 elem
.style
.height
= area
.h
+ 'px';
202 graphDiv
.appendChild(elem
);
205 var plotArea
= this.area
;
216 w
: this.width
- plotArea
.x
,
222 x
: plotArea
.x
+ plotArea
.w
, y
: 0,
223 w
: this.width
-plotArea
.x
- plotArea
.w
,
230 y
: plotArea
.y
+ plotArea
.h
,
231 w
: this.width
- plotArea
.x
,
232 h
: this.height
- plotArea
.h
- plotArea
.y
238 * Returns a predicate to be used with an iterator, which will
239 * iterate over points appropriately, depending on whether
240 * connectSeparatedPoints is true. When it's false, the predicate will
241 * skip over points with missing yVals.
243 DygraphCanvasRenderer
._getIteratorPredicate
= function(connectSeparatedPoints
) {
244 return connectSeparatedPoints
?
245 DygraphCanvasRenderer
._predicateThatSkipsEmptyPoints
:
249 DygraphCanvasRenderer
._predicateThatSkipsEmptyPoints
=
250 function(array
, idx
) {
251 return array
[idx
].yval
!== null;
255 * Draws a line with the styles passed in and calls all the drawPointCallbacks.
256 * @param {Object} e The dictionary passed to the plotter function.
259 DygraphCanvasRenderer
._drawStyledLine
= function(e
,
260 color
, strokeWidth
, strokePattern
, drawPoints
,
261 drawPointCallback
, pointSize
) {
263 // TODO(konigsberg): Compute attributes outside this method call.
264 var stepPlot
= g
.getOption("stepPlot"); // TODO(danvk): per-series
265 if (!Dygraph
.isArrayLike(strokePattern
)) {
266 strokePattern
= null;
269 var drawGapPoints
= g
.getOption('drawGapEdgePoints', e
.setName
);
271 var points
= e
.points
;
272 var iter
= Dygraph
.createIterator(points
, 0, points
.length
,
273 DygraphCanvasRenderer
._getIteratorPredicate(
274 g
.getOption("connectSeparatedPoints"))); // TODO(danvk): per-series?
276 var stroking
= strokePattern
&& (strokePattern
.length
>= 2);
278 var ctx
= e
.drawingContext
;
281 ctx
.installPattern(strokePattern
);
284 var pointsOnLine
= DygraphCanvasRenderer
._drawSeries(
285 e
, iter
, strokeWidth
, pointSize
, drawPoints
, drawGapPoints
, stepPlot
, color
);
286 DygraphCanvasRenderer
._drawPointsOnLine(
287 e
, pointsOnLine
, drawPointCallback
, color
, pointSize
);
290 ctx
.uninstallPattern();
297 * This does the actual drawing of lines on the canvas, for just one series.
298 * Returns a list of [canvasx, canvasy] pairs for points for which a
299 * drawPointCallback should be fired. These include isolated points, or all
300 * points if drawPoints=true.
301 * @param {Object} e The dictionary passed to the plotter function.
304 DygraphCanvasRenderer
._drawSeries
= function(e
,
305 iter
, strokeWidth
, pointSize
, drawPoints
, drawGapPoints
, stepPlot
, color
) {
307 var prevCanvasX
= null;
308 var prevCanvasY
= null;
309 var nextCanvasY
= null;
310 var isIsolated
; // true if this point is isolated (no line segments)
311 var point
; // the point being processed in the while loop
312 var pointsOnLine
= []; // Array of [canvasx, canvasy] pairs.
313 var first
= true; // the first cycle through the while loop
315 var ctx
= e
.drawingContext
;
317 ctx
.strokeStyle
= color
;
318 ctx
.lineWidth
= strokeWidth
;
320 // NOTE: we break the iterator's encapsulation here for about a 25% speedup.
321 var arr
= iter
.array_
;
322 var limit
= iter
.end_
;
323 var predicate
= iter
.predicate_
;
325 for (var i
= iter
.start_
; i
< limit
; i
++) {
328 while (i
< limit
&& !predicate(arr
, i
)) {
331 if (i
== limit
) break;
335 if (point
.canvasy
=== null || point
.canvasy
!= point
.canvasy
) {
336 if (stepPlot
&& prevCanvasX
!== null) {
337 // Draw a horizontal line to the start of the missing data
338 ctx
.moveTo(prevCanvasX
, prevCanvasY
);
339 ctx
.lineTo(point
.canvasx
, prevCanvasY
);
341 prevCanvasX
= prevCanvasY
= null;
344 if (drawGapPoints
|| !prevCanvasX
) {
346 var peek
= iter
.next();
347 nextCanvasY
= iter
.hasNext
? iter
.peek
.canvasy
: null;
349 var isNextCanvasYNullOrNaN
= nextCanvasY
=== null ||
350 nextCanvasY
!= nextCanvasY
;
351 isIsolated
= (!prevCanvasX
&& isNextCanvasYNullOrNaN
);
353 // Also consider a point to be "isolated" if it's adjacent to a
354 // null point, excluding the graph edges.
355 if ((!first
&& !prevCanvasX
) ||
356 (iter
.hasNext
&& isNextCanvasYNullOrNaN
)) {
362 if (prevCanvasX
!== null) {
365 ctx
.moveTo(prevCanvasX
, prevCanvasY
);
366 ctx
.lineTo(point
.canvasx
, prevCanvasY
);
367 prevCanvasX
= point
.canvasx
;
370 // TODO(danvk): this moveTo is rarely necessary
371 ctx
.moveTo(prevCanvasX
, prevCanvasY
);
372 ctx
.lineTo(point
.canvasx
, point
.canvasy
);
375 if (drawPoints
|| isIsolated
) {
376 pointsOnLine
.push([point
.canvasx
, point
.canvasy
]);
378 prevCanvasX
= point
.canvasx
;
379 prevCanvasY
= point
.canvasy
;
388 * This fires the drawPointCallback functions, which draw dots on the points by
389 * default. This gets used when the "drawPoints" option is set, or when there
390 * are isolated points.
391 * @param {Object} e The dictionary passed to the plotter function.
394 DygraphCanvasRenderer
._drawPointsOnLine
= function(
395 e
, pointsOnLine
, drawPointCallback
, color
, pointSize
) {
396 var ctx
= e
.drawingContext
;
397 for (var idx
= 0; idx
< pointsOnLine
.length
; idx
++) {
398 var cb
= pointsOnLine
[idx
];
401 e
.dygraph
, e
.setName
, ctx
, cb
[0], cb
[1], color
, pointSize
);
407 * Attaches canvas coordinates to the points array.
410 DygraphCanvasRenderer
.prototype._updatePoints
= function() {
414 // TODO(bhs): this loop is a hot-spot for high-point-count charts. These
415 // transformations can be pushed into the canvas via linear transformation
417 // NOTE(danvk): this is trickier than it sounds at first. The transformation
418 // needs to be done before the .moveTo() and .lineTo() calls, but must be
419 // undone before the .stroke() call to ensure that the stroke width is
420 // unaffected. An alternative is to reduce the stroke width in the
421 // transformed coordinate space, but you can't specify different values for
422 // each dimension (as you can with .scale()). The speedup here is ~12%.
423 var sets
= this.layout
.points
;
424 for (var i
= sets
.length
; i
--;) {
425 var points
= sets
[i
];
426 for (var j
= points
.length
; j
--;) {
427 var point
= points
[j
];
428 point
.canvasx
= this.area
.w
* point
.x
+ this.area
.x
;
429 point
.canvasy
= this.area
.h
* point
.y
+ this.area
.y
;
435 * Add canvas Actually draw the lines chart, including error bars.
436 * If opt_seriesName is specified, only that series will be drawn.
437 * (This is used for expedited redrawing with highlightSeriesOpts)
438 * Lines are typically drawn in the non-interactive dygraph canvas. If opt_ctx
439 * is specified, they can be drawn elsewhere.
441 * This function can only be called if DygraphLayout's points array has been
442 * updated with canvas{x,y} attributes, i.e. by
443 * DygraphCanvasRenderer._updatePoints.
446 DygraphCanvasRenderer
.prototype._renderLineChart
= function(opt_seriesName
, opt_ctx
) {
447 var ctx
= opt_ctx
|| this.elementContext
;
448 var errorBars
= this.attr_("errorBars") || this.attr_("customBars");
449 var fillGraph
= this.attr_("fillGraph");
452 var sets
= this.layout
.points
;
453 var setNames
= this.layout
.setNames
;
454 var setCount
= setNames
.length
;
457 this.colors
= this.dygraph_
.colorsMap_
;
459 // Determine which series have specialized plotters.
460 var plotter_attr
= this.attr_("plotter");
461 var plotters
= plotter_attr
;
462 if (!Dygraph
.isArrayLike(plotters
)) {
463 plotters
= [plotters
];
466 var setPlotters
= {}; // series name -> plotter fn.
467 for (i
= 0; i
< setNames
.length
; i
++) {
468 setName
= setNames
[i
];
469 var setPlotter
= this.attr_("plotter", setName
);
470 if (setPlotter
== plotter_attr
) continue; // not specialized.
472 setPlotters
[setName
] = setPlotter
;
475 for (i
= 0; i
< plotters
.length
; i
++) {
476 var plotter
= plotters
[i
];
477 var is_last
= (i
== plotters
.length
- 1);
479 for (var j
= 0; j
< sets
.length
; j
++) {
480 setName
= setNames
[j
];
481 if (opt_seriesName
&& setName
!= opt_seriesName
) continue;
483 var points
= sets
[j
];
485 // Only throw in the specialized plotters on the last iteration.
487 if (setName
in setPlotters
) {
489 p
= setPlotters
[setName
];
491 // Don't use the standard plotters in this case.
496 var color
= this.colors
[setName
];
497 var strokeWidth
= this.dygraph_
.getOption("strokeWidth", setName
);
500 ctx
.strokeStyle
= color
;
501 ctx
.lineWidth
= strokeWidth
;
507 strokeWidth
: strokeWidth
,
508 dygraph
: this.dygraph_
,
509 axis
: this.dygraph_
.axisPropertiesForSeries(setName
),
512 seriesCount
: sets
.length
,
513 allSeriesPoints
: sets
521 * Standard plotters. These may be used by clients via Dygraph.Plotters.
522 * See comments there for more details.
524 DygraphCanvasRenderer
._Plotters
= {
525 linePlotter
: function(e
) {
526 DygraphCanvasRenderer
._linePlotter(e
);
529 fillPlotter
: function(e
) {
530 DygraphCanvasRenderer
._fillPlotter(e
);
533 errorPlotter
: function(e
) {
534 DygraphCanvasRenderer
._errorPlotter(e
);
539 * Plotter which draws the central lines for a series.
542 DygraphCanvasRenderer
._linePlotter
= function(e
) {
544 var setName
= e
.setName
;
545 var strokeWidth
= e
.strokeWidth
;
547 // TODO(danvk): Check if there's any performance impact of just calling
548 // getOption() inside of _drawStyledLine. Passing in so many parameters makes
549 // this code a bit nasty.
550 var borderWidth
= g
.getOption("strokeBorderWidth", setName
);
551 var drawPointCallback
= g
.getOption("drawPointCallback", setName
) ||
552 Dygraph
.Circles
.DEFAULT
;
553 var strokePattern
= g
.getOption("strokePattern", setName
);
554 var drawPoints
= g
.getOption("drawPoints", setName
);
555 var pointSize
= g
.getOption("pointSize", setName
);
557 if (borderWidth
&& strokeWidth
) {
558 DygraphCanvasRenderer
._drawStyledLine(e
,
559 g
.getOption("strokeBorderColor", setName
),
560 strokeWidth
+ 2 * borderWidth
,
568 DygraphCanvasRenderer
._drawStyledLine(e
,
579 * Draws the shaded error bars/confidence intervals for each series.
580 * This happens before the center lines are drawn, since the center lines
581 * need to be drawn on top of the error bars for all series.
584 DygraphCanvasRenderer
._errorPlotter
= function(e
) {
586 var errorBars
= g
.getOption("errorBars") || g
.getOption("customBars");
587 if (!errorBars
) return;
589 var fillGraph
= g
.getOption("fillGraph");
591 g
.warn("Can't use fillGraph option with error bars");
594 var setName
= e
.setName
;
595 var ctx
= e
.drawingContext
;
597 var fillAlpha
= g
.getOption('fillAlpha', setName
);
598 var stepPlot
= g
.getOption('stepPlot'); // TODO(danvk): per-series
600 var points
= e
.points
;
602 var iter
= Dygraph
.createIterator(points
, 0, points
.length
,
603 DygraphCanvasRenderer
._getIteratorPredicate(
604 g
.getOption("connectSeparatedPoints")));
608 // setup graphics context
611 var prevYs
= [-1, -1];
612 var yscale
= axis
.yscale
;
613 // should be same color as the lines but only 15% opaque.
614 var rgb
= new RGBColor(color
);
616 'rgba(' + rgb
.r
+ ',' + rgb
.g
+ ',' + rgb
.b
+ ',' + fillAlpha
+ ')';
617 ctx
.fillStyle
= err_color
;
619 while (iter
.hasNext
) {
620 var point
= iter
.next();
621 if ((!stepPlot
&& !Dygraph
.isOK(point
.y
)) || (stepPlot
&& !isNaN(prevY
) && !Dygraph
.isOK(prevY
))) {
627 newYs
= [ point
.y_bottom
, point
.y_top
];
630 newYs
= [ point
.y_bottom
, point
.y_top
];
632 newYs
[0] = e
.plotArea
.h
* newYs
[0] + e
.plotArea
.y
;
633 newYs
[1] = e
.plotArea
.h
* newYs
[1] + e
.plotArea
.y
;
636 ctx
.moveTo(prevX
, prevYs
[0]);
637 ctx
.lineTo(point
.canvasx
, prevYs
[0]);
638 ctx
.lineTo(point
.canvasx
, prevYs
[1]);
640 ctx
.moveTo(prevX
, prevYs
[0]);
641 ctx
.lineTo(point
.canvasx
, newYs
[0]);
642 ctx
.lineTo(point
.canvasx
, newYs
[1]);
644 ctx
.lineTo(prevX
, prevYs
[1]);
648 prevX
= point
.canvasx
;
654 * Draws the shaded regions when "fillGraph" is set. Not to be confused with
657 * For stacked charts, it's more convenient to handle all the series
658 * simultaneously. So this plotter plots all the points on the first series
659 * it's asked to draw, then ignores all the other series.
663 DygraphCanvasRenderer
._fillPlotter
= function(e
) {
665 if (!g
.getOption("fillGraph")) return;
667 // We'll handle all the series at once, not one-by-one.
668 if (e
.seriesIndex
!== 0) return;
670 var ctx
= e
.drawingContext
;
671 var area
= e
.plotArea
;
672 var sets
= e
.allSeriesPoints
;
673 var setCount
= sets
.length
;
675 var setNames
= g
.getLabels().slice(1); // remove x-axis
676 // getLabels() includes names for invisible series, which are not included in
677 // allSeriesPoints. We remove those to make the two match.
678 // TODO(danvk): provide a simpler way to get this information.
679 for (var i
= setNames
.length
; i
>= 0; i
--) {
680 if (!g
.visibility()[i
]) setNames
.splice(i
, 1);
683 var fillAlpha
= g
.getOption('fillAlpha');
684 var stepPlot
= g
.getOption('stepPlot');
685 var stackedGraph
= g
.getOption("stackedGraph");
686 var colors
= g
.getColors();
688 var baseline
= {}; // for stacked graphs: baseline for filling
691 // process sets in reverse order (needed for stacked graphs)
692 for (var setIdx
= setCount
- 1; setIdx
>= 0; setIdx
--) {
693 var setName
= setNames
[setIdx
];
694 var color
= colors
[setIdx
];
695 var axis
= g
.axisPropertiesForSeries(setName
);
696 var axisY
= 1.0 + axis
.minyval
* axis
.yscale
;
697 if (axisY
< 0.0) axisY
= 0.0;
698 else if (axisY
> 1.0) axisY
= 1.0;
699 axisY
= area
.h
* axisY
+ area
.y
;
701 var points
= sets
[setIdx
];
702 var iter
= Dygraph
.createIterator(points
, 0, points
.length
,
703 DygraphCanvasRenderer
._getIteratorPredicate(
704 g
.getOption("connectSeparatedPoints")));
706 // setup graphics context
708 var prevYs
= [-1, -1];
710 var yscale
= axis
.yscale
;
711 // should be same color as the lines but only 15% opaque.
712 var rgb
= new RGBColor(color
);
714 'rgba(' + rgb
.r
+ ',' + rgb
.g
+ ',' + rgb
.b
+ ',' + fillAlpha
+ ')';
715 ctx
.fillStyle
= err_color
;
717 while(iter
.hasNext
) {
718 var point
= iter
.next();
719 if (!Dygraph
.isOK(point
.y
)) {
724 currBaseline
= baseline
[point
.canvasx
];
726 if (currBaseline
=== undefined
) {
730 lastY
= currBaseline
[0];
732 lastY
= currBaseline
;
735 newYs
= [ point
.canvasy
, lastY
];
738 // Step plots must keep track of the top and bottom of
739 // the baseline at each point.
740 if(prevYs
[0] === -1) {
741 baseline
[point
.canvasx
] = [ point
.canvasy
, axisY
];
743 baseline
[point
.canvasx
] = [ point
.canvasy
, prevYs
[0] ];
746 baseline
[point
.canvasx
] = point
.canvasy
;
750 newYs
= [ point
.canvasy
, axisY
];
753 ctx
.moveTo(prevX
, prevYs
[0]);
756 ctx
.lineTo(point
.canvasx
, prevYs
[0]);
758 // Draw to the bottom of the baseline
759 ctx
.lineTo(point
.canvasx
, currBaseline
[1]);
761 ctx
.lineTo(point
.canvasx
, newYs
[1]);
764 ctx
.lineTo(point
.canvasx
, newYs
[0]);
765 ctx
.lineTo(point
.canvasx
, newYs
[1]);
768 ctx
.lineTo(prevX
, prevYs
[1]);
772 prevX
= point
.canvasx
;