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.";
67 this.annotations
= [];
69 this.area
= layout
.getPlotArea();
70 this.container
.style
.position
= "relative";
71 this.container
.style
.width
= this.width
+ "px";
73 // Set up a clipping area for the canvas (and the interaction canvas).
74 // This ensures that we don't overdraw.
75 if (this.dygraph_
.isUsingExcanvas_
) {
76 this._createIEClipArea();
78 // on Android 3 and 4, setting a clipping area on a canvas prevents it from
79 // displaying anything.
80 if (!Dygraph
.isAndroid()) {
81 var ctx
= this.dygraph_
.canvas_ctx_
;
83 ctx
.rect(this.area
.x
, this.area
.y
, this.area
.w
, this.area
.h
);
86 ctx
= this.dygraph_
.hidden_ctx_
;
88 ctx
.rect(this.area
.x
, this.area
.y
, this.area
.w
, this.area
.h
);
94 DygraphCanvasRenderer
.prototype.attr_
= function(x
) {
95 return this.dygraph_
.attr_(x
);
99 * Clears out all chart content and DOM elements.
100 * This is called immediately before render() on every frame, including
101 * during zooms and pans.
104 DygraphCanvasRenderer
.prototype.clear
= function() {
107 // VML takes a while to start up, so we just poll every this.IEDelay
109 if (this.clearDelay
) {
110 this.clearDelay
.cancel();
111 this.clearDelay
= null;
113 context
= this.elementContext
;
116 // TODO(danvk): this is broken, since MochiKit.Async is gone.
117 // this.clearDelay = MochiKit.Async.wait(this.IEDelay);
118 // this.clearDelay.addCallback(bind(this.clear, this));
123 context
= this.elementContext
;
124 context
.clearRect(0, 0, this.width
, this.height
);
126 function removeArray(ary
) {
127 for (var i
= 0; i
< ary
.length
; i
++) {
129 if (el
.parentNode
) el
.parentNode
.removeChild(el
);
133 removeArray(this.xlabels
);
134 removeArray(this.ylabels
);
135 removeArray(this.annotations
);
139 this.annotations
= [];
143 * Checks whether the browser supports the <canvas> tag.
146 DygraphCanvasRenderer
.isSupported
= function(canvasName
) {
149 if (typeof(canvasName
) == 'undefined' || canvasName
=== null) {
150 canvas
= document
.createElement("canvas");
154 canvas
.getContext("2d");
157 var ie
= navigator
.appVersion
.match(/MSIE (\d\.\d)/);
158 var opera
= (navigator
.userAgent
.toLowerCase().indexOf("opera") != -1);
159 if ((!ie
) || (ie
[1] < 6) || (opera
))
167 * @param { [String] } colors Array of color strings. Should have one entry for
168 * each series to be rendered.
170 DygraphCanvasRenderer
.prototype.setColors
= function(colors
) {
171 this.colorScheme_
= colors
;
175 * This method is responsible for drawing everything on the chart, including
176 * lines, error bars, fills and axes.
177 * It is called immediately after clear() on every frame, including during pans
181 DygraphCanvasRenderer
.prototype.render
= function() {
182 // Draw the new X/Y grid
. Lines appear crisper when pixels are rounded to
183 // half-integers. This prevents them from drawing in two rows/cols.
184 var ctx
= this.elementContext
;
185 function halfUp(x
) { return Math
.round(x
) + 0.5; }
186 function halfDown(y
){ return Math
.round(y
) - 0.5; }
188 if (this.attr_('underlayCallback')) {
189 // NOTE: we pass the dygraph object to this callback twice to avoid breaking
190 // users who expect a deprecated form of this callback.
191 this.attr_('underlayCallback')(ctx
, this.area
, this.dygraph_
, this.dygraph_
);
195 if (this.attr_('drawYGrid')) {
196 ticks
= this.layout
.yticks
;
197 // TODO(konigsberg): I don't think these calls to save() have a corresponding restore().
199 ctx
.strokeStyle
= this.attr_('gridLineColor');
200 ctx
.lineWidth
= this.attr_('gridLineWidth');
201 for (i
= 0; i
< ticks
.length
; i
++) {
202 // TODO(danvk): allow secondary axes to draw a grid, too.
203 if (ticks
[i
][0] !== 0) continue;
204 x
= halfUp(this.area
.x
);
205 y
= halfDown(this.area
.y
+ ticks
[i
][1] * this.area
.h
);
208 ctx
.lineTo(x
+ this.area
.w
, y
);
215 if (this.attr_('drawXGrid')) {
216 ticks
= this.layout
.xticks
;
218 ctx
.strokeStyle
= this.attr_('gridLineColor');
219 ctx
.lineWidth
= this.attr_('gridLineWidth');
220 for (i
=0; i
<ticks
.length
; i
++) {
221 x
= halfUp(this.area
.x
+ ticks
[i
][0] * this.area
.w
);
222 y
= halfDown(this.area
.y
+ this.area
.h
);
225 ctx
.lineTo(x
, this.area
.y
);
232 // Do the ordinary rendering, as before
233 this._renderLineChart();
237 DygraphCanvasRenderer
.prototype._createIEClipArea
= function() {
238 var className
= 'dygraph-clip-div';
239 var graphDiv
= this.dygraph_
.graphDiv
;
241 // Remove old clip divs.
242 for (var i
= graphDiv
.childNodes
.length
-1; i
>= 0; i
--) {
243 if (graphDiv
.childNodes
[i
].className
== className
) {
244 graphDiv
.removeChild(graphDiv
.childNodes
[i
]);
248 // Determine background color to give clip divs.
249 var backgroundColor
= document
.bgColor
;
250 var element
= this.dygraph_
.graphDiv
;
251 while (element
!= document
) {
252 var bgcolor
= element
.currentStyle
.backgroundColor
;
253 if (bgcolor
&& bgcolor
!= 'transparent') {
254 backgroundColor
= bgcolor
;
257 element
= element
.parentNode
;
260 function createClipDiv(area
) {
261 if (area
.w
=== 0 || area
.h
=== 0) {
264 var elem
= document
.createElement('div');
265 elem
.className
= className
;
266 elem
.style
.backgroundColor
= backgroundColor
;
267 elem
.style
.position
= 'absolute';
268 elem
.style
.left
= area
.x
+ 'px';
269 elem
.style
.top
= area
.y
+ 'px';
270 elem
.style
.width
= area
.w
+ 'px';
271 elem
.style
.height
= area
.h
+ 'px';
272 graphDiv
.appendChild(elem
);
275 var plotArea
= this.area
;
286 w
: this.width
- plotArea
.x
,
292 x
: plotArea
.x
+ plotArea
.w
, y
: 0,
293 w
: this.width
-plotArea
.x
- plotArea
.w
,
300 y
: plotArea
.y
+ plotArea
.h
,
301 w
: this.width
- plotArea
.x
,
302 h
: this.height
- plotArea
.h
- plotArea
.y
306 DygraphCanvasRenderer
.prototype._renderAxis
= function() {
307 if (!this.attr_('drawXAxis') && !this.attr_('drawYAxis')) return;
309 // Round pixels to half-integer boundaries for crisper drawing.
310 function halfUp(x
) { return Math
.round(x
) + 0.5; }
311 function halfDown(y
){ return Math
.round(y
) - 0.5; }
313 var context
= this.elementContext
;
315 var label
, x
, y
, tick
, i
;
318 position
: "absolute",
319 fontSize
: this.attr_('axisLabelFontSize') + "px",
321 color
: this.attr_('axisLabelColor'),
322 width
: this.attr_('axisLabelWidth') + "px",
323 // height: this.attr_('axisLabelFontSize') + 2 + "px",
324 lineHeight
: "normal", // Something other than "normal" line-height screws up label positioning.
327 var makeDiv
= function(txt
, axis
, prec_axis
) {
328 var div
= document
.createElement("div");
329 for (var name
in labelStyle
) {
330 if (labelStyle
.hasOwnProperty(name
)) {
331 div
.style
[name
] = labelStyle
[name
];
334 var inner_div
= document
.createElement("div");
335 inner_div
.className
= 'dygraph-axis-label' +
336 ' dygraph-axis-label-' + axis
+
337 (prec_axis
? ' dygraph-axis-label-' + prec_axis
: '');
338 inner_div
.innerHTML
=txt
;
339 div
.appendChild(inner_div
);
345 context
.strokeStyle
= this.attr_('axisLineColor');
346 context
.lineWidth
= this.attr_('axisLineWidth');
348 if (this.attr_('drawYAxis')) {
349 if (this.layout
.yticks
&& this.layout
.yticks
.length
> 0) {
350 var num_axes
= this.dygraph_
.numAxes();
351 for (i
= 0; i
< this.layout
.yticks
.length
; i
++) {
352 tick
= this.layout
.yticks
[i
];
353 if (typeof(tick
) == "function") return;
356 var prec_axis
= 'y1';
357 if (tick
[0] == 1) { // right-side y-axis
358 x
= this.area
.x
+ this.area
.w
;
362 y
= this.area
.y
+ tick
[1] * this.area
.h
;
364 /* Tick marks are currently clipped, so don't bother drawing them.
366 context.moveTo(halfUp(x), halfDown(y));
367 context.lineTo(halfUp(x - sgn * this.attr_('axisTickSize')), halfDown(y));
372 label
= makeDiv(tick
[2], 'y', num_axes
== 2 ? prec_axis
: null);
373 var top
= (y
- this.attr_('axisLabelFontSize') / 2);
374 if (top
< 0) top
= 0;
376 if (top
+ this.attr_('axisLabelFontSize') + 3 > this.height
) {
377 label
.style
.bottom
= "0px";
379 label
.style
.top
= top
+ "px";
382 label
.style
.left
= (this.area
.x
- this.attr_('yAxisLabelWidth') - this.attr_('axisTickSize')) + "px";
383 label
.style
.textAlign
= "right";
384 } else if (tick
[0] == 1) {
385 label
.style
.left
= (this.area
.x
+ this.area
.w
+
386 this.attr_('axisTickSize')) + "px";
387 label
.style
.textAlign
= "left";
389 label
.style
.width
= this.attr_('yAxisLabelWidth') + "px";
390 this.container
.appendChild(label
);
391 this.ylabels
.push(label
);
394 // The lowest tick on the y-axis often overlaps with the leftmost
395 // tick on the x-axis. Shift the bottom tick up a little bit to
396 // compensate if necessary.
397 var bottomTick
= this.ylabels
[0];
398 var fontSize
= this.attr_('axisLabelFontSize');
399 var bottom
= parseInt(bottomTick
.style
.top
, 10) + fontSize
;
400 if (bottom
> this.height
- fontSize
) {
401 bottomTick
.style
.top
= (parseInt(bottomTick
.style
.top
, 10) -
402 fontSize
/ 2) + "px";
406 // draw a vertical line on the left to separate the chart from the labels.
408 if (this.attr_('drawAxesAtZero')) {
409 var r
= this.dygraph_
.toPercentXCoord(0);
410 if (r
> 1 || r
< 0) r
= 0;
411 axisX
= halfUp(this.area
.x
+ r
* this.area
.w
);
413 axisX
= halfUp(this.area
.x
);
416 context
.moveTo(axisX
, halfDown(this.area
.y
));
417 context
.lineTo(axisX
, halfDown(this.area
.y
+ this.area
.h
));
421 // if there's a secondary y-axis, draw a vertical line for that, too.
422 if (this.dygraph_
.numAxes() == 2) {
424 context
.moveTo(halfDown(this.area
.x
+ this.area
.w
), halfDown(this.area
.y
));
425 context
.lineTo(halfDown(this.area
.x
+ this.area
.w
), halfDown(this.area
.y
+ this.area
.h
));
431 if (this.attr_('drawXAxis')) {
432 if (this.layout
.xticks
) {
433 for (i
= 0; i
< this.layout
.xticks
.length
; i
++) {
434 tick
= this.layout
.xticks
[i
];
435 x
= this.area
.x
+ tick
[0] * this.area
.w
;
436 y
= this.area
.y
+ this.area
.h
;
438 /* Tick marks are currently clipped, so don't bother drawing them.
440 context.moveTo(halfUp(x), halfDown(y));
441 context.lineTo(halfUp(x), halfDown(y + this.attr_('axisTickSize')));
446 label
= makeDiv(tick
[1], 'x');
447 label
.style
.textAlign
= "center";
448 label
.style
.top
= (y
+ this.attr_('axisTickSize')) + 'px';
450 var left
= (x
- this.attr_('axisLabelWidth')/2);
451 if (left
+ this.attr_('axisLabelWidth') > this.width
) {
452 left
= this.width
- this.attr_('xAxisLabelWidth');
453 label
.style
.textAlign
= "right";
457 label
.style
.textAlign
= "left";
460 label
.style
.left
= left
+ "px";
461 label
.style
.width
= this.attr_('xAxisLabelWidth') + "px";
462 this.container
.appendChild(label
);
463 this.xlabels
.push(label
);
469 if (this.attr_('drawAxesAtZero')) {
470 var r
= this.dygraph_
.toPercentYCoord(0, 0);
471 if (r
> 1 || r
< 0) r
= 1;
472 axisY
= halfDown(this.area
.y
+ r
* this.area
.h
);
474 axisY
= halfDown(this.area
.y
+ this.area
.h
);
476 context
.moveTo(halfUp(this.area
.x
), axisY
);
477 context
.lineTo(halfUp(this.area
.x
+ this.area
.w
), axisY
);
487 * Returns a predicate to be used with an iterator, which will
488 * iterate over points appropriately, depending on whether
489 * connectSeparatedPoints is true. When it's false, the predicate will
490 * skip over points with missing yVals.
492 DygraphCanvasRenderer
._getIteratorPredicate
= function(connectSeparatedPoints
) {
493 return connectSeparatedPoints
? DygraphCanvasRenderer
._predicateThatSkipsEmptyPoints
: null;
496 DygraphCanvasRenderer
._predicateThatSkipsEmptyPoints
=
497 function(array
, idx
) { return array
[idx
].yval
!== null; }
499 DygraphCanvasRenderer
.prototype._drawStyledLine
= function(
500 ctx
, i
, setName
, color
, strokeWidth
, strokePattern
, drawPoints
,
501 drawPointCallback
, pointSize
) {
502 // TODO(konigsberg): Compute attributes outside this method call.
503 var stepPlot
= this.attr_("stepPlot");
504 var firstIndexInSet
= this.layout
.setPointsOffsets
[i
];
505 var setLength
= this.layout
.setPointsLengths
[i
];
506 var points
= this.layout
.points
;
507 if (!Dygraph
.isArrayLike(strokePattern
)) {
508 strokePattern
= null;
510 var drawGapPoints
= this.dygraph_
.attr_('drawGapEdgePoints', setName
);
514 var iter
= Dygraph
.createIterator(points
, firstIndexInSet
, setLength
,
515 DygraphCanvasRenderer
._getIteratorPredicate(this.attr_("connectSeparatedPoints")));
519 if (!strokePattern
|| strokePattern
.length
<= 1) {
520 strategy
= trivialStrategy(ctx
, color
, strokeWidth
);
522 strategy
= nonTrivialStrategy(this, ctx
, color
, strokeWidth
, strokePattern
);
524 pointsOnLine
= this._drawSeries(ctx
, iter
, strokeWidth
, pointSize
, drawPoints
, drawGapPoints
, stepPlot
, strategy
);
525 this._drawPointsOnLine(ctx
, pointsOnLine
, drawPointCallback
, setName
, color
, pointSize
);
530 var nonTrivialStrategy
= function(renderer
, ctx
, color
, strokeWidth
, strokePattern
) {
531 return new function() {
532 this.init
= function() { };
533 this.finish
= function() { };
534 this.startSegment
= function() {
536 ctx
.strokeStyle
= color
;
537 ctx
.lineWidth
= strokeWidth
;
539 this.endSegment
= function() {
540 ctx
.stroke(); // should this include closePath?
542 this.drawLine
= function(x1
, y1
, x2
, y2
) {
543 renderer
._dashedLine(ctx
, x1
, y1
, x2
, y2
, strokePattern
);
545 this.skipPixel
= function(prevX
, prevY
, curX
, curY
) {
546 // TODO(konigsberg): optimize with http://jsperf.com/math-round
-vs
-hack
/6 ?
547 return (Math
.round(prevX
) == Math
.round(curX
) &&
548 Math
.round(prevY
) == Math
.round(curY
));
553 var trivialStrategy
= function(ctx
, color
, strokeWidth
) {
554 return new function() {
555 this.init
= function() {
557 ctx
.strokeStyle
= color
;
558 ctx
.lineWidth
= strokeWidth
;
560 this.finish
= function() {
561 ctx
.stroke(); // should this include closePath?
563 this.startSegment
= function() { };
564 this.endSegment
= function() { };
565 this.drawLine
= function(x1
, y1
, x2
, y2
) {
569 // don't skip pixels.
570 this.skipPixel
= function() {
576 DygraphCanvasRenderer
.prototype._drawPointsOnLine
= function(ctx
, pointsOnLine
, drawPointCallback
, setName
, color
, pointSize
) {
577 for (var idx
= 0; idx
< pointsOnLine
.length
; idx
++) {
578 var cb
= pointsOnLine
[idx
];
581 this.dygraph_
, setName
, ctx
, cb
[0], cb
[1], color
, pointSize
);
586 DygraphCanvasRenderer
.prototype._drawSeries
= function(
587 ctx
, iter
, strokeWidth
, pointSize
, drawPoints
, drawGapPoints
,
588 stepPlot
, strategy
) {
590 var prevCanvasX
= null;
591 var prevCanvasY
= null;
592 var nextCanvasY
= null;
593 var isIsolated
; // true if this point is isolated (no line segments)
594 var point
; // the point being processed in the while loop
595 var pointsOnLine
= []; // Array of [canvasx, canvasy] pairs.
596 var first
= true; // the first cycle through the while loop
600 while(iter
.hasNext()) {
602 if (point
.canvasy
=== null || point
.canvasy
!= point
.canvasy
) {
603 if (stepPlot
&& prevCanvasX
!== null) {
604 // Draw a horizontal line to the start of the missing data
605 strategy
.startSegment();
606 strategy
.drawLine(prevX
, prevY
, point
.canvasx
, prevY
);
607 strategy
.endSegment();
609 prevCanvasX
= prevCanvasY
= null;
611 nextCanvasY
= iter
.hasNext() ? iter
.peek().canvasy
: null;
612 // TODO: we calculate isNullOrNaN for this point, and the next, and then, when
613 // we iterate, test for isNullOrNaN again. Why bother?
614 var isNextCanvasYNullOrNaN
= nextCanvasY
=== null || nextCanvasY
!= nextCanvasY
;
615 isIsolated
= (!prevCanvasX
&& isNextCanvasYNullOrNaN
);
617 // Also consider a point to be "isolated" if it's adjacent to a
618 // null point, excluding the graph edges.
619 if ((!first
&& !prevCanvasX
) ||
620 (iter
.hasNext() && isNextCanvasYNullOrNaN
)) {
624 if (prevCanvasX
!== null) {
625 if (strategy
.skipPixel(prevCanvasX
, prevCanvasY
, point
.canvasx
, point
.canvasy
)) {
629 strategy
.startSegment();
631 strategy
.drawLine(prevCanvasX
, prevCanvasY
, point
.canvasx
, prevCanvasY
);
632 prevCanvasX
= point
.canvasx
;
634 strategy
.drawLine(prevCanvasX
, prevCanvasY
, point
.canvasx
, point
.canvasy
);
635 strategy
.endSegment();
638 if (drawPoints
|| isIsolated
) {
639 pointsOnLine
.push([point
.canvasx
, point
.canvasy
]);
641 prevCanvasX
= point
.canvasx
;
642 prevCanvasY
= point
.canvasy
;
650 DygraphCanvasRenderer
.prototype._drawLine
= function(ctx
, i
) {
651 var setNames
= this.layout
.setNames
;
652 var setName
= setNames
[i
];
654 var strokeWidth
= this.dygraph_
.attr_("strokeWidth", setName
);
655 var borderWidth
= this.dygraph_
.attr_("strokeBorderWidth", setName
);
656 var drawPointCallback
= this.dygraph_
.attr_("drawPointCallback", setName
) ||
657 Dygraph
.Circles
.DEFAULT
;
659 if (borderWidth
&& strokeWidth
) {
660 this._drawStyledLine(ctx
, i
, setName
,
661 this.dygraph_
.attr_("strokeBorderColor", setName
),
662 strokeWidth
+ 2 * borderWidth
,
663 this.dygraph_
.attr_("strokePattern", setName
),
664 this.dygraph_
.attr_("drawPoints", setName
),
666 this.dygraph_
.attr_("pointSize", setName
));
669 this._drawStyledLine(ctx
, i
, setName
,
670 this.colors
[setName
],
672 this.dygraph_
.attr_("strokePattern", setName
),
673 this.dygraph_
.attr_("drawPoints", setName
),
675 this.dygraph_
.attr_("pointSize", setName
));
679 * Actually draw the lines chart, including error bars.
680 * TODO(danvk): split this into several smaller functions.
683 DygraphCanvasRenderer
.prototype._renderLineChart
= function() {
684 // TODO(danvk): use this.attr_ for many of these.
685 var ctx
= this.elementContext
;
686 var fillAlpha
= this.attr_('fillAlpha');
687 var errorBars
= this.attr_("errorBars") || this.attr_("customBars");
688 var fillGraph
= this.attr_("fillGraph");
689 var stackedGraph
= this.attr_("stackedGraph");
690 var stepPlot
= this.attr_("stepPlot");
691 var points
= this.layout
.points
;
692 var pointsLength
= points
.length
;
693 var point
, i
, prevX
, prevY
, prevYs
, color
, setName
, newYs
, err_color
, rgb
, yscale
, axis
;
695 var setNames
= this.layout
.setNames
;
696 var setCount
= setNames
.length
;
698 this.colors
= this.dygraph_
.colorsMap_
;
703 // TODO(bhs): this loop is a hot-spot for high-point-count charts. These
704 // transformations can be pushed into the canvas via linear transformation
706 for (i
= pointsLength
; i
--;) {
708 point
.canvasx
= this.area
.w
* point
.x
+ this.area
.x
;
709 point
.canvasy
= this.area
.h
* point
.y
+ this.area
.y
;
716 this.dygraph_
.warn("Can't use fillGraph option with error bars");
719 for (i
= 0; i
< setCount
; i
++) {
720 setName
= setNames
[i
];
721 axis
= this.dygraph_
.axisPropertiesForSeries(setName
);
722 color
= this.colors
[setName
];
724 var firstIndexInSet
= this.layout
.setPointsOffsets
[i
];
725 var setLength
= this.layout
.setPointsLengths
[i
];
727 var iter
= Dygraph
.createIterator(points
, firstIndexInSet
, setLength
,
728 DygraphCanvasRenderer
._getIteratorPredicate(this.attr_("connectSeparatedPoints")));
730 // setup graphics context
734 yscale
= axis
.yscale
;
735 // should be same color as the lines but only 15% opaque.
736 rgb
= new RGBColor(color
);
737 err_color
= 'rgba(' + rgb
.r
+ ',' + rgb
.g
+ ',' + rgb
.b
+ ',' +
739 ctx
.fillStyle
= err_color
;
741 while (iter
.hasNext()) {
743 if (point
.name
== setName
) { // TODO(klausw): this is always true
744 if (!Dygraph
.isOK(point
.y
)) {
751 newYs
= [ point
.y_bottom
, point
.y_top
];
754 newYs
= [ point
.y_bottom
, point
.y_top
];
756 newYs
[0] = this.area
.h
* newYs
[0] + this.area
.y
;
757 newYs
[1] = this.area
.h
* newYs
[1] + this.area
.y
;
760 ctx
.moveTo(prevX
, newYs
[0]);
762 ctx
.moveTo(prevX
, prevYs
[0]);
764 ctx
.lineTo(point
.canvasx
, newYs
[0]);
765 ctx
.lineTo(point
.canvasx
, newYs
[1]);
767 ctx
.lineTo(prevX
, newYs
[1]);
769 ctx
.lineTo(prevX
, prevYs
[1]);
774 prevX
= point
.canvasx
;
780 } else if (fillGraph
) {
782 var baseline
= {}; // for stacked graphs: baseline for filling
785 // process sets in reverse order (needed for stacked graphs)
786 for (i
= setCount
- 1; i
>= 0; i
--) {
787 setName
= setNames
[i
];
788 color
= this.colors
[setName
];
789 axis
= this.dygraph_
.axisPropertiesForSeries(setName
);
790 var axisY
= 1.0 + axis
.minyval
* axis
.yscale
;
791 if (axisY
< 0.0) axisY
= 0.0;
792 else if (axisY
> 1.0) axisY
= 1.0;
793 axisY
= this.area
.h
* axisY
+ this.area
.y
;
794 var firstIndexInSet
= this.layout
.setPointsOffsets
[i
];
795 var setLength
= this.layout
.setPointsLengths
[i
];
797 var iter
= Dygraph
.createIterator(points
, firstIndexInSet
, setLength
,
798 DygraphCanvasRenderer
._getIteratorPredicate(this.attr_("connectSeparatedPoints")));
800 // setup graphics context
803 yscale
= axis
.yscale
;
804 // should be same color as the lines but only 15% opaque.
805 rgb
= new RGBColor(color
);
806 err_color
= 'rgba(' + rgb
.r
+ ',' + rgb
.g
+ ',' + rgb
.b
+ ',' +
808 ctx
.fillStyle
= err_color
;
810 while(iter
.hasNext()) {
812 if (point
.name
== setName
) { // TODO(klausw): this is always true
813 if (!Dygraph
.isOK(point
.y
)) {
818 currBaseline
= baseline
[point
.canvasx
];
820 if (currBaseline
=== undefined
) {
824 lastY
= currBaseline
[0];
826 lastY
= currBaseline
;
829 newYs
= [ point
.canvasy
, lastY
];
832 // Step plots must keep track of the top and bottom of
833 // the baseline at each point.
834 if(prevYs
[0] === -1) {
835 baseline
[point
.canvasx
] = [ point
.canvasy
, axisY
];
837 baseline
[point
.canvasx
] = [ point
.canvasy
, prevYs
[0] ];
840 baseline
[point
.canvasx
] = point
.canvasy
;
844 newYs
= [ point
.canvasy
, axisY
];
847 ctx
.moveTo(prevX
, prevYs
[0]);
850 ctx
.lineTo(point
.canvasx
, prevYs
[0]);
852 // Draw to the bottom of the baseline
853 ctx
.lineTo(point
.canvasx
, currBaseline
[1]);
855 ctx
.lineTo(point
.canvasx
, newYs
[1]);
858 ctx
.lineTo(point
.canvasx
, newYs
[0]);
859 ctx
.lineTo(point
.canvasx
, newYs
[1]);
862 ctx
.lineTo(prevX
, prevYs
[1]);
866 prevX
= point
.canvasx
;
874 // Drawing the lines.
875 for (i
= 0; i
< setCount
; i
+= 1) {
876 this._drawLine(ctx
, i
);
881 * This does dashed lines onto a canvas for a given pattern. You must call
882 * ctx.stroke() after to actually draw it, much line ctx.lineTo(). It remembers
883 * the state of the line in regards to where we left off on drawing the pattern.
884 * You can draw a dashed line in several function calls and the pattern will be
885 * continous as long as you didn't call this function with a different pattern
887 * @param ctx The canvas 2d context to draw on.
888 * @param x The start of the line's x coordinate.
889 * @param y The start of the line's y coordinate.
890 * @param x2 The end of the line's x coordinate.
891 * @param y2 The end of the line's y coordinate.
892 * @param pattern The dash pattern to draw, an array of integers where even
893 * index is drawn and odd index is not drawn (Ex. [10, 2, 5, 2], 10 is drawn 5
894 * is drawn, 2 is the space between.). A null pattern, array of length one, or
895 * empty array will do just a solid line.
898 DygraphCanvasRenderer
.prototype._dashedLine
= function(ctx
, x
, y
, x2
, y2
, pattern
) {
899 // Original version http://stackoverflow.com/questions
/4576724/dotted-stroke
-in-canvas
900 // Modified by Russell Valentine to keep line history and continue the pattern
901 // where it left off.
902 var dx
, dy
, len
, rot
, patternIndex
, segment
;
904 // If we don't have a pattern or it is an empty array or of size one just
906 if (!pattern
|| pattern
.length
<= 1) {
912 // If we have a different dash pattern than the last time this was called we
913 // reset our dash history and start the pattern from the begging
914 // regardless of state of the last pattern.
915 if (!Dygraph
.compareArrays(pattern
, this._dashedLineToHistoryPattern
)) {
916 this._dashedLineToHistoryPattern
= pattern
;
917 this._dashedLineToHistory
= [0, 0];
921 // Calculate transformation parameters
924 len
= Math
.sqrt(dx
*dx
+ dy
*dy
);
925 rot
= Math
.atan2(dy
, dx
);
927 // Set transformation
932 // Set last pattern index we used for this pattern.
933 patternIndex
= this._dashedLineToHistory
[0];
936 // Get the length of the pattern segment we are dealing with.
937 segment
= pattern
[patternIndex
];
938 // If our last draw didn't complete the pattern segment all the way we
939 // will try to finish it. Otherwise we will try to do the whole segment.
940 if (this._dashedLineToHistory
[1]) {
941 x
+= this._dashedLineToHistory
[1];
946 // We were unable to complete this pattern index all the way, keep
947 // where we are the history so our next draw continues where we left off
949 this._dashedLineToHistory
= [patternIndex
, x
-len
];
952 // We completed this patternIndex, we put in the history that we are on
953 // the beginning of the next segment.
954 this._dashedLineToHistory
= [(patternIndex
+1)%pattern
.length
, 0];
957 // We do a line on a even pattern index and just move on a odd pattern index.
958 // The move is the empty space in the dash.
959 if(patternIndex
% 2 === 0) {
964 // If we are not done, next loop process the next pattern segment, or the
965 // first segment again if we are at the end of the pattern.
966 patternIndex
= (patternIndex
+1) % pattern
.length
;