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
);
90 DygraphCanvasRenderer
.prototype.attr_
= function(x
) {
91 return this.dygraph_
.attr_(x
);
95 * Clears out all chart content and DOM elements.
96 * This is called immediately before render() on every frame, including
97 * during zooms and pans.
100 DygraphCanvasRenderer
.prototype.clear
= function() {
103 // VML takes a while to start up, so we just poll every this.IEDelay
105 if (this.clearDelay
) {
106 this.clearDelay
.cancel();
107 this.clearDelay
= null;
109 context
= this.elementContext
;
112 // TODO(danvk): this is broken, since MochiKit.Async is gone.
113 // this.clearDelay = MochiKit.Async.wait(this.IEDelay);
114 // this.clearDelay.addCallback(bind(this.clear, this));
119 context
= this.elementContext
;
120 context
.clearRect(0, 0, this.width
, this.height
);
124 * Checks whether the browser supports the <canvas> tag.
127 DygraphCanvasRenderer
.isSupported
= function(canvasName
) {
130 if (typeof(canvasName
) == 'undefined' || canvasName
=== null) {
131 canvas
= document
.createElement("canvas");
135 canvas
.getContext("2d");
138 var ie
= navigator
.appVersion
.match(/MSIE (\d\.\d)/);
139 var opera
= (navigator
.userAgent
.toLowerCase().indexOf("opera") != -1);
140 if ((!ie
) || (ie
[1] < 6) || (opera
))
148 * This method is responsible for drawing everything on the chart, including
149 * lines, error bars, fills and axes.
150 * It is called immediately after clear() on every frame, including during pans
154 DygraphCanvasRenderer
.prototype.render
= function() {
155 this._renderLineChart();
158 DygraphCanvasRenderer
.prototype._createIEClipArea
= function() {
159 var className
= 'dygraph-clip-div';
160 var graphDiv
= this.dygraph_
.graphDiv
;
162 // Remove old clip divs.
163 for (var i
= graphDiv
.childNodes
.length
-1; i
>= 0; i
--) {
164 if (graphDiv
.childNodes
[i
].className
== className
) {
165 graphDiv
.removeChild(graphDiv
.childNodes
[i
]);
169 // Determine background color to give clip divs.
170 var backgroundColor
= document
.bgColor
;
171 var element
= this.dygraph_
.graphDiv
;
172 while (element
!= document
) {
173 var bgcolor
= element
.currentStyle
.backgroundColor
;
174 if (bgcolor
&& bgcolor
!= 'transparent') {
175 backgroundColor
= bgcolor
;
178 element
= element
.parentNode
;
181 function createClipDiv(area
) {
182 if (area
.w
=== 0 || area
.h
=== 0) {
185 var elem
= document
.createElement('div');
186 elem
.className
= className
;
187 elem
.style
.backgroundColor
= backgroundColor
;
188 elem
.style
.position
= 'absolute';
189 elem
.style
.left
= area
.x
+ 'px';
190 elem
.style
.top
= area
.y
+ 'px';
191 elem
.style
.width
= area
.w
+ 'px';
192 elem
.style
.height
= area
.h
+ 'px';
193 graphDiv
.appendChild(elem
);
196 var plotArea
= this.area
;
207 w
: this.width
- plotArea
.x
,
213 x
: plotArea
.x
+ plotArea
.w
, y
: 0,
214 w
: this.width
-plotArea
.x
- plotArea
.w
,
221 y
: plotArea
.y
+ plotArea
.h
,
222 w
: this.width
- plotArea
.x
,
223 h
: this.height
- plotArea
.h
- plotArea
.y
229 * Returns a predicate to be used with an iterator, which will
230 * iterate over points appropriately, depending on whether
231 * connectSeparatedPoints is true. When it's false, the predicate will
232 * skip over points with missing yVals.
234 DygraphCanvasRenderer
._getIteratorPredicate
= function(connectSeparatedPoints
) {
235 return connectSeparatedPoints
236 ? DygraphCanvasRenderer
._predicateThatSkipsEmptyPoints
240 DygraphCanvasRenderer
._predicateThatSkipsEmptyPoints
=
241 function(array
, idx
) {
242 return array
[idx
].yval
!== null;
249 DygraphCanvasRenderer
.prototype._drawStyledLine
= function(
250 ctx
, i
, setName
, color
, strokeWidth
, strokePattern
, drawPoints
,
251 drawPointCallback
, pointSize
) {
252 // TODO(konigsberg): Compute attributes outside this method call.
253 var stepPlot
= this.attr_("stepPlot");
254 var firstIndexInSet
= this.layout
.setPointsOffsets
[i
];
255 var setLength
= this.layout
.setPointsLengths
[i
];
256 var points
= this.layout
.points
;
257 if (!Dygraph
.isArrayLike(strokePattern
)) {
258 strokePattern
= null;
260 var drawGapPoints
= this.dygraph_
.attr_('drawGapEdgePoints', setName
);
262 var iter
= Dygraph
.createIterator(points
, firstIndexInSet
, setLength
,
263 DygraphCanvasRenderer
._getIteratorPredicate(
264 this.attr_("connectSeparatedPoints")));
266 var stroking
= strokePattern
&& (strokePattern
.length
>= 2);
270 ctx
.installPattern(strokePattern
);
273 var pointsOnLine
= this._drawSeries(ctx
, iter
, strokeWidth
, pointSize
, drawPoints
, drawGapPoints
, stepPlot
, color
);
274 this._drawPointsOnLine(ctx
, pointsOnLine
, drawPointCallback
, setName
, color
, pointSize
);
277 ctx
.uninstallPattern();
283 DygraphCanvasRenderer
.prototype._drawPointsOnLine
= function(ctx
, pointsOnLine
, drawPointCallback
, setName
, color
, pointSize
) {
284 for (var idx
= 0; idx
< pointsOnLine
.length
; idx
++) {
285 var cb
= pointsOnLine
[idx
];
288 this.dygraph_
, setName
, ctx
, cb
[0], cb
[1], color
, pointSize
);
293 DygraphCanvasRenderer
.prototype._drawSeries
= function(
294 ctx
, iter
, strokeWidth
, pointSize
, drawPoints
, drawGapPoints
,
297 var prevCanvasX
= null;
298 var prevCanvasY
= null;
299 var nextCanvasY
= null;
300 var isIsolated
; // true if this point is isolated (no line segments)
301 var point
; // the point being processed in the while loop
302 var pointsOnLine
= []; // Array of [canvasx, canvasy] pairs.
303 var first
= true; // the first cycle through the while loop
306 ctx
.strokeStyle
= color
;
307 ctx
.lineWidth
= strokeWidth
;
309 var arr
= iter
.array_
;
310 var limit
= iter
.end_
;
311 var predicate
= iter
.predicate_
;
313 for (var i
= iter
.start_
; i
< limit
; i
++) {
316 while (i
< limit
&& !predicate(arr
, i
)) {
319 if (i
== limit
) break;
323 if (point
.canvasy
=== null || point
.canvasy
!= point
.canvasy
) {
324 if (stepPlot
&& prevCanvasX
!== null) {
325 // Draw a horizontal line to the start of the missing data
326 ctx
.moveTo(prevX
, prevY
);
327 ctx
.lineTo(point
.canvasx
, prevY
);
329 prevCanvasX
= prevCanvasY
= null;
332 if (drawGapPoints
|| !prevCanvasX
) {
334 var peek
= iter
.next();
335 nextCanvasY
= iter
.hasNext
? iter
.peek
.canvasy
: null;
337 var isNextCanvasYNullOrNaN
= nextCanvasY
=== null ||
338 nextCanvasY
!= nextCanvasY
;
339 isIsolated
= (!prevCanvasX
&& isNextCanvasYNullOrNaN
);
341 // Also consider a point to be "isolated" if it's adjacent to a
342 // null point, excluding the graph edges.
343 if ((!first
&& !prevCanvasX
) ||
344 (iter
.hasNext
&& isNextCanvasYNullOrNaN
)) {
350 if (prevCanvasX
!== null) {
353 ctx
.moveTo(prevCanvasX
, prevCanvasY
);
354 ctx
.lineTo(point
.canvasx
, prevCanvasY
);
355 prevCanvasX
= point
.canvasx
;
357 ctx
.moveTo(prevCanvasX
, prevCanvasY
);
358 ctx
.lineTo(point
.canvasx
, point
.canvasy
);
361 if (drawPoints
|| isIsolated
) {
362 pointsOnLine
.push([point
.canvasx
, point
.canvasy
]);
364 prevCanvasX
= point
.canvasx
;
365 prevCanvasY
= point
.canvasy
;
373 DygraphCanvasRenderer
.prototype._drawLine
= function(ctx
, i
) {
374 var setNames
= this.layout
.setNames
;
375 var setName
= setNames
[i
];
377 var strokeWidth
= this.dygraph_
.attr_("strokeWidth", setName
);
378 var borderWidth
= this.dygraph_
.attr_("strokeBorderWidth", setName
);
379 var drawPointCallback
= this.dygraph_
.attr_("drawPointCallback", setName
) ||
380 Dygraph
.Circles
.DEFAULT
;
382 if (borderWidth
&& strokeWidth
) {
383 this._drawStyledLine(ctx
, i
, setName
,
384 this.dygraph_
.attr_("strokeBorderColor", setName
),
385 strokeWidth
+ 2 * borderWidth
,
386 this.dygraph_
.attr_("strokePattern", setName
),
387 this.dygraph_
.attr_("drawPoints", setName
),
389 this.dygraph_
.attr_("pointSize", setName
));
392 this._drawStyledLine(ctx
, i
, setName
,
393 this.colors
[setName
],
395 this.dygraph_
.attr_("strokePattern", setName
),
396 this.dygraph_
.attr_("drawPoints", setName
),
398 this.dygraph_
.attr_("pointSize", setName
));
402 * Actually draw the lines chart, including error bars.
405 DygraphCanvasRenderer
.prototype._renderLineChart
= function() {
406 var ctx
= this.elementContext
;
407 var errorBars
= this.attr_("errorBars") || this.attr_("customBars");
408 var fillGraph
= this.attr_("fillGraph");
411 var setNames
= this.layout
.setNames
;
412 var setCount
= setNames
.length
;
414 this.colors
= this.dygraph_
.colorsMap_
;
419 // TODO(bhs): this loop is a hot-spot for high-point-count charts. These
420 // transformations can be pushed into the canvas via linear transformation
422 var points
= this.layout
.points
;
423 for (i
= points
.length
; i
--;) {
424 var point
= points
[i
];
425 point
.canvasx
= this.area
.w
* point
.x
+ this.area
.x
;
426 point
.canvasy
= this.area
.h
* point
.y
+ this.area
.y
;
429 // Draw any "fills", i.e. error bars or the filled area under a series.
430 // These must all be drawn before any lines, so that the main lines of a
431 // series are drawn on top.
434 this.dygraph_
.warn("Can't use fillGraph option with error bars");
438 this.drawErrorBars_(points
);
440 } else if (fillGraph
) {
442 this.drawFillBars_(points
);
446 // Drawing the lines.
447 for (i
= 0; i
< setCount
; i
+= 1) {
448 this._drawLine(ctx
, i
);
453 * Draws the shaded error bars/confidence intervals for each series.
454 * This happens before the center lines are drawn, since the center lines
455 * need to be drawn on top of the error bars for all series.
459 DygraphCanvasRenderer
.prototype.drawErrorBars_
= function(points
) {
460 var ctx
= this.elementContext
;
461 var setNames
= this.layout
.setNames
;
462 var setCount
= setNames
.length
;
463 var fillAlpha
= this.attr_('fillAlpha');
464 var stepPlot
= this.attr_('stepPlot');
468 for (var i
= 0; i
< setCount
; i
++) {
469 var setName
= setNames
[i
];
470 var axis
= this.dygraph_
.axisPropertiesForSeries(setName
);
471 var color
= this.colors
[setName
];
473 var firstIndexInSet
= this.layout
.setPointsOffsets
[i
];
474 var setLength
= this.layout
.setPointsLengths
[i
];
476 var iter
= Dygraph
.createIterator(points
, firstIndexInSet
, setLength
,
477 DygraphCanvasRenderer
._getIteratorPredicate(
478 this.attr_("connectSeparatedPoints")));
480 // setup graphics context
483 var prevYs
= [-1, -1];
484 var yscale
= axis
.yscale
;
485 // should be same color as the lines but only 15% opaque.
486 var rgb
= new RGBColor(color
);
488 'rgba(' + rgb
.r
+ ',' + rgb
.g
+ ',' + rgb
.b
+ ',' + fillAlpha
+ ')';
489 ctx
.fillStyle
= err_color
;
491 while (iter
.hasNext
) {
492 var point
= iter
.next();
493 if (!Dygraph
.isOK(point
.y
)) {
500 newYs
= [ point
.y_bottom
, point
.y_top
];
503 newYs
= [ point
.y_bottom
, point
.y_top
];
505 newYs
[0] = this.area
.h
* newYs
[0] + this.area
.y
;
506 newYs
[1] = this.area
.h
* newYs
[1] + this.area
.y
;
509 ctx
.moveTo(prevX
, newYs
[0]);
511 ctx
.moveTo(prevX
, prevYs
[0]);
513 ctx
.lineTo(point
.canvasx
, newYs
[0]);
514 ctx
.lineTo(point
.canvasx
, newYs
[1]);
516 ctx
.lineTo(prevX
, newYs
[1]);
518 ctx
.lineTo(prevX
, prevYs
[1]);
523 prevX
= point
.canvasx
;
530 * Draws the shaded regions when "fillGraph" is set. Not to be confused with
535 DygraphCanvasRenderer
.prototype.drawFillBars_
= function(points
) {
536 var ctx
= this.elementContext
;
537 var setNames
= this.layout
.setNames
;
538 var setCount
= setNames
.length
;
539 var fillAlpha
= this.attr_('fillAlpha');
540 var stepPlot
= this.attr_('stepPlot');
541 var stackedGraph
= this.attr_("stackedGraph");
543 var baseline
= {}; // for stacked graphs: baseline for filling
546 // process sets in reverse order (needed for stacked graphs)
547 for (var i
= setCount
- 1; i
>= 0; i
--) {
548 var setName
= setNames
[i
];
549 var color
= this.colors
[setName
];
550 var axis
= this.dygraph_
.axisPropertiesForSeries(setName
);
551 var axisY
= 1.0 + axis
.minyval
* axis
.yscale
;
552 if (axisY
< 0.0) axisY
= 0.0;
553 else if (axisY
> 1.0) axisY
= 1.0;
554 axisY
= this.area
.h
* axisY
+ this.area
.y
;
555 var firstIndexInSet
= this.layout
.setPointsOffsets
[i
];
556 var setLength
= this.layout
.setPointsLengths
[i
];
558 var iter
= Dygraph
.createIterator(points
, firstIndexInSet
, setLength
,
559 DygraphCanvasRenderer
._getIteratorPredicate(
560 this.attr_("connectSeparatedPoints")));
562 // setup graphics context
564 var prevYs
= [-1, -1];
566 var yscale
= axis
.yscale
;
567 // should be same color as the lines but only 15% opaque.
568 var rgb
= new RGBColor(color
);
570 'rgba(' + rgb
.r
+ ',' + rgb
.g
+ ',' + rgb
.b
+ ',' + fillAlpha
+ ')';
571 ctx
.fillStyle
= err_color
;
573 while(iter
.hasNext
) {
574 var point
= iter
.next();
575 if (!Dygraph
.isOK(point
.y
)) {
580 currBaseline
= baseline
[point
.canvasx
];
582 if (currBaseline
=== undefined
) {
586 lastY
= currBaseline
[0];
588 lastY
= currBaseline
;
591 newYs
= [ point
.canvasy
, lastY
];
594 // Step plots must keep track of the top and bottom of
595 // the baseline at each point.
596 if(prevYs
[0] === -1) {
597 baseline
[point
.canvasx
] = [ point
.canvasy
, axisY
];
599 baseline
[point
.canvasx
] = [ point
.canvasy
, prevYs
[0] ];
602 baseline
[point
.canvasx
] = point
.canvasy
;
606 newYs
= [ point
.canvasy
, axisY
];
609 ctx
.moveTo(prevX
, prevYs
[0]);
612 ctx
.lineTo(point
.canvasx
, prevYs
[0]);
614 // Draw to the bottom of the baseline
615 ctx
.lineTo(point
.canvasx
, currBaseline
[1]);
617 ctx
.lineTo(point
.canvasx
, newYs
[1]);
620 ctx
.lineTo(point
.canvasx
, newYs
[0]);
621 ctx
.lineTo(point
.canvasx
, newYs
[1]);
624 ctx
.lineTo(prevX
, prevYs
[1]);
628 prevX
= point
.canvasx
;