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
? DygraphCanvasRenderer
._predicateThatSkipsEmptyPoints
: null;
238 DygraphCanvasRenderer
._predicateThatSkipsEmptyPoints
=
239 function(array
, idx
) { return array
[idx
].yval
!== null; }
241 DygraphCanvasRenderer
.prototype._drawStyledLine
= function(
242 ctx
, i
, setName
, color
, strokeWidth
, strokePattern
, drawPoints
,
243 drawPointCallback
, pointSize
) {
244 // TODO(konigsberg): Compute attributes outside this method call.
245 var stepPlot
= this.attr_("stepPlot");
246 var firstIndexInSet
= this.layout
.setPointsOffsets
[i
];
247 var setLength
= this.layout
.setPointsLengths
[i
];
248 var points
= this.layout
.points
;
249 if (!Dygraph
.isArrayLike(strokePattern
)) {
250 strokePattern
= null;
252 var drawGapPoints
= this.dygraph_
.attr_('drawGapEdgePoints', setName
);
256 var iter
= Dygraph
.createIterator(points
, firstIndexInSet
, setLength
,
257 DygraphCanvasRenderer
._getIteratorPredicate(this.attr_("connectSeparatedPoints")));
261 if (!strokePattern
|| strokePattern
.length
<= 1) {
262 strategy
= trivialStrategy(ctx
, color
, strokeWidth
);
264 strategy
= nonTrivialStrategy(this, ctx
, color
, strokeWidth
, strokePattern
);
266 pointsOnLine
= this._drawSeries(ctx
, iter
, strokeWidth
, pointSize
, drawPoints
, drawGapPoints
, stepPlot
, strategy
);
267 this._drawPointsOnLine(ctx
, pointsOnLine
, drawPointCallback
, setName
, color
, pointSize
);
272 var nonTrivialStrategy
= function(renderer
, ctx
, color
, strokeWidth
, strokePattern
) {
273 return new function() {
274 this.init
= function() { };
275 this.finish
= function() { };
276 this.startSegment
= function() {
278 ctx
.strokeStyle
= color
;
279 ctx
.lineWidth
= strokeWidth
;
281 this.endSegment
= function() {
282 ctx
.stroke(); // should this include closePath?
284 this.drawLine
= function(x1
, y1
, x2
, y2
) {
285 renderer
._dashedLine(ctx
, x1
, y1
, x2
, y2
, strokePattern
);
287 this.skipPixel
= function(prevX
, prevY
, curX
, curY
) {
288 // TODO(konigsberg): optimize with http://jsperf.com/math-round
-vs
-hack
/6 ?
289 return (Math
.round(prevX
) == Math
.round(curX
) &&
290 Math
.round(prevY
) == Math
.round(curY
));
295 var trivialStrategy
= function(ctx
, color
, strokeWidth
) {
296 return new function() {
297 this.init
= function() {
299 ctx
.strokeStyle
= color
;
300 ctx
.lineWidth
= strokeWidth
;
302 this.finish
= function() {
303 ctx
.stroke(); // should this include closePath?
305 this.startSegment
= function() { };
306 this.endSegment
= function() { };
307 this.drawLine
= function(x1
, y1
, x2
, y2
) {
311 // don't skip pixels.
312 this.skipPixel
= function() {
318 DygraphCanvasRenderer
.prototype._drawPointsOnLine
= function(ctx
, pointsOnLine
, drawPointCallback
, setName
, color
, pointSize
) {
319 for (var idx
= 0; idx
< pointsOnLine
.length
; idx
++) {
320 var cb
= pointsOnLine
[idx
];
323 this.dygraph_
, setName
, ctx
, cb
[0], cb
[1], color
, pointSize
);
328 DygraphCanvasRenderer
.prototype._drawSeries
= function(
329 ctx
, iter
, strokeWidth
, pointSize
, drawPoints
, drawGapPoints
,
330 stepPlot
, strategy
) {
332 var prevCanvasX
= null;
333 var prevCanvasY
= null;
334 var nextCanvasY
= null;
335 var isIsolated
; // true if this point is isolated (no line segments)
336 var point
; // the point being processed in the while loop
337 var pointsOnLine
= []; // Array of [canvasx, canvasy] pairs.
338 var first
= true; // the first cycle through the while loop
342 while(iter
.hasNext
) {
344 if (point
.canvasy
=== null || point
.canvasy
!= point
.canvasy
) {
345 if (stepPlot
&& prevCanvasX
!== null) {
346 // Draw a horizontal line to the start of the missing data
347 strategy
.startSegment();
348 strategy
.drawLine(prevX
, prevY
, point
.canvasx
, prevY
);
349 strategy
.endSegment();
351 prevCanvasX
= prevCanvasY
= null;
353 nextCanvasY
= iter
.hasNext
? iter
.peek
.canvasy
: null;
354 // TODO: we calculate isNullOrNaN for this point, and the next, and then, when
355 // we iterate, test for isNullOrNaN again. Why bother?
356 var isNextCanvasYNullOrNaN
= nextCanvasY
=== null || nextCanvasY
!= nextCanvasY
;
357 isIsolated
= (!prevCanvasX
&& isNextCanvasYNullOrNaN
);
359 // Also consider a point to be "isolated" if it's adjacent to a
360 // null point, excluding the graph edges.
361 if ((!first
&& !prevCanvasX
) ||
362 (iter
.hasNext
&& isNextCanvasYNullOrNaN
)) {
366 if (prevCanvasX
!== null) {
367 if (strategy
.skipPixel(prevCanvasX
, prevCanvasY
, point
.canvasx
, point
.canvasy
)) {
371 strategy
.startSegment();
373 strategy
.drawLine(prevCanvasX
, prevCanvasY
, point
.canvasx
, prevCanvasY
);
374 prevCanvasX
= point
.canvasx
;
376 strategy
.drawLine(prevCanvasX
, prevCanvasY
, point
.canvasx
, point
.canvasy
);
377 strategy
.endSegment();
380 if (drawPoints
|| isIsolated
) {
381 pointsOnLine
.push([point
.canvasx
, point
.canvasy
]);
383 prevCanvasX
= point
.canvasx
;
384 prevCanvasY
= point
.canvasy
;
392 DygraphCanvasRenderer
.prototype._drawLine
= function(ctx
, i
) {
393 var setNames
= this.layout
.setNames
;
394 var setName
= setNames
[i
];
396 var strokeWidth
= this.dygraph_
.attr_("strokeWidth", setName
);
397 var borderWidth
= this.dygraph_
.attr_("strokeBorderWidth", setName
);
398 var drawPointCallback
= this.dygraph_
.attr_("drawPointCallback", setName
) ||
399 Dygraph
.Circles
.DEFAULT
;
401 if (borderWidth
&& strokeWidth
) {
402 this._drawStyledLine(ctx
, i
, setName
,
403 this.dygraph_
.attr_("strokeBorderColor", setName
),
404 strokeWidth
+ 2 * borderWidth
,
405 this.dygraph_
.attr_("strokePattern", setName
),
406 this.dygraph_
.attr_("drawPoints", setName
),
408 this.dygraph_
.attr_("pointSize", setName
));
411 this._drawStyledLine(ctx
, i
, setName
,
412 this.colors
[setName
],
414 this.dygraph_
.attr_("strokePattern", setName
),
415 this.dygraph_
.attr_("drawPoints", setName
),
417 this.dygraph_
.attr_("pointSize", setName
));
421 * Actually draw the lines chart, including error bars.
424 DygraphCanvasRenderer
.prototype._renderLineChart
= function() {
425 var ctx
= this.elementContext
;
426 var errorBars
= this.attr_("errorBars") || this.attr_("customBars");
427 var fillGraph
= this.attr_("fillGraph");
430 var setNames
= this.layout
.setNames
;
431 var setCount
= setNames
.length
;
433 this.colors
= this.dygraph_
.colorsMap_
;
438 // TODO(bhs): this loop is a hot-spot for high-point-count charts. These
439 // transformations can be pushed into the canvas via linear transformation
441 var points
= this.layout
.points
;
442 for (i
= points
.length
; i
--;) {
443 var point
= points
[i
];
444 point
.canvasx
= this.area
.w
* point
.x
+ this.area
.x
;
445 point
.canvasy
= this.area
.h
* point
.y
+ this.area
.y
;
448 // Draw any "fills", i.e. error bars or the filled area under a series.
449 // These must all be drawn before any lines, so that the main lines of a
450 // series are drawn on top.
453 this.dygraph_
.warn("Can't use fillGraph option with error bars");
457 this.drawErrorBars_(points
);
459 } else if (fillGraph
) {
461 this.drawFillBars_(points
);
465 // Drawing the lines.
466 for (i
= 0; i
< setCount
; i
+= 1) {
467 this._drawLine(ctx
, i
);
472 * Draws the shaded error bars/confidence intervals for each series.
473 * This happens before the center lines are drawn, since the center lines
474 * need to be drawn on top of the error bars for all series.
478 DygraphCanvasRenderer
.prototype.drawErrorBars_
= function(points
) {
479 var ctx
= this.elementContext
;
480 var setNames
= this.layout
.setNames
;
481 var setCount
= setNames
.length
;
482 var fillAlpha
= this.attr_('fillAlpha');
483 var stepPlot
= this.attr_('stepPlot');
487 for (var i
= 0; i
< setCount
; i
++) {
488 var setName
= setNames
[i
];
489 var axis
= this.dygraph_
.axisPropertiesForSeries(setName
);
490 var color
= this.colors
[setName
];
492 var firstIndexInSet
= this.layout
.setPointsOffsets
[i
];
493 var setLength
= this.layout
.setPointsLengths
[i
];
495 var iter
= Dygraph
.createIterator(points
, firstIndexInSet
, setLength
,
496 DygraphCanvasRenderer
._getIteratorPredicate(
497 this.attr_("connectSeparatedPoints")));
499 // setup graphics context
502 var prevYs
= [-1, -1];
503 var yscale
= axis
.yscale
;
504 // should be same color as the lines but only 15% opaque.
505 var rgb
= new RGBColor(color
);
507 'rgba(' + rgb
.r
+ ',' + rgb
.g
+ ',' + rgb
.b
+ ',' + fillAlpha
+ ')';
508 ctx
.fillStyle
= err_color
;
510 while (iter
.hasNext
) {
511 var point
= iter
.next();
512 if (point
.name
== setName
) { // TODO(klausw): this is always true
513 if (!Dygraph
.isOK(point
.y
)) {
520 newYs
= [ point
.y_bottom
, point
.y_top
];
523 newYs
= [ point
.y_bottom
, point
.y_top
];
525 newYs
[0] = this.area
.h
* newYs
[0] + this.area
.y
;
526 newYs
[1] = this.area
.h
* newYs
[1] + this.area
.y
;
529 ctx
.moveTo(prevX
, newYs
[0]);
531 ctx
.moveTo(prevX
, prevYs
[0]);
533 ctx
.lineTo(point
.canvasx
, newYs
[0]);
534 ctx
.lineTo(point
.canvasx
, newYs
[1]);
536 ctx
.lineTo(prevX
, newYs
[1]);
538 ctx
.lineTo(prevX
, prevYs
[1]);
543 prevX
= point
.canvasx
;
551 * Draws the shaded regions when "fillGraph" is set. Not to be confused with
556 DygraphCanvasRenderer
.prototype.drawFillBars_
= function(points
) {
557 var ctx
= this.elementContext
;
558 var setNames
= this.layout
.setNames
;
559 var setCount
= setNames
.length
;
560 var fillAlpha
= this.attr_('fillAlpha');
561 var stepPlot
= this.attr_('stepPlot');
562 var stackedGraph
= this.attr_("stackedGraph");
564 var baseline
= {}; // for stacked graphs: baseline for filling
567 // process sets in reverse order (needed for stacked graphs)
568 for (var i
= setCount
- 1; i
>= 0; i
--) {
569 var setName
= setNames
[i
];
570 var color
= this.colors
[setName
];
571 var axis
= this.dygraph_
.axisPropertiesForSeries(setName
);
572 var axisY
= 1.0 + axis
.minyval
* axis
.yscale
;
573 if (axisY
< 0.0) axisY
= 0.0;
574 else if (axisY
> 1.0) axisY
= 1.0;
575 axisY
= this.area
.h
* axisY
+ this.area
.y
;
576 var firstIndexInSet
= this.layout
.setPointsOffsets
[i
];
577 var setLength
= this.layout
.setPointsLengths
[i
];
579 var iter
= Dygraph
.createIterator(points
, firstIndexInSet
, setLength
,
580 DygraphCanvasRenderer
._getIteratorPredicate(
581 this.attr_("connectSeparatedPoints")));
583 // setup graphics context
585 var prevYs
= [-1, -1];
587 var yscale
= axis
.yscale
;
588 // should be same color as the lines but only 15% opaque.
589 var rgb
= new RGBColor(color
);
591 'rgba(' + rgb
.r
+ ',' + rgb
.g
+ ',' + rgb
.b
+ ',' + fillAlpha
+ ')';
592 ctx
.fillStyle
= err_color
;
594 while(iter
.hasNext
) {
595 var point
= iter
.next();
596 if (point
.name
== setName
) { // TODO(klausw): this is always true
597 if (!Dygraph
.isOK(point
.y
)) {
602 currBaseline
= baseline
[point
.canvasx
];
604 if (currBaseline
=== undefined
) {
608 lastY
= currBaseline
[0];
610 lastY
= currBaseline
;
613 newYs
= [ point
.canvasy
, lastY
];
616 // Step plots must keep track of the top and bottom of
617 // the baseline at each point.
618 if(prevYs
[0] === -1) {
619 baseline
[point
.canvasx
] = [ point
.canvasy
, axisY
];
621 baseline
[point
.canvasx
] = [ point
.canvasy
, prevYs
[0] ];
624 baseline
[point
.canvasx
] = point
.canvasy
;
628 newYs
= [ point
.canvasy
, axisY
];
631 ctx
.moveTo(prevX
, prevYs
[0]);
634 ctx
.lineTo(point
.canvasx
, prevYs
[0]);
636 // Draw to the bottom of the baseline
637 ctx
.lineTo(point
.canvasx
, currBaseline
[1]);
639 ctx
.lineTo(point
.canvasx
, newYs
[1]);
642 ctx
.lineTo(point
.canvasx
, newYs
[0]);
643 ctx
.lineTo(point
.canvasx
, newYs
[1]);
646 ctx
.lineTo(prevX
, prevYs
[1]);
650 prevX
= point
.canvasx
;
658 * This does dashed lines onto a canvas for a given pattern. You must call
659 * ctx.stroke() after to actually draw it, much line ctx.lineTo(). It remembers
660 * the state of the line in regards to where we left off on drawing the pattern.
661 * You can draw a dashed line in several function calls and the pattern will be
662 * continous as long as you didn't call this function with a different pattern
664 * @param ctx The canvas 2d context to draw on.
665 * @param x The start of the line's x coordinate.
666 * @param y The start of the line's y coordinate.
667 * @param x2 The end of the line's x coordinate.
668 * @param y2 The end of the line's y coordinate.
669 * @param pattern The dash pattern to draw, an array of integers where even
670 * index is drawn and odd index is not drawn (Ex. [10, 2, 5, 2], 10 is drawn 5
671 * is drawn, 2 is the space between.). A null pattern, array of length one, or
672 * empty array will do just a solid line.
675 DygraphCanvasRenderer
.prototype._dashedLine
= function(ctx
, x
, y
, x2
, y2
, pattern
) {
676 // Original version http://stackoverflow.com/questions
/4576724/dotted-stroke
-in-canvas
677 // Modified by Russell Valentine to keep line history and continue the pattern
678 // where it left off.
679 var dx
, dy
, len
, rot
, patternIndex
, segment
;
681 // If we don't have a pattern or it is an empty array or of size one just
683 if (!pattern
|| pattern
.length
<= 1) {
689 // If we have a different dash pattern than the last time this was called we
690 // reset our dash history and start the pattern from the begging
691 // regardless of state of the last pattern.
692 if (!Dygraph
.compareArrays(pattern
, this._dashedLineToHistoryPattern
)) {
693 this._dashedLineToHistoryPattern
= pattern
;
694 this._dashedLineToHistory
= [0, 0];
698 // Calculate transformation parameters
701 len
= Math
.sqrt(dx
*dx
+ dy
*dy
);
702 rot
= Math
.atan2(dy
, dx
);
704 // Set transformation
709 // Set last pattern index we used for this pattern.
710 patternIndex
= this._dashedLineToHistory
[0];
713 // Get the length of the pattern segment we are dealing with.
714 segment
= pattern
[patternIndex
];
715 // If our last draw didn't complete the pattern segment all the way we
716 // will try to finish it. Otherwise we will try to do the whole segment.
717 if (this._dashedLineToHistory
[1]) {
718 x
+= this._dashedLineToHistory
[1];
723 // We were unable to complete this pattern index all the way, keep
724 // where we are the history so our next draw continues where we left off
726 this._dashedLineToHistory
= [patternIndex
, x
-len
];
729 // We completed this patternIndex, we put in the history that we are on
730 // the beginning of the next segment.
731 this._dashedLineToHistory
= [(patternIndex
+1)%pattern
.length
, 0];
734 // We do a line on a even pattern index and just move on a odd pattern index.
735 // The move is the empty space in the dash.
736 if(patternIndex
% 2 === 0) {
741 // If we are not done, next loop process the next pattern segment, or the
742 // first segment again if we are at the end of the pattern.
743 patternIndex
= (patternIndex
+1) % pattern
.length
;