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 */
32 var DygraphCanvasRenderer
= function(dygraph
, element
, elementContext
, layout
) {
33 this.dygraph_
= dygraph
;
36 this.element
= element
;
37 this.elementContext
= elementContext
;
38 this.container
= this.element
.parentNode
;
40 this.height
= this.element
.height
;
41 this.width
= this.element
.width
;
43 // --- check whether everything is ok before we return
44 if (!this.isIE
&& !(DygraphCanvasRenderer
.isSupported(this.element
)))
45 throw "Canvas is not supported.";
50 this.annotations
= [];
51 this.chartLabels
= {};
53 this.area
= layout
.getPlotArea();
54 this.container
.style
.position
= "relative";
55 this.container
.style
.width
= this.width
+ "px";
57 // Set up a clipping area for the canvas (and the interaction canvas).
58 // This ensures that we don't overdraw.
59 if (this.dygraph_
.isUsingExcanvas_
) {
60 this._createIEClipArea();
62 // on Android 3 and 4, setting a clipping area on a canvas prevents it from
63 // displaying anything.
64 if (!Dygraph
.isAndroid()) {
65 var ctx
= this.dygraph_
.canvas_ctx_
;
67 ctx
.rect(this.area
.x
, this.area
.y
, this.area
.w
, this.area
.h
);
70 ctx
= this.dygraph_
.hidden_ctx_
;
72 ctx
.rect(this.area
.x
, this.area
.y
, this.area
.w
, this.area
.h
);
78 DygraphCanvasRenderer
.prototype.attr_
= function(x
) {
79 return this.dygraph_
.attr_(x
);
82 DygraphCanvasRenderer
.prototype.clear
= function() {
85 // VML takes a while to start up, so we just poll every this.IEDelay
87 if (this.clearDelay
) {
88 this.clearDelay
.cancel();
89 this.clearDelay
= null;
91 context
= this.elementContext
;
94 // TODO(danvk): this is broken, since MochiKit.Async is gone.
95 // this.clearDelay = MochiKit.Async.wait(this.IEDelay);
96 // this.clearDelay.addCallback(bind(this.clear, this));
101 context
= this.elementContext
;
102 context
.clearRect(0, 0, this.width
, this.height
);
104 function removeArray(ary
) {
105 for (var i
= 0; i
< ary
.length
; i
++) {
107 if (el
.parentNode
) el
.parentNode
.removeChild(el
);
111 removeArray(this.xlabels
);
112 removeArray(this.ylabels
);
113 removeArray(this.annotations
);
115 for (var k
in this.chartLabels
) {
116 if (!this.chartLabels
.hasOwnProperty(k
)) continue;
117 var el
= this.chartLabels
[k
];
118 if (el
.parentNode
) el
.parentNode
.removeChild(el
);
122 this.annotations
= [];
123 this.chartLabels
= {};
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 * Draw an X/Y grid on top of the existing plot
158 DygraphCanvasRenderer
.prototype.render
= function() {
159 // Draw the new X/Y grid
. Lines appear crisper when pixels are rounded to
160 // half-integers. This prevents them from drawing in two rows/cols.
161 var ctx
= this.elementContext
;
162 function halfUp(x
) { return Math
.round(x
) + 0.5; }
163 function halfDown(y
){ return Math
.round(y
) - 0.5; }
165 if (this.attr_('underlayCallback')) {
166 // NOTE: we pass the dygraph object to this callback twice to avoid breaking
167 // users who expect a deprecated form of this callback.
168 this.attr_('underlayCallback')(ctx
, this.area
, this.dygraph_
, this.dygraph_
);
172 if (this.attr_('drawYGrid')) {
173 ticks
= this.layout
.yticks
;
174 // TODO(konigsberg): I don't think these calls to save() have a corresponding restore().
176 ctx
.strokeStyle
= this.attr_('gridLineColor');
177 ctx
.lineWidth
= this.attr_('gridLineWidth');
178 for (i
= 0; i
< ticks
.length
; i
++) {
179 // TODO(danvk): allow secondary axes to draw a grid, too.
180 if (ticks
[i
][0] !== 0) continue;
181 x
= halfUp(this.area
.x
);
182 y
= halfDown(this.area
.y
+ ticks
[i
][1] * this.area
.h
);
185 ctx
.lineTo(x
+ this.area
.w
, y
);
191 if (this.attr_('drawXGrid')) {
192 ticks
= this.layout
.xticks
;
194 ctx
.strokeStyle
= this.attr_('gridLineColor');
195 ctx
.lineWidth
= this.attr_('gridLineWidth');
196 for (i
=0; i
<ticks
.length
; i
++) {
197 x
= halfUp(this.area
.x
+ ticks
[i
][0] * this.area
.w
);
198 y
= halfDown(this.area
.y
+ this.area
.h
);
201 ctx
.lineTo(x
, this.area
.y
);
207 // Do the ordinary rendering, as before
208 this._renderLineChart();
210 this._renderChartLabels();
211 this._renderAnnotations();
214 DygraphCanvasRenderer
.prototype._createIEClipArea
= function() {
215 var className
= 'dygraph-clip-div';
216 var graphDiv
= this.dygraph_
.graphDiv
;
218 // Remove old clip divs.
219 for (var i
= graphDiv
.childNodes
.length
-1; i
>= 0; i
--) {
220 if (graphDiv
.childNodes
[i
].className
== className
) {
221 graphDiv
.removeChild(graphDiv
.childNodes
[i
]);
225 // Determine background color to give clip divs.
226 var backgroundColor
= document
.bgColor
;
227 var element
= this.dygraph_
.graphDiv
;
228 while (element
!= document
) {
229 var bgcolor
= element
.currentStyle
.backgroundColor
;
230 if (bgcolor
&& bgcolor
!= 'transparent') {
231 backgroundColor
= bgcolor
;
234 element
= element
.parentNode
;
237 function createClipDiv(area
) {
238 if (area
.w
=== 0 || area
.h
=== 0) {
241 var elem
= document
.createElement('div');
242 elem
.className
= className
;
243 elem
.style
.backgroundColor
= backgroundColor
;
244 elem
.style
.position
= 'absolute';
245 elem
.style
.left
= area
.x
+ 'px';
246 elem
.style
.top
= area
.y
+ 'px';
247 elem
.style
.width
= area
.w
+ 'px';
248 elem
.style
.height
= area
.h
+ 'px';
249 graphDiv
.appendChild(elem
);
252 var plotArea
= this.area
;
263 w
: this.width
- plotArea
.x
,
269 x
: plotArea
.x
+ plotArea
.w
, y
: 0,
270 w
: this.width
-plotArea
.x
- plotArea
.w
,
277 y
: plotArea
.y
+ plotArea
.h
,
278 w
: this.width
- plotArea
.x
,
279 h
: this.height
- plotArea
.h
- plotArea
.y
283 DygraphCanvasRenderer
.prototype._renderAxis
= function() {
284 if (!this.attr_('drawXAxis') && !this.attr_('drawYAxis')) return;
286 // Round pixels to half-integer boundaries for crisper drawing.
287 function halfUp(x
) { return Math
.round(x
) + 0.5; }
288 function halfDown(y
){ return Math
.round(y
) - 0.5; }
290 var context
= this.elementContext
;
292 var label
, x
, y
, tick
, i
;
295 position
: "absolute",
296 fontSize
: this.attr_('axisLabelFontSize') + "px",
298 color
: this.attr_('axisLabelColor'),
299 width
: this.attr_('axisLabelWidth') + "px",
300 // height: this.attr_('axisLabelFontSize') + 2 + "px",
301 lineHeight
: "normal", // Something other than "normal" line-height screws up label positioning.
304 var makeDiv
= function(txt
, axis
, prec_axis
) {
305 var div
= document
.createElement("div");
306 for (var name
in labelStyle
) {
307 if (labelStyle
.hasOwnProperty(name
)) {
308 div
.style
[name
] = labelStyle
[name
];
311 var inner_div
= document
.createElement("div");
312 inner_div
.className
= 'dygraph-axis-label' +
313 ' dygraph-axis-label-' + axis
+
314 (prec_axis
? ' dygraph-axis-label-' + prec_axis
: '');
315 inner_div
.innerHTML
=txt
;
316 div
.appendChild(inner_div
);
322 context
.strokeStyle
= this.attr_('axisLineColor');
323 context
.lineWidth
= this.attr_('axisLineWidth');
325 if (this.attr_('drawYAxis')) {
326 if (this.layout
.yticks
&& this.layout
.yticks
.length
> 0) {
327 var num_axes
= this.dygraph_
.numAxes();
328 for (i
= 0; i
< this.layout
.yticks
.length
; i
++) {
329 tick
= this.layout
.yticks
[i
];
330 if (typeof(tick
) == "function") return;
333 var prec_axis
= 'y1';
334 if (tick
[0] == 1) { // right-side y-axis
335 x
= this.area
.x
+ this.area
.w
;
339 y
= this.area
.y
+ tick
[1] * this.area
.h
;
341 /* Tick marks are currently clipped, so don't bother drawing them.
343 context.moveTo(halfUp(x), halfDown(y));
344 context.lineTo(halfUp(x - sgn * this.attr_('axisTickSize')), halfDown(y));
349 label
= makeDiv(tick
[2], 'y', num_axes
== 2 ? prec_axis
: null);
350 var top
= (y
- this.attr_('axisLabelFontSize') / 2);
351 if (top
< 0) top
= 0;
353 if (top
+ this.attr_('axisLabelFontSize') + 3 > this.height
) {
354 label
.style
.bottom
= "0px";
356 label
.style
.top
= top
+ "px";
359 label
.style
.left
= (this.area
.x
- this.attr_('yAxisLabelWidth') - this.attr_('axisTickSize')) + "px";
360 label
.style
.textAlign
= "right";
361 } else if (tick
[0] == 1) {
362 label
.style
.left
= (this.area
.x
+ this.area
.w
+
363 this.attr_('axisTickSize')) + "px";
364 label
.style
.textAlign
= "left";
366 label
.style
.width
= this.attr_('yAxisLabelWidth') + "px";
367 this.container
.appendChild(label
);
368 this.ylabels
.push(label
);
371 // The lowest tick on the y-axis often overlaps with the leftmost
372 // tick on the x-axis. Shift the bottom tick up a little bit to
373 // compensate if necessary.
374 var bottomTick
= this.ylabels
[0];
375 var fontSize
= this.attr_('axisLabelFontSize');
376 var bottom
= parseInt(bottomTick
.style
.top
, 10) + fontSize
;
377 if (bottom
> this.height
- fontSize
) {
378 bottomTick
.style
.top
= (parseInt(bottomTick
.style
.top
, 10) -
379 fontSize
/ 2) + "px";
383 // draw a vertical line on the left to separate the chart from the labels.
385 context
.moveTo(halfUp(this.area
.x
), halfDown(this.area
.y
));
386 context
.lineTo(halfUp(this.area
.x
), halfDown(this.area
.y
+ this.area
.h
));
390 // if there's a secondary y-axis, draw a vertical line for that, too.
391 if (this.dygraph_
.numAxes() == 2) {
393 context
.moveTo(halfDown(this.area
.x
+ this.area
.w
), halfDown(this.area
.y
));
394 context
.lineTo(halfDown(this.area
.x
+ this.area
.w
), halfDown(this.area
.y
+ this.area
.h
));
400 if (this.attr_('drawXAxis')) {
401 if (this.layout
.xticks
) {
402 for (i
= 0; i
< this.layout
.xticks
.length
; i
++) {
403 tick
= this.layout
.xticks
[i
];
404 x
= this.area
.x
+ tick
[0] * this.area
.w
;
405 y
= this.area
.y
+ this.area
.h
;
407 /* Tick marks are currently clipped, so don't bother drawing them.
409 context.moveTo(halfUp(x), halfDown(y));
410 context.lineTo(halfUp(x), halfDown(y + this.attr_('axisTickSize')));
415 label
= makeDiv(tick
[1], 'x');
416 label
.style
.textAlign
= "center";
417 label
.style
.top
= (y
+ this.attr_('axisTickSize')) + 'px';
419 var left
= (x
- this.attr_('axisLabelWidth')/2);
420 if (left
+ this.attr_('axisLabelWidth') > this.width
) {
421 left
= this.width
- this.attr_('xAxisLabelWidth');
422 label
.style
.textAlign
= "right";
426 label
.style
.textAlign
= "left";
429 label
.style
.left
= left
+ "px";
430 label
.style
.width
= this.attr_('xAxisLabelWidth') + "px";
431 this.container
.appendChild(label
);
432 this.xlabels
.push(label
);
437 context
.moveTo(halfUp(this.area
.x
), halfDown(this.area
.y
+ this.area
.h
));
438 context
.lineTo(halfUp(this.area
.x
+ this.area
.w
), halfDown(this.area
.y
+ this.area
.h
));
447 DygraphCanvasRenderer
.prototype._renderChartLabels
= function() {
450 // Generate divs for the chart title, xlabel and ylabel.
451 // Space for these divs has already been taken away from the charting area in
452 // the DygraphCanvasRenderer constructor.
453 if (this.attr_('title')) {
454 div
= document
.createElement("div");
455 div
.style
.position
= 'absolute';
456 div
.style
.top
= '0px';
457 div
.style
.left
= this.area
.x
+ 'px';
458 div
.style
.width
= this.area
.w
+ 'px';
459 div
.style
.height
= this.attr_('titleHeight') + 'px';
460 div
.style
.textAlign
= 'center';
461 div
.style
.fontSize
= (this.attr_('titleHeight') - 8) + 'px';
462 div
.style
.fontWeight
= 'bold';
463 class_div
= document
.createElement("div");
464 class_div
.className
= 'dygraph-label dygraph-title';
465 class_div
.innerHTML
= this.attr_('title');
466 div
.appendChild(class_div
);
467 this.container
.appendChild(div
);
468 this.chartLabels
.title
= div
;
471 if (this.attr_('xlabel')) {
472 div
= document
.createElement("div");
473 div
.style
.position
= 'absolute';
474 div
.style
.bottom
= 0; // TODO(danvk): this is lazy. Calculate style.top.
475 div
.style
.left
= this.area
.x
+ 'px';
476 div
.style
.width
= this.area
.w
+ 'px';
477 div
.style
.height
= this.attr_('xLabelHeight') + 'px';
478 div
.style
.textAlign
= 'center';
479 div
.style
.fontSize
= (this.attr_('xLabelHeight') - 2) + 'px';
481 class_div
= document
.createElement("div");
482 class_div
.className
= 'dygraph-label dygraph-xlabel';
483 class_div
.innerHTML
= this.attr_('xlabel');
484 div
.appendChild(class_div
);
485 this.container
.appendChild(div
);
486 this.chartLabels
.xlabel
= div
;
490 function createRotatedDiv(axis
, classes
, html
) {
494 width
: that
.attr_('yLabelWidth'),
497 // TODO(danvk): is this outer div actually necessary?
498 div
= document
.createElement("div");
499 div
.style
.position
= 'absolute';
501 div
.style
.left
= box
.left
;
503 div
.style
.right
= box
.left
;
505 div
.style
.top
= box
.top
+ 'px';
506 div
.style
.width
= box
.width
+ 'px';
507 div
.style
.height
= box
.height
+ 'px';
508 div
.style
.fontSize
= (that
.attr_('yLabelWidth') - 2) + 'px';
510 var inner_div
= document
.createElement("div");
511 inner_div
.style
.position
= 'absolute';
512 inner_div
.style
.width
= box
.height
+ 'px';
513 inner_div
.style
.height
= box
.width
+ 'px';
514 inner_div
.style
.top
= (box
.height
/ 2 - box.width / 2) + 'px';
515 inner_div
.style
.left
= (box
.width
/ 2 - box.height / 2) + 'px';
516 inner_div
.style
.textAlign
= 'center';
518 // CSS rotation is an HTML5 feature which is not standardized. Hence every
519 // browser has its own name for the CSS style.
520 var val
= 'rotate(' + (axis
== 1 ? '-' : '') + '90deg)';
521 inner_div
.style
.transform
= val
; // HTML5
522 inner_div
.style
.WebkitTransform
= val
; // Safari/Chrome
523 inner_div
.style
.MozTransform
= val
; // Firefox
524 inner_div
.style
.OTransform
= val
; // Opera
525 inner_div
.style
.msTransform
= val
; // IE9
527 if (typeof(document
.documentMode
) !== 'undefined' &&
528 document
.documentMode
< 9) {
529 // We're dealing w/ an old version of IE
, so we have to rotate the text
530 // using a BasicImage transform. This uses a different origin of rotation
531 // than HTML5 rotation (top left of div vs. its center).
532 inner_div
.style
.filter
=
533 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' +
534 (axis
== 1 ? '3' : '1') + ')';
535 inner_div
.style
.left
= '0px';
536 inner_div
.style
.top
= '0px';
539 class_div
= document
.createElement("div");
540 class_div
.className
= classes
;
541 class_div
.innerHTML
= html
;
543 inner_div
.appendChild(class_div
);
544 div
.appendChild(inner_div
);
549 if (this.attr_('ylabel')) {
550 div
= createRotatedDiv(1, 'dygraph-label dygraph-ylabel',
551 this.attr_('ylabel'));
552 this.container
.appendChild(div
);
553 this.chartLabels
.ylabel
= div
;
555 if (this.attr_('y2label') && this.dygraph_
.numAxes() == 2) {
556 div
= createRotatedDiv(2, 'dygraph-label dygraph-y2label',
557 this.attr_('y2label'));
558 this.container
.appendChild(div
);
559 this.chartLabels
.y2label
= div
;
564 DygraphCanvasRenderer
.prototype._renderAnnotations
= function() {
565 var annotationStyle
= {
566 "position": "absolute",
567 "fontSize": this.attr_('axisLabelFontSize') + "px",
572 var bindEvt
= function(eventName
, classEventName
, p
, self
) {
574 var a
= p
.annotation
;
575 if (a
.hasOwnProperty(eventName
)) {
576 a
[eventName
](a
, p
, self
.dygraph_
, e
);
577 } else if (self
.dygraph_
.attr_(classEventName
)) {
578 self
.dygraph_
.attr_(classEventName
)(a
, p
, self
.dygraph_
,e
);
583 // Get a list of point with annotations.
584 var points
= this.layout
.annotated_points
;
585 for (var i
= 0; i
< points
.length
; i
++) {
587 if (p
.canvasx
< this.area
.x
|| p
.canvasx
> this.area
.x
+ this.area
.w
) {
591 var a
= p
.annotation
;
593 if (a
.hasOwnProperty("tickHeight")) {
594 tick_height
= a
.tickHeight
;
597 var div
= document
.createElement("div");
598 for (var name
in annotationStyle
) {
599 if (annotationStyle
.hasOwnProperty(name
)) {
600 div
.style
[name
] = annotationStyle
[name
];
603 if (!a
.hasOwnProperty('icon')) {
604 div
.className
= "dygraphDefaultAnnotation";
606 if (a
.hasOwnProperty('cssClass')) {
607 div
.className
+= " " + a
.cssClass
;
610 var width
= a
.hasOwnProperty('width') ? a
.width
: 16;
611 var height
= a
.hasOwnProperty('height') ? a
.height
: 16;
612 if (a
.hasOwnProperty('icon')) {
613 var img
= document
.createElement("img");
617 div
.appendChild(img
);
618 } else if (p
.annotation
.hasOwnProperty('shortText')) {
619 div
.appendChild(document
.createTextNode(p
.annotation
.shortText
));
621 div
.style
.left
= (p
.canvasx
- width
/ 2) + "px";
622 if (a
.attachAtBottom
) {
623 div
.style
.top
= (this.area
.h
- height
- tick_height
) + "px";
625 div
.style
.top
= (p
.canvasy
- height
- tick_height
) + "px";
627 div
.style
.width
= width
+ "px";
628 div
.style
.height
= height
+ "px";
629 div
.title
= p
.annotation
.text
;
630 div
.style
.color
= this.colors
[p
.name
];
631 div
.style
.borderColor
= this.colors
[p
.name
];
634 Dygraph
.addEvent(div
, 'click',
635 bindEvt('clickHandler', 'annotationClickHandler', p
, this));
636 Dygraph
.addEvent(div
, 'mouseover',
637 bindEvt('mouseOverHandler', 'annotationMouseOverHandler', p
, this));
638 Dygraph
.addEvent(div
, 'mouseout',
639 bindEvt('mouseOutHandler', 'annotationMouseOutHandler', p
, this));
640 Dygraph
.addEvent(div
, 'dblclick',
641 bindEvt('dblClickHandler', 'annotationDblClickHandler', p
, this));
643 this.container
.appendChild(div
);
644 this.annotations
.push(div
);
646 var ctx
= this.elementContext
;
647 ctx
.strokeStyle
= this.colors
[p
.name
];
649 if (!a
.attachAtBottom
) {
650 ctx
.moveTo(p
.canvasx
, p
.canvasy
);
651 ctx
.lineTo(p
.canvasx
, p
.canvasy
- 2 - tick_height
);
653 ctx
.moveTo(p
.canvasx
, this.area
.h
);
654 ctx
.lineTo(p
.canvasx
, this.area
.h
- 2 - tick_height
);
661 DygraphCanvasRenderer
.makeNextPointStep_
= function(connect
, points
, end
) {
665 if (!(points
[j
].yval
=== null)) break;
670 return function(j
) { return j
+ 1 };
674 DygraphCanvasRenderer
.prototype._drawStyledLine
= function(
675 ctx
, i
, setName
, color
, strokeWidth
, strokePattern
, drawPoints
,
676 drawPointCallback
, pointSize
) {
677 var isNullOrNaN
= function(x
) {
678 return (x
=== null || isNaN(x
));
681 var stepPlot
= this.attr_("stepPlot");
682 var firstIndexInSet
= this.layout
.setPointsOffsets
[i
];
683 var setLength
= this.layout
.setPointsLengths
[i
];
684 var afterLastIndexInSet
= firstIndexInSet
+ setLength
;
685 var points
= this.layout
.points
;
688 var pointsOnLine
= []; // Array of [canvasx, canvasy] pairs.
689 if (!Dygraph
.isArrayLike(strokePattern
)) {
690 strokePattern
= null;
694 var next
= DygraphCanvasRenderer
.makeNextPointStep_(
695 this.attr_('connectSeparatedPoints'), points
, afterLastIndexInSet
);
697 for (var j
= firstIndexInSet
; j
< afterLastIndexInSet
; j
= next(j
)) {
699 if (isNullOrNaN(point
.canvasy
)) {
700 if (stepPlot
&& prevX
!== null) {
701 // Draw a horizontal line to the start of the missing data
703 ctx
.strokeStyle
= color
;
704 ctx
.lineWidth
= this.attr_('strokeWidth');
705 this._dashedLine(ctx
, prevX
, prevY
, point
.canvasx
, prevY
, strokePattern
);
708 // this will make us move to the next point, not draw a line to it.
709 prevX
= prevY
= null;
711 // A point is "isolated" if it is non-null but both the previous
712 // and next points are null.
713 var isIsolated
= (!prevX
&& (j
== points
.length
- 1 ||
714 isNullOrNaN(points
[j
+1].canvasy
)));
715 if (prevX
=== null) {
716 prevX
= point
.canvasx
;
717 prevY
= point
.canvasy
;
719 // Skip over points that will be drawn in the same pixel.
720 if (Math
.round(prevX
) == Math
.round(point
.canvasx
) &&
721 Math
.round(prevY
) == Math
.round(point
.canvasy
)) {
724 // TODO(antrob): skip over points that lie on a line that is already
725 // going to be drawn. There is no need to have more than 2
726 // consecutive points that are collinear.
729 ctx
.strokeStyle
= color
;
730 ctx
.lineWidth
= strokeWidth
;
732 this._dashedLine(ctx
, prevX
, prevY
, point
.canvasx
, prevY
, strokePattern
);
733 prevX
= point
.canvasx
;
735 this._dashedLine(ctx
, prevX
, prevY
, point
.canvasx
, point
.canvasy
, strokePattern
);
736 prevX
= point
.canvasx
;
737 prevY
= point
.canvasy
;
742 if (drawPoints
|| isIsolated
) {
743 pointsOnLine
.push([point
.canvasx
, point
.canvasy
]);
747 for (var idx
= 0; idx
< pointsOnLine
.length
; idx
++) {
748 var cb
= pointsOnLine
[idx
];
751 this.dygraph_
, setName
, ctx
, cb
[0], cb
[1], color
, pointSize
);
757 DygraphCanvasRenderer
.prototype._drawLine
= function(ctx
, i
) {
758 var setNames
= this.layout
.setNames
;
759 var setName
= setNames
[i
];
761 var strokeWidth
= this.dygraph_
.attr_("strokeWidth", setName
);
762 var borderWidth
= this.dygraph_
.attr_("strokeBorderWidth", setName
);
763 var drawPointCallback
= this.dygraph_
.attr_("drawPointCallback", setName
) ||
764 Dygraph
.Circles
.DEFAULT
;
765 if (borderWidth
&& strokeWidth
) {
766 this._drawStyledLine(ctx
, i
, setName
,
767 this.dygraph_
.attr_("strokeBorderColor", setName
),
768 strokeWidth
+ 2 * borderWidth
,
769 this.dygraph_
.attr_("strokePattern", setName
),
770 this.dygraph_
.attr_("drawPoints", setName
),
772 this.dygraph_
.attr_("pointSize", setName
));
775 this._drawStyledLine(ctx
, i
, setName
,
776 this.colors
[setName
],
778 this.dygraph_
.attr_("strokePattern", setName
),
779 this.dygraph_
.attr_("drawPoints", setName
),
781 this.dygraph_
.attr_("pointSize", setName
));
785 * Actually draw the lines chart, including error bars.
786 * TODO(danvk): split this into several smaller functions.
789 DygraphCanvasRenderer
.prototype._renderLineChart
= function() {
790 // TODO(danvk): use this.attr_ for many of these.
791 var ctx
= this.elementContext
;
792 var fillAlpha
= this.attr_('fillAlpha');
793 var errorBars
= this.attr_("errorBars") || this.attr_("customBars");
794 var fillGraph
= this.attr_("fillGraph");
795 var stackedGraph
= this.attr_("stackedGraph");
796 var stepPlot
= this.attr_("stepPlot");
797 var points
= this.layout
.points
;
798 var pointsLength
= points
.length
;
799 var point
, i
, j
, prevX
, prevY
, prevYs
, color
, setName
, newYs
, err_color
, rgb
, yscale
, axis
;
801 var setNames
= this.layout
.setNames
;
802 var setCount
= setNames
.length
;
804 // TODO(danvk): Move this mapping into Dygraph and get it out of here.
806 for (i
= 0; i
< setCount
; i
++) {
807 this.colors
[setNames
[i
]] = this.colorScheme_
[i
% this.colorScheme_
.length
];
812 for (i
= pointsLength
; i
--;) {
814 point
.canvasx
= this.area
.w
* point
.x
+ this.area
.x
;
815 point
.canvasy
= this.area
.h
* point
.y
+ this.area
.y
;
822 this.dygraph_
.warn("Can't use fillGraph option with error bars");
825 for (i
= 0; i
< setCount
; i
++) {
826 setName
= setNames
[i
];
827 axis
= this.dygraph_
.axisPropertiesForSeries(setName
);
828 color
= this.colors
[setName
];
830 var firstIndexInSet
= this.layout
.setPointsOffsets
[i
];
831 var setLength
= this.layout
.setPointsLengths
[i
];
832 var afterLastIndexInSet
= firstIndexInSet
+ setLength
;
834 var next
= DygraphCanvasRenderer
.makeNextPointStep_(
835 this.attr_('connectSeparatedPoints'), points
,
836 afterLastIndexInSet
);
838 // setup graphics context
842 yscale
= axis
.yscale
;
843 // should be same color as the lines but only 15% opaque.
844 rgb
= new RGBColor(color
);
845 err_color
= 'rgba(' + rgb
.r
+ ',' + rgb
.g
+ ',' + rgb
.b
+ ',' +
847 ctx
.fillStyle
= err_color
;
849 for (j
= firstIndexInSet
; j
< afterLastIndexInSet
; j
= next(j
)) {
851 if (point
.name
== setName
) { // TODO(klausw): this is always true
852 if (!Dygraph
.isOK(point
.y
)) {
859 newYs
= [ point
.y_bottom
, point
.y_top
];
862 newYs
= [ point
.y_bottom
, point
.y_top
];
864 newYs
[0] = this.area
.h
* newYs
[0] + this.area
.y
;
865 newYs
[1] = this.area
.h
* newYs
[1] + this.area
.y
;
868 ctx
.moveTo(prevX
, newYs
[0]);
870 ctx
.moveTo(prevX
, prevYs
[0]);
872 ctx
.lineTo(point
.canvasx
, newYs
[0]);
873 ctx
.lineTo(point
.canvasx
, newYs
[1]);
875 ctx
.lineTo(prevX
, newYs
[1]);
877 ctx
.lineTo(prevX
, prevYs
[1]);
882 prevX
= point
.canvasx
;
888 } else if (fillGraph
) {
890 var baseline
= []; // for stacked graphs: baseline for filling
892 // process sets in reverse order (needed for stacked graphs)
893 for (i
= setCount
- 1; i
>= 0; i
--) {
894 setName
= setNames
[i
];
895 color
= this.colors
[setName
];
896 axis
= this.dygraph_
.axisPropertiesForSeries(setName
);
897 var axisY
= 1.0 + axis
.minyval
* axis
.yscale
;
898 if (axisY
< 0.0) axisY
= 0.0;
899 else if (axisY
> 1.0) axisY
= 1.0;
900 axisY
= this.area
.h
* axisY
+ this.area
.y
;
901 var firstIndexInSet
= this.layout
.setPointsOffsets
[i
];
902 var setLength
= this.layout
.setPointsLengths
[i
];
903 var afterLastIndexInSet
= firstIndexInSet
+ setLength
;
905 var next
= DygraphCanvasRenderer
.makeNextPointStep_(
906 this.attr_('connectSeparatedPoints'), points
,
907 afterLastIndexInSet
);
909 // setup graphics context
912 yscale
= axis
.yscale
;
913 // should be same color as the lines but only 15% opaque.
914 rgb
= new RGBColor(color
);
915 err_color
= 'rgba(' + rgb
.r
+ ',' + rgb
.g
+ ',' + rgb
.b
+ ',' +
917 ctx
.fillStyle
= err_color
;
919 for (j
= firstIndexInSet
; j
< afterLastIndexInSet
; j
= next(j
)) {
921 if (point
.name
== setName
) { // TODO(klausw): this is always true
922 if (!Dygraph
.isOK(point
.y
)) {
927 var lastY
= baseline
[point
.canvasx
];
928 if (lastY
=== undefined
) lastY
= axisY
;
929 baseline
[point
.canvasx
] = point
.canvasy
;
930 newYs
= [ point
.canvasy
, lastY
];
932 newYs
= [ point
.canvasy
, axisY
];
935 ctx
.moveTo(prevX
, prevYs
[0]);
937 ctx
.lineTo(point
.canvasx
, prevYs
[0]);
939 ctx
.lineTo(point
.canvasx
, newYs
[0]);
941 ctx
.lineTo(point
.canvasx
, newYs
[1]);
942 ctx
.lineTo(prevX
, prevYs
[1]);
946 prevX
= point
.canvasx
;
954 // Drawing the lines.
955 for (i
= 0; i
< setCount
; i
+= 1) {
956 this._drawLine(ctx
, i
);
961 * This does dashed lines onto a canvas for a given pattern. You must call
962 * ctx.stroke() after to actually draw it, much line ctx.lineTo(). It remembers
963 * the state of the line in regards to where we left off on drawing the pattern.
964 * You can draw a dashed line in several function calls and the pattern will be
965 * continous as long as you didn't call this function with a different pattern
967 * @param ctx The canvas 2d context to draw on.
968 * @param x The start of the line's x coordinate.
969 * @param y The start of the line's y coordinate.
970 * @param x2 The end of the line's x coordinate.
971 * @param y2 The end of the line's y coordinate.
972 * @param pattern The dash pattern to draw, an array of integers where even
973 * index is drawn and odd index is not drawn (Ex. [10, 2, 5, 2], 10 is drawn 5
974 * is drawn, 2 is the space between.). A null pattern, array of length one, or
975 * empty array will do just a solid line.
978 DygraphCanvasRenderer
.prototype._dashedLine
= function(ctx
, x
, y
, x2
, y2
, pattern
) {
979 // Original version http://stackoverflow.com/questions
/4576724/dotted-stroke
-in-canvas
980 // Modified by Russell Valentine to keep line history and continue the pattern
981 // where it left off.
982 var dx
, dy
, len
, rot
, patternIndex
, segment
;
984 // If we don't have a pattern or it is an empty array or of size one just
986 if (!pattern
|| pattern
.length
<= 1) {
992 // If we have a different dash pattern than the last time this was called we
993 // reset our dash history and start the pattern from the begging
994 // regardless of state of the last pattern.
995 if (!Dygraph
.compareArrays(pattern
, this._dashedLineToHistoryPattern
)) {
996 this._dashedLineToHistoryPattern
= pattern
;
997 this._dashedLineToHistory
= [0, 0];
1001 // Calculate transformation parameters
1004 len
= Math
.sqrt(dx
*dx
+ dy
*dy
);
1005 rot
= Math
.atan2(dy
, dx
);
1007 // Set transformation
1008 ctx
.translate(x
, y
);
1012 // Set last pattern index we used for this pattern.
1013 patternIndex
= this._dashedLineToHistory
[0];
1016 // Get the length of the pattern segment we are dealing with.
1017 segment
= pattern
[patternIndex
];
1018 // If our last draw didn't complete the pattern segment all the way we
1019 // will try to finish it. Otherwise we will try to do the whole segment.
1020 if (this._dashedLineToHistory
[1]) {
1021 x
+= this._dashedLineToHistory
[1];
1026 // We were unable to complete this pattern index all the way, keep
1027 // where we are the history so our next draw continues where we left off
1029 this._dashedLineToHistory
= [patternIndex
, x
-len
];
1032 // We completed this patternIndex, we put in the history that we are on
1033 // the beginning of the next segment.
1034 this._dashedLineToHistory
= [(patternIndex
+1)%pattern
.length
, 0];
1037 // We do a line on a even pattern index and just move on a odd pattern index.
1038 // The move is the empty space in the dash.
1039 if(patternIndex
% 2 === 0) {
1044 // If we are not done, next loop process the next pattern segment, or the
1045 // first segment again if we are at the end of the pattern.
1046 patternIndex
= (patternIndex
+1) % pattern
.length
;