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 * @param { [String] } colors Array of color strings. Should have one entry for
149 * each series to be rendered.
151 DygraphCanvasRenderer
.prototype.setColors
= function(colors
) {
152 this.colorScheme_
= colors
;
156 * This method is responsible for drawing everything on the chart, including
157 * lines, error bars, fills and axes.
158 * It is called immediately after clear() on every frame, including during pans
162 DygraphCanvasRenderer
.prototype.render
= function() {
163 // Draw the new X/Y grid
. Lines appear crisper when pixels are rounded to
164 // half-integers. This prevents them from drawing in two rows/cols.
165 var ctx
= this.elementContext
;
166 function halfUp(x
) { return Math
.round(x
) + 0.5; }
167 function halfDown(y
){ return Math
.round(y
) - 0.5; }
169 if (this.attr_('underlayCallback')) {
170 // NOTE: we pass the dygraph object to this callback twice to avoid breaking
171 // users who expect a deprecated form of this callback.
172 this.attr_('underlayCallback')(ctx
, this.area
, this.dygraph_
, this.dygraph_
);
175 // Do the ordinary rendering, as before
176 this._renderLineChart();
179 DygraphCanvasRenderer
.prototype._createIEClipArea
= function() {
180 var className
= 'dygraph-clip-div';
181 var graphDiv
= this.dygraph_
.graphDiv
;
183 // Remove old clip divs.
184 for (var i
= graphDiv
.childNodes
.length
-1; i
>= 0; i
--) {
185 if (graphDiv
.childNodes
[i
].className
== className
) {
186 graphDiv
.removeChild(graphDiv
.childNodes
[i
]);
190 // Determine background color to give clip divs.
191 var backgroundColor
= document
.bgColor
;
192 var element
= this.dygraph_
.graphDiv
;
193 while (element
!= document
) {
194 var bgcolor
= element
.currentStyle
.backgroundColor
;
195 if (bgcolor
&& bgcolor
!= 'transparent') {
196 backgroundColor
= bgcolor
;
199 element
= element
.parentNode
;
202 function createClipDiv(area
) {
203 if (area
.w
=== 0 || area
.h
=== 0) {
206 var elem
= document
.createElement('div');
207 elem
.className
= className
;
208 elem
.style
.backgroundColor
= backgroundColor
;
209 elem
.style
.position
= 'absolute';
210 elem
.style
.left
= area
.x
+ 'px';
211 elem
.style
.top
= area
.y
+ 'px';
212 elem
.style
.width
= area
.w
+ 'px';
213 elem
.style
.height
= area
.h
+ 'px';
214 graphDiv
.appendChild(elem
);
217 var plotArea
= this.area
;
228 w
: this.width
- plotArea
.x
,
234 x
: plotArea
.x
+ plotArea
.w
, y
: 0,
235 w
: this.width
-plotArea
.x
- plotArea
.w
,
242 y
: plotArea
.y
+ plotArea
.h
,
243 w
: this.width
- plotArea
.x
,
244 h
: this.height
- plotArea
.h
- plotArea
.y
250 * Returns a predicate to be used with an iterator, which will
251 * iterate over points appropriately, depending on whether
252 * connectSeparatedPoints is true. When it's false, the predicate will
253 * skip over points with missing yVals.
255 DygraphCanvasRenderer
._getIteratorPredicate
= function(connectSeparatedPoints
) {
256 return connectSeparatedPoints
? DygraphCanvasRenderer
._predicateThatSkipsEmptyPoints
: null;
259 DygraphCanvasRenderer
._predicateThatSkipsEmptyPoints
=
260 function(array
, idx
) { return array
[idx
].yval
!== null; }
262 DygraphCanvasRenderer
.prototype._drawStyledLine
= function(
263 ctx
, i
, setName
, color
, strokeWidth
, strokePattern
, drawPoints
,
264 drawPointCallback
, pointSize
) {
265 // TODO(konigsberg): Compute attributes outside this method call.
266 var stepPlot
= this.attr_("stepPlot");
267 var firstIndexInSet
= this.layout
.setPointsOffsets
[i
];
268 var setLength
= this.layout
.setPointsLengths
[i
];
269 var points
= this.layout
.points
;
270 if (!Dygraph
.isArrayLike(strokePattern
)) {
271 strokePattern
= null;
273 var drawGapPoints
= this.dygraph_
.attr_('drawGapEdgePoints', setName
);
277 var iter
= Dygraph
.createIterator(points
, firstIndexInSet
, setLength
,
278 DygraphCanvasRenderer
._getIteratorPredicate(this.attr_("connectSeparatedPoints")));
282 if (!strokePattern
|| strokePattern
.length
<= 1) {
283 strategy
= trivialStrategy(ctx
, color
, strokeWidth
);
285 strategy
= nonTrivialStrategy(this, ctx
, color
, strokeWidth
, strokePattern
);
287 pointsOnLine
= this._drawSeries(ctx
, iter
, strokeWidth
, pointSize
, drawPoints
, drawGapPoints
, stepPlot
, strategy
);
288 this._drawPointsOnLine(ctx
, pointsOnLine
, drawPointCallback
, setName
, color
, pointSize
);
293 var nonTrivialStrategy
= function(renderer
, ctx
, color
, strokeWidth
, strokePattern
) {
294 return new function() {
295 this.init
= function() { };
296 this.finish
= function() { };
297 this.startSegment
= function() {
299 ctx
.strokeStyle
= color
;
300 ctx
.lineWidth
= strokeWidth
;
302 this.endSegment
= function() {
303 ctx
.stroke(); // should this include closePath?
305 this.drawLine
= function(x1
, y1
, x2
, y2
) {
306 renderer
._dashedLine(ctx
, x1
, y1
, x2
, y2
, strokePattern
);
308 this.skipPixel
= function(prevX
, prevY
, curX
, curY
) {
309 // TODO(konigsberg): optimize with http://jsperf.com/math-round
-vs
-hack
/6 ?
310 return (Math
.round(prevX
) == Math
.round(curX
) &&
311 Math
.round(prevY
) == Math
.round(curY
));
316 var trivialStrategy
= function(ctx
, color
, strokeWidth
) {
317 return new function() {
318 this.init
= function() {
320 ctx
.strokeStyle
= color
;
321 ctx
.lineWidth
= strokeWidth
;
323 this.finish
= function() {
324 ctx
.stroke(); // should this include closePath?
326 this.startSegment
= function() { };
327 this.endSegment
= function() { };
328 this.drawLine
= function(x1
, y1
, x2
, y2
) {
332 // don't skip pixels.
333 this.skipPixel
= function() {
339 DygraphCanvasRenderer
.prototype._drawPointsOnLine
= function(ctx
, pointsOnLine
, drawPointCallback
, setName
, color
, pointSize
) {
340 for (var idx
= 0; idx
< pointsOnLine
.length
; idx
++) {
341 var cb
= pointsOnLine
[idx
];
344 this.dygraph_
, setName
, ctx
, cb
[0], cb
[1], color
, pointSize
);
349 DygraphCanvasRenderer
.prototype._drawSeries
= function(
350 ctx
, iter
, strokeWidth
, pointSize
, drawPoints
, drawGapPoints
,
351 stepPlot
, strategy
) {
353 var prevCanvasX
= null;
354 var prevCanvasY
= null;
355 var nextCanvasY
= null;
356 var isIsolated
; // true if this point is isolated (no line segments)
357 var point
; // the point being processed in the while loop
358 var pointsOnLine
= []; // Array of [canvasx, canvasy] pairs.
359 var first
= true; // the first cycle through the while loop
363 while(iter
.hasNext()) {
365 if (point
.canvasy
=== null || point
.canvasy
!= point
.canvasy
) {
366 if (stepPlot
&& prevCanvasX
!== null) {
367 // Draw a horizontal line to the start of the missing data
368 strategy
.startSegment();
369 strategy
.drawLine(prevX
, prevY
, point
.canvasx
, prevY
);
370 strategy
.endSegment();
372 prevCanvasX
= prevCanvasY
= null;
374 nextCanvasY
= iter
.hasNext() ? iter
.peek().canvasy
: null;
375 // TODO: we calculate isNullOrNaN for this point, and the next, and then, when
376 // we iterate, test for isNullOrNaN again. Why bother?
377 var isNextCanvasYNullOrNaN
= nextCanvasY
=== null || nextCanvasY
!= nextCanvasY
;
378 isIsolated
= (!prevCanvasX
&& isNextCanvasYNullOrNaN
);
380 // Also consider a point to be "isolated" if it's adjacent to a
381 // null point, excluding the graph edges.
382 if ((!first
&& !prevCanvasX
) ||
383 (iter
.hasNext() && isNextCanvasYNullOrNaN
)) {
387 if (prevCanvasX
!== null) {
388 if (strategy
.skipPixel(prevCanvasX
, prevCanvasY
, point
.canvasx
, point
.canvasy
)) {
392 strategy
.startSegment();
394 strategy
.drawLine(prevCanvasX
, prevCanvasY
, point
.canvasx
, prevCanvasY
);
395 prevCanvasX
= point
.canvasx
;
397 strategy
.drawLine(prevCanvasX
, prevCanvasY
, point
.canvasx
, point
.canvasy
);
398 strategy
.endSegment();
401 if (drawPoints
|| isIsolated
) {
402 pointsOnLine
.push([point
.canvasx
, point
.canvasy
]);
404 prevCanvasX
= point
.canvasx
;
405 prevCanvasY
= point
.canvasy
;
413 DygraphCanvasRenderer
.prototype._drawLine
= function(ctx
, i
) {
414 var setNames
= this.layout
.setNames
;
415 var setName
= setNames
[i
];
417 var strokeWidth
= this.dygraph_
.attr_("strokeWidth", setName
);
418 var borderWidth
= this.dygraph_
.attr_("strokeBorderWidth", setName
);
419 var drawPointCallback
= this.dygraph_
.attr_("drawPointCallback", setName
) ||
420 Dygraph
.Circles
.DEFAULT
;
422 if (borderWidth
&& strokeWidth
) {
423 this._drawStyledLine(ctx
, i
, setName
,
424 this.dygraph_
.attr_("strokeBorderColor", setName
),
425 strokeWidth
+ 2 * borderWidth
,
426 this.dygraph_
.attr_("strokePattern", setName
),
427 this.dygraph_
.attr_("drawPoints", setName
),
429 this.dygraph_
.attr_("pointSize", setName
));
432 this._drawStyledLine(ctx
, i
, setName
,
433 this.colors
[setName
],
435 this.dygraph_
.attr_("strokePattern", setName
),
436 this.dygraph_
.attr_("drawPoints", setName
),
438 this.dygraph_
.attr_("pointSize", setName
));
442 * Actually draw the lines chart, including error bars.
443 * TODO(danvk): split this into several smaller functions.
446 DygraphCanvasRenderer
.prototype._renderLineChart
= function() {
447 // TODO(danvk): use this.attr_ for many of these.
448 var ctx
= this.elementContext
;
449 var fillAlpha
= this.attr_('fillAlpha');
450 var errorBars
= this.attr_("errorBars") || this.attr_("customBars");
451 var fillGraph
= this.attr_("fillGraph");
452 var stackedGraph
= this.attr_("stackedGraph");
453 var stepPlot
= this.attr_("stepPlot");
454 var points
= this.layout
.points
;
455 var pointsLength
= points
.length
;
456 var point
, i
, prevX
, prevY
, prevYs
, color
, setName
, newYs
, err_color
, rgb
, yscale
, axis
;
458 var setNames
= this.layout
.setNames
;
459 var setCount
= setNames
.length
;
461 this.colors
= this.dygraph_
.colorsMap_
;
466 // TODO(bhs): this loop is a hot-spot for high-point-count charts. These
467 // transformations can be pushed into the canvas via linear transformation
469 for (i
= pointsLength
; i
--;) {
471 point
.canvasx
= this.area
.w
* point
.x
+ this.area
.x
;
472 point
.canvasy
= this.area
.h
* point
.y
+ this.area
.y
;
479 this.dygraph_
.warn("Can't use fillGraph option with error bars");
482 for (i
= 0; i
< setCount
; i
++) {
483 setName
= setNames
[i
];
484 axis
= this.dygraph_
.axisPropertiesForSeries(setName
);
485 color
= this.colors
[setName
];
487 var firstIndexInSet
= this.layout
.setPointsOffsets
[i
];
488 var setLength
= this.layout
.setPointsLengths
[i
];
490 var iter
= Dygraph
.createIterator(points
, firstIndexInSet
, setLength
,
491 DygraphCanvasRenderer
._getIteratorPredicate(this.attr_("connectSeparatedPoints")));
493 // setup graphics context
497 yscale
= axis
.yscale
;
498 // should be same color as the lines but only 15% opaque.
499 rgb
= new RGBColor(color
);
500 err_color
= 'rgba(' + rgb
.r
+ ',' + rgb
.g
+ ',' + rgb
.b
+ ',' +
502 ctx
.fillStyle
= err_color
;
504 while (iter
.hasNext()) {
506 if (point
.name
== setName
) { // TODO(klausw): this is always true
507 if (!Dygraph
.isOK(point
.y
)) {
514 newYs
= [ point
.y_bottom
, point
.y_top
];
517 newYs
= [ point
.y_bottom
, point
.y_top
];
519 newYs
[0] = this.area
.h
* newYs
[0] + this.area
.y
;
520 newYs
[1] = this.area
.h
* newYs
[1] + this.area
.y
;
523 ctx
.moveTo(prevX
, newYs
[0]);
525 ctx
.moveTo(prevX
, prevYs
[0]);
527 ctx
.lineTo(point
.canvasx
, newYs
[0]);
528 ctx
.lineTo(point
.canvasx
, newYs
[1]);
530 ctx
.lineTo(prevX
, newYs
[1]);
532 ctx
.lineTo(prevX
, prevYs
[1]);
537 prevX
= point
.canvasx
;
543 } else if (fillGraph
) {
545 var baseline
= {}; // for stacked graphs: baseline for filling
548 // process sets in reverse order (needed for stacked graphs)
549 for (i
= setCount
- 1; i
>= 0; i
--) {
550 setName
= setNames
[i
];
551 color
= this.colors
[setName
];
552 axis
= this.dygraph_
.axisPropertiesForSeries(setName
);
553 var axisY
= 1.0 + axis
.minyval
* axis
.yscale
;
554 if (axisY
< 0.0) axisY
= 0.0;
555 else if (axisY
> 1.0) axisY
= 1.0;
556 axisY
= this.area
.h
* axisY
+ this.area
.y
;
557 var firstIndexInSet
= this.layout
.setPointsOffsets
[i
];
558 var setLength
= this.layout
.setPointsLengths
[i
];
560 var iter
= Dygraph
.createIterator(points
, firstIndexInSet
, setLength
,
561 DygraphCanvasRenderer
._getIteratorPredicate(this.attr_("connectSeparatedPoints")));
563 // setup graphics context
566 yscale
= axis
.yscale
;
567 // should be same color as the lines but only 15% opaque.
568 rgb
= new RGBColor(color
);
569 err_color
= 'rgba(' + rgb
.r
+ ',' + rgb
.g
+ ',' + rgb
.b
+ ',' +
571 ctx
.fillStyle
= err_color
;
573 while(iter
.hasNext()) {
575 if (point
.name
== setName
) { // TODO(klausw): this is always true
576 if (!Dygraph
.isOK(point
.y
)) {
581 currBaseline
= baseline
[point
.canvasx
];
583 if (currBaseline
=== undefined
) {
587 lastY
= currBaseline
[0];
589 lastY
= currBaseline
;
592 newYs
= [ point
.canvasy
, lastY
];
595 // Step plots must keep track of the top and bottom of
596 // the baseline at each point.
597 if(prevYs
[0] === -1) {
598 baseline
[point
.canvasx
] = [ point
.canvasy
, axisY
];
600 baseline
[point
.canvasx
] = [ point
.canvasy
, prevYs
[0] ];
603 baseline
[point
.canvasx
] = point
.canvasy
;
607 newYs
= [ point
.canvasy
, axisY
];
610 ctx
.moveTo(prevX
, prevYs
[0]);
613 ctx
.lineTo(point
.canvasx
, prevYs
[0]);
615 // Draw to the bottom of the baseline
616 ctx
.lineTo(point
.canvasx
, currBaseline
[1]);
618 ctx
.lineTo(point
.canvasx
, newYs
[1]);
621 ctx
.lineTo(point
.canvasx
, newYs
[0]);
622 ctx
.lineTo(point
.canvasx
, newYs
[1]);
625 ctx
.lineTo(prevX
, prevYs
[1]);
629 prevX
= point
.canvasx
;
637 // Drawing the lines.
638 for (i
= 0; i
< setCount
; i
+= 1) {
639 this._drawLine(ctx
, i
);
644 * This does dashed lines onto a canvas for a given pattern. You must call
645 * ctx.stroke() after to actually draw it, much line ctx.lineTo(). It remembers
646 * the state of the line in regards to where we left off on drawing the pattern.
647 * You can draw a dashed line in several function calls and the pattern will be
648 * continous as long as you didn't call this function with a different pattern
650 * @param ctx The canvas 2d context to draw on.
651 * @param x The start of the line's x coordinate.
652 * @param y The start of the line's y coordinate.
653 * @param x2 The end of the line's x coordinate.
654 * @param y2 The end of the line's y coordinate.
655 * @param pattern The dash pattern to draw, an array of integers where even
656 * index is drawn and odd index is not drawn (Ex. [10, 2, 5, 2], 10 is drawn 5
657 * is drawn, 2 is the space between.). A null pattern, array of length one, or
658 * empty array will do just a solid line.
661 DygraphCanvasRenderer
.prototype._dashedLine
= function(ctx
, x
, y
, x2
, y2
, pattern
) {
662 // Original version http://stackoverflow.com/questions
/4576724/dotted-stroke
-in-canvas
663 // Modified by Russell Valentine to keep line history and continue the pattern
664 // where it left off.
665 var dx
, dy
, len
, rot
, patternIndex
, segment
;
667 // If we don't have a pattern or it is an empty array or of size one just
669 if (!pattern
|| pattern
.length
<= 1) {
675 // If we have a different dash pattern than the last time this was called we
676 // reset our dash history and start the pattern from the begging
677 // regardless of state of the last pattern.
678 if (!Dygraph
.compareArrays(pattern
, this._dashedLineToHistoryPattern
)) {
679 this._dashedLineToHistoryPattern
= pattern
;
680 this._dashedLineToHistory
= [0, 0];
684 // Calculate transformation parameters
687 len
= Math
.sqrt(dx
*dx
+ dy
*dy
);
688 rot
= Math
.atan2(dy
, dx
);
690 // Set transformation
695 // Set last pattern index we used for this pattern.
696 patternIndex
= this._dashedLineToHistory
[0];
699 // Get the length of the pattern segment we are dealing with.
700 segment
= pattern
[patternIndex
];
701 // If our last draw didn't complete the pattern segment all the way we
702 // will try to finish it. Otherwise we will try to do the whole segment.
703 if (this._dashedLineToHistory
[1]) {
704 x
+= this._dashedLineToHistory
[1];
709 // We were unable to complete this pattern index all the way, keep
710 // where we are the history so our next draw continues where we left off
712 this._dashedLineToHistory
= [patternIndex
, x
-len
];
715 // We completed this patternIndex, we put in the history that we are on
716 // the beginning of the next segment.
717 this._dashedLineToHistory
= [(patternIndex
+1)%pattern
.length
, 0];
720 // We do a line on a even pattern index and just move on a odd pattern index.
721 // The move is the empty space in the dash.
722 if(patternIndex
% 2 === 0) {
727 // If we are not done, next loop process the next pattern segment, or the
728 // first segment again if we are at the end of the pattern.
729 patternIndex
= (patternIndex
+1) % pattern
.length
;