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
);
192 if (this.attr_('drawXGrid')) {
193 ticks
= this.layout
.xticks
;
195 ctx
.strokeStyle
= this.attr_('gridLineColor');
196 ctx
.lineWidth
= this.attr_('gridLineWidth');
197 for (i
=0; i
<ticks
.length
; i
++) {
198 x
= halfUp(this.area
.x
+ ticks
[i
][0] * this.area
.w
);
199 y
= halfDown(this.area
.y
+ this.area
.h
);
202 ctx
.lineTo(x
, this.area
.y
);
209 // Do the ordinary rendering, as before
210 this._renderLineChart();
212 this._renderChartLabels();
213 this._renderAnnotations();
216 DygraphCanvasRenderer
.prototype._createIEClipArea
= function() {
217 var className
= 'dygraph-clip-div';
218 var graphDiv
= this.dygraph_
.graphDiv
;
220 // Remove old clip divs.
221 for (var i
= graphDiv
.childNodes
.length
-1; i
>= 0; i
--) {
222 if (graphDiv
.childNodes
[i
].className
== className
) {
223 graphDiv
.removeChild(graphDiv
.childNodes
[i
]);
227 // Determine background color to give clip divs.
228 var backgroundColor
= document
.bgColor
;
229 var element
= this.dygraph_
.graphDiv
;
230 while (element
!= document
) {
231 var bgcolor
= element
.currentStyle
.backgroundColor
;
232 if (bgcolor
&& bgcolor
!= 'transparent') {
233 backgroundColor
= bgcolor
;
236 element
= element
.parentNode
;
239 function createClipDiv(area
) {
240 if (area
.w
=== 0 || area
.h
=== 0) {
243 var elem
= document
.createElement('div');
244 elem
.className
= className
;
245 elem
.style
.backgroundColor
= backgroundColor
;
246 elem
.style
.position
= 'absolute';
247 elem
.style
.left
= area
.x
+ 'px';
248 elem
.style
.top
= area
.y
+ 'px';
249 elem
.style
.width
= area
.w
+ 'px';
250 elem
.style
.height
= area
.h
+ 'px';
251 graphDiv
.appendChild(elem
);
254 var plotArea
= this.area
;
265 w
: this.width
- plotArea
.x
,
271 x
: plotArea
.x
+ plotArea
.w
, y
: 0,
272 w
: this.width
-plotArea
.x
- plotArea
.w
,
279 y
: plotArea
.y
+ plotArea
.h
,
280 w
: this.width
- plotArea
.x
,
281 h
: this.height
- plotArea
.h
- plotArea
.y
285 DygraphCanvasRenderer
.prototype._renderAxis
= function() {
286 if (!this.attr_('drawXAxis') && !this.attr_('drawYAxis')) return;
288 // Round pixels to half-integer boundaries for crisper drawing.
289 function halfUp(x
) { return Math
.round(x
) + 0.5; }
290 function halfDown(y
){ return Math
.round(y
) - 0.5; }
292 var context
= this.elementContext
;
294 var label
, x
, y
, tick
, i
;
297 position
: "absolute",
298 fontSize
: this.attr_('axisLabelFontSize') + "px",
300 color
: this.attr_('axisLabelColor'),
301 width
: this.attr_('axisLabelWidth') + "px",
302 // height: this.attr_('axisLabelFontSize') + 2 + "px",
303 lineHeight
: "normal", // Something other than "normal" line-height screws up label positioning.
306 var makeDiv
= function(txt
, axis
, prec_axis
) {
307 var div
= document
.createElement("div");
308 for (var name
in labelStyle
) {
309 if (labelStyle
.hasOwnProperty(name
)) {
310 div
.style
[name
] = labelStyle
[name
];
313 var inner_div
= document
.createElement("div");
314 inner_div
.className
= 'dygraph-axis-label' +
315 ' dygraph-axis-label-' + axis
+
316 (prec_axis
? ' dygraph-axis-label-' + prec_axis
: '');
317 inner_div
.innerHTML
=txt
;
318 div
.appendChild(inner_div
);
324 context
.strokeStyle
= this.attr_('axisLineColor');
325 context
.lineWidth
= this.attr_('axisLineWidth');
327 if (this.attr_('drawYAxis')) {
328 if (this.layout
.yticks
&& this.layout
.yticks
.length
> 0) {
329 var num_axes
= this.dygraph_
.numAxes();
330 for (i
= 0; i
< this.layout
.yticks
.length
; i
++) {
331 tick
= this.layout
.yticks
[i
];
332 if (typeof(tick
) == "function") return;
335 var prec_axis
= 'y1';
336 if (tick
[0] == 1) { // right-side y-axis
337 x
= this.area
.x
+ this.area
.w
;
341 y
= this.area
.y
+ tick
[1] * this.area
.h
;
343 /* Tick marks are currently clipped, so don't bother drawing them.
345 context.moveTo(halfUp(x), halfDown(y));
346 context.lineTo(halfUp(x - sgn * this.attr_('axisTickSize')), halfDown(y));
351 label
= makeDiv(tick
[2], 'y', num_axes
== 2 ? prec_axis
: null);
352 var top
= (y
- this.attr_('axisLabelFontSize') / 2);
353 if (top
< 0) top
= 0;
355 if (top
+ this.attr_('axisLabelFontSize') + 3 > this.height
) {
356 label
.style
.bottom
= "0px";
358 label
.style
.top
= top
+ "px";
361 label
.style
.left
= (this.area
.x
- this.attr_('yAxisLabelWidth') - this.attr_('axisTickSize')) + "px";
362 label
.style
.textAlign
= "right";
363 } else if (tick
[0] == 1) {
364 label
.style
.left
= (this.area
.x
+ this.area
.w
+
365 this.attr_('axisTickSize')) + "px";
366 label
.style
.textAlign
= "left";
368 label
.style
.width
= this.attr_('yAxisLabelWidth') + "px";
369 this.container
.appendChild(label
);
370 this.ylabels
.push(label
);
373 // The lowest tick on the y-axis often overlaps with the leftmost
374 // tick on the x-axis. Shift the bottom tick up a little bit to
375 // compensate if necessary.
376 var bottomTick
= this.ylabels
[0];
377 var fontSize
= this.attr_('axisLabelFontSize');
378 var bottom
= parseInt(bottomTick
.style
.top
, 10) + fontSize
;
379 if (bottom
> this.height
- fontSize
) {
380 bottomTick
.style
.top
= (parseInt(bottomTick
.style
.top
, 10) -
381 fontSize
/ 2) + "px";
385 // draw a vertical line on the left to separate the chart from the labels.
387 context
.moveTo(halfUp(this.area
.x
), halfDown(this.area
.y
));
388 context
.lineTo(halfUp(this.area
.x
), halfDown(this.area
.y
+ this.area
.h
));
392 // if there's a secondary y-axis, draw a vertical line for that, too.
393 if (this.dygraph_
.numAxes() == 2) {
395 context
.moveTo(halfDown(this.area
.x
+ this.area
.w
), halfDown(this.area
.y
));
396 context
.lineTo(halfDown(this.area
.x
+ this.area
.w
), halfDown(this.area
.y
+ this.area
.h
));
402 if (this.attr_('drawXAxis')) {
403 if (this.layout
.xticks
) {
404 for (i
= 0; i
< this.layout
.xticks
.length
; i
++) {
405 tick
= this.layout
.xticks
[i
];
406 x
= this.area
.x
+ tick
[0] * this.area
.w
;
407 y
= this.area
.y
+ this.area
.h
;
409 /* Tick marks are currently clipped, so don't bother drawing them.
411 context.moveTo(halfUp(x), halfDown(y));
412 context.lineTo(halfUp(x), halfDown(y + this.attr_('axisTickSize')));
417 label
= makeDiv(tick
[1], 'x');
418 label
.style
.textAlign
= "center";
419 label
.style
.top
= (y
+ this.attr_('axisTickSize')) + 'px';
421 var left
= (x
- this.attr_('axisLabelWidth')/2);
422 if (left
+ this.attr_('axisLabelWidth') > this.width
) {
423 left
= this.width
- this.attr_('xAxisLabelWidth');
424 label
.style
.textAlign
= "right";
428 label
.style
.textAlign
= "left";
431 label
.style
.left
= left
+ "px";
432 label
.style
.width
= this.attr_('xAxisLabelWidth') + "px";
433 this.container
.appendChild(label
);
434 this.xlabels
.push(label
);
439 context
.moveTo(halfUp(this.area
.x
), halfDown(this.area
.y
+ this.area
.h
));
440 context
.lineTo(halfUp(this.area
.x
+ this.area
.w
), halfDown(this.area
.y
+ this.area
.h
));
449 DygraphCanvasRenderer
.prototype._renderChartLabels
= function() {
452 // Generate divs for the chart title, xlabel and ylabel.
453 // Space for these divs has already been taken away from the charting area in
454 // the DygraphCanvasRenderer constructor.
455 if (this.attr_('title')) {
456 div
= document
.createElement("div");
457 div
.style
.position
= 'absolute';
458 div
.style
.top
= '0px';
459 div
.style
.left
= this.area
.x
+ 'px';
460 div
.style
.width
= this.area
.w
+ 'px';
461 div
.style
.height
= this.attr_('titleHeight') + 'px';
462 div
.style
.textAlign
= 'center';
463 div
.style
.fontSize
= (this.attr_('titleHeight') - 8) + 'px';
464 div
.style
.fontWeight
= 'bold';
465 class_div
= document
.createElement("div");
466 class_div
.className
= 'dygraph-label dygraph-title';
467 class_div
.innerHTML
= this.attr_('title');
468 div
.appendChild(class_div
);
469 this.container
.appendChild(div
);
470 this.chartLabels
.title
= div
;
473 if (this.attr_('xlabel')) {
474 div
= document
.createElement("div");
475 div
.style
.position
= 'absolute';
476 div
.style
.bottom
= 0; // TODO(danvk): this is lazy. Calculate style.top.
477 div
.style
.left
= this.area
.x
+ 'px';
478 div
.style
.width
= this.area
.w
+ 'px';
479 div
.style
.height
= this.attr_('xLabelHeight') + 'px';
480 div
.style
.textAlign
= 'center';
481 div
.style
.fontSize
= (this.attr_('xLabelHeight') - 2) + 'px';
483 class_div
= document
.createElement("div");
484 class_div
.className
= 'dygraph-label dygraph-xlabel';
485 class_div
.innerHTML
= this.attr_('xlabel');
486 div
.appendChild(class_div
);
487 this.container
.appendChild(div
);
488 this.chartLabels
.xlabel
= div
;
492 function createRotatedDiv(axis
, classes
, html
) {
496 width
: that
.attr_('yLabelWidth'),
499 // TODO(danvk): is this outer div actually necessary?
500 div
= document
.createElement("div");
501 div
.style
.position
= 'absolute';
503 div
.style
.left
= box
.left
;
505 div
.style
.right
= box
.left
;
507 div
.style
.top
= box
.top
+ 'px';
508 div
.style
.width
= box
.width
+ 'px';
509 div
.style
.height
= box
.height
+ 'px';
510 div
.style
.fontSize
= (that
.attr_('yLabelWidth') - 2) + 'px';
512 var inner_div
= document
.createElement("div");
513 inner_div
.style
.position
= 'absolute';
514 inner_div
.style
.width
= box
.height
+ 'px';
515 inner_div
.style
.height
= box
.width
+ 'px';
516 inner_div
.style
.top
= (box
.height
/ 2 - box.width / 2) + 'px';
517 inner_div
.style
.left
= (box
.width
/ 2 - box.height / 2) + 'px';
518 inner_div
.style
.textAlign
= 'center';
520 // CSS rotation is an HTML5 feature which is not standardized. Hence every
521 // browser has its own name for the CSS style.
522 var val
= 'rotate(' + (axis
== 1 ? '-' : '') + '90deg)';
523 inner_div
.style
.transform
= val
; // HTML5
524 inner_div
.style
.WebkitTransform
= val
; // Safari/Chrome
525 inner_div
.style
.MozTransform
= val
; // Firefox
526 inner_div
.style
.OTransform
= val
; // Opera
527 inner_div
.style
.msTransform
= val
; // IE9
529 if (typeof(document
.documentMode
) !== 'undefined' &&
530 document
.documentMode
< 9) {
531 // We're dealing w/ an old version of IE
, so we have to rotate the text
532 // using a BasicImage transform. This uses a different origin of rotation
533 // than HTML5 rotation (top left of div vs. its center).
534 inner_div
.style
.filter
=
535 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' +
536 (axis
== 1 ? '3' : '1') + ')';
537 inner_div
.style
.left
= '0px';
538 inner_div
.style
.top
= '0px';
541 class_div
= document
.createElement("div");
542 class_div
.className
= classes
;
543 class_div
.innerHTML
= html
;
545 inner_div
.appendChild(class_div
);
546 div
.appendChild(inner_div
);
551 if (this.attr_('ylabel')) {
552 div
= createRotatedDiv(1, 'dygraph-label dygraph-ylabel',
553 this.attr_('ylabel'));
554 this.container
.appendChild(div
);
555 this.chartLabels
.ylabel
= div
;
557 if (this.attr_('y2label') && this.dygraph_
.numAxes() == 2) {
558 div
= createRotatedDiv(2, 'dygraph-label dygraph-y2label',
559 this.attr_('y2label'));
560 this.container
.appendChild(div
);
561 this.chartLabels
.y2label
= div
;
566 DygraphCanvasRenderer
.prototype._renderAnnotations
= function() {
567 var annotationStyle
= {
568 "position": "absolute",
569 "fontSize": this.attr_('axisLabelFontSize') + "px",
574 var bindEvt
= function(eventName
, classEventName
, p
, self
) {
576 var a
= p
.annotation
;
577 if (a
.hasOwnProperty(eventName
)) {
578 a
[eventName
](a
, p
, self
.dygraph_
, e
);
579 } else if (self
.dygraph_
.attr_(classEventName
)) {
580 self
.dygraph_
.attr_(classEventName
)(a
, p
, self
.dygraph_
,e
);
585 // Get a list of point with annotations.
586 var points
= this.layout
.annotated_points
;
587 for (var i
= 0; i
< points
.length
; i
++) {
589 if (p
.canvasx
< this.area
.x
|| p
.canvasx
> this.area
.x
+ this.area
.w
||
590 p
.canvasy
< this.area
.y
|| p
.canvasy
> this.area
.y
+ this.area
.h
) {
594 var a
= p
.annotation
;
596 if (a
.hasOwnProperty("tickHeight")) {
597 tick_height
= a
.tickHeight
;
600 var div
= document
.createElement("div");
601 for (var name
in annotationStyle
) {
602 if (annotationStyle
.hasOwnProperty(name
)) {
603 div
.style
[name
] = annotationStyle
[name
];
606 if (!a
.hasOwnProperty('icon')) {
607 div
.className
= "dygraphDefaultAnnotation";
609 if (a
.hasOwnProperty('cssClass')) {
610 div
.className
+= " " + a
.cssClass
;
613 var width
= a
.hasOwnProperty('width') ? a
.width
: 16;
614 var height
= a
.hasOwnProperty('height') ? a
.height
: 16;
615 if (a
.hasOwnProperty('icon')) {
616 var img
= document
.createElement("img");
620 div
.appendChild(img
);
621 } else if (p
.annotation
.hasOwnProperty('shortText')) {
622 div
.appendChild(document
.createTextNode(p
.annotation
.shortText
));
624 div
.style
.left
= (p
.canvasx
- width
/ 2) + "px";
625 if (a
.attachAtBottom
) {
626 div
.style
.top
= (this.area
.h
- height
- tick_height
) + "px";
628 div
.style
.top
= (p
.canvasy
- height
- tick_height
) + "px";
630 div
.style
.width
= width
+ "px";
631 div
.style
.height
= height
+ "px";
632 div
.title
= p
.annotation
.text
;
633 div
.style
.color
= this.colors
[p
.name
];
634 div
.style
.borderColor
= this.colors
[p
.name
];
637 this.dygraph_
.addEvent(div
, 'click',
638 bindEvt('clickHandler', 'annotationClickHandler', p
, this));
639 this.dygraph_
.addEvent(div
, 'mouseover',
640 bindEvt('mouseOverHandler', 'annotationMouseOverHandler', p
, this));
641 this.dygraph_
.addEvent(div
, 'mouseout',
642 bindEvt('mouseOutHandler', 'annotationMouseOutHandler', p
, this));
643 this.dygraph_
.addEvent(div
, 'dblclick',
644 bindEvt('dblClickHandler', 'annotationDblClickHandler', p
, this));
646 this.container
.appendChild(div
);
647 this.annotations
.push(div
);
649 var ctx
= this.elementContext
;
650 ctx
.strokeStyle
= this.colors
[p
.name
];
652 if (!a
.attachAtBottom
) {
653 ctx
.moveTo(p
.canvasx
, p
.canvasy
);
654 ctx
.lineTo(p
.canvasx
, p
.canvasy
- 2 - tick_height
);
656 ctx
.moveTo(p
.canvasx
, this.area
.h
);
657 ctx
.lineTo(p
.canvasx
, this.area
.h
- 2 - tick_height
);
664 DygraphCanvasRenderer
.makeNextPointStep_
= function(connect
, points
, end
) {
668 if (!(points
[j
].yval
=== null)) break;
673 return function(j
) { return j
+ 1 };
677 DygraphCanvasRenderer
.prototype._drawStyledLine
= function(
678 ctx
, i
, setName
, color
, strokeWidth
, strokePattern
, drawPoints
,
679 drawPointCallback
, pointSize
) {
680 var isNullOrNaN
= function(x
) {
681 return (x
=== null || isNaN(x
));
684 var stepPlot
= this.attr_("stepPlot");
685 var firstIndexInSet
= this.layout
.setPointsOffsets
[i
];
686 var setLength
= this.layout
.setPointsLengths
[i
];
687 var afterLastIndexInSet
= firstIndexInSet
+ setLength
;
688 var points
= this.layout
.points
;
691 var pointsOnLine
= []; // Array of [canvasx, canvasy] pairs.
692 if (!Dygraph
.isArrayLike(strokePattern
)) {
693 strokePattern
= null;
697 var next
= DygraphCanvasRenderer
.makeNextPointStep_(
698 this.attr_('connectSeparatedPoints'), points
, afterLastIndexInSet
);
700 for (var j
= firstIndexInSet
; j
< afterLastIndexInSet
; j
= next(j
)) {
702 if (isNullOrNaN(point
.canvasy
)) {
703 if (stepPlot
&& prevX
!== null) {
704 // Draw a horizontal line to the start of the missing data
706 ctx
.strokeStyle
= color
;
707 ctx
.lineWidth
= this.attr_('strokeWidth');
708 this._dashedLine(ctx
, prevX
, prevY
, point
.canvasx
, prevY
, strokePattern
);
711 // this will make us move to the next point, not draw a line to it.
712 prevX
= prevY
= null;
714 // A point is "isolated" if it is non-null but both the previous
715 // and next points are null.
716 var isIsolated
= (!prevX
&& (j
== points
.length
- 1 ||
717 isNullOrNaN(points
[j
+1].canvasy
)));
718 if (prevX
=== null) {
719 prevX
= point
.canvasx
;
720 prevY
= point
.canvasy
;
722 // Skip over points that will be drawn in the same pixel.
723 if (Math
.round(prevX
) == Math
.round(point
.canvasx
) &&
724 Math
.round(prevY
) == Math
.round(point
.canvasy
)) {
727 // TODO(antrob): skip over points that lie on a line that is already
728 // going to be drawn. There is no need to have more than 2
729 // consecutive points that are collinear.
732 ctx
.strokeStyle
= color
;
733 ctx
.lineWidth
= strokeWidth
;
735 this._dashedLine(ctx
, prevX
, prevY
, point
.canvasx
, prevY
, strokePattern
);
736 prevX
= point
.canvasx
;
738 this._dashedLine(ctx
, prevX
, prevY
, point
.canvasx
, point
.canvasy
, strokePattern
);
739 prevX
= point
.canvasx
;
740 prevY
= point
.canvasy
;
745 if (drawPoints
|| isIsolated
) {
746 pointsOnLine
.push([point
.canvasx
, point
.canvasy
]);
750 for (var idx
= 0; idx
< pointsOnLine
.length
; idx
++) {
751 var cb
= pointsOnLine
[idx
];
754 this.dygraph_
, setName
, ctx
, cb
[0], cb
[1], color
, pointSize
);
760 DygraphCanvasRenderer
.prototype._drawLine
= function(ctx
, i
) {
761 var setNames
= this.layout
.setNames
;
762 var setName
= setNames
[i
];
764 var strokeWidth
= this.dygraph_
.attr_("strokeWidth", setName
);
765 var borderWidth
= this.dygraph_
.attr_("strokeBorderWidth", setName
);
766 var drawPointCallback
= this.dygraph_
.attr_("drawPointCallback", setName
) ||
767 Dygraph
.Circles
.DEFAULT
;
768 if (borderWidth
&& strokeWidth
) {
769 this._drawStyledLine(ctx
, i
, setName
,
770 this.dygraph_
.attr_("strokeBorderColor", setName
),
771 strokeWidth
+ 2 * borderWidth
,
772 this.dygraph_
.attr_("strokePattern", setName
),
773 this.dygraph_
.attr_("drawPoints", setName
),
775 this.dygraph_
.attr_("pointSize", setName
));
778 this._drawStyledLine(ctx
, i
, setName
,
779 this.colors
[setName
],
781 this.dygraph_
.attr_("strokePattern", setName
),
782 this.dygraph_
.attr_("drawPoints", setName
),
784 this.dygraph_
.attr_("pointSize", setName
));
788 * Actually draw the lines chart, including error bars.
789 * TODO(danvk): split this into several smaller functions.
792 DygraphCanvasRenderer
.prototype._renderLineChart
= function() {
793 // TODO(danvk): use this.attr_ for many of these.
794 var ctx
= this.elementContext
;
795 var fillAlpha
= this.attr_('fillAlpha');
796 var errorBars
= this.attr_("errorBars") || this.attr_("customBars");
797 var fillGraph
= this.attr_("fillGraph");
798 var stackedGraph
= this.attr_("stackedGraph");
799 var stepPlot
= this.attr_("stepPlot");
800 var points
= this.layout
.points
;
801 var pointsLength
= points
.length
;
802 var point
, i
, j
, prevX
, prevY
, prevYs
, color
, setName
, newYs
, err_color
, rgb
, yscale
, axis
;
804 var setNames
= this.layout
.setNames
;
805 var setCount
= setNames
.length
;
807 // TODO(danvk): Move this mapping into Dygraph and get it out of here.
809 for (i
= 0; i
< setCount
; i
++) {
810 this.colors
[setNames
[i
]] = this.colorScheme_
[i
% this.colorScheme_
.length
];
815 for (i
= pointsLength
; i
--;) {
817 point
.canvasx
= this.area
.w
* point
.x
+ this.area
.x
;
818 point
.canvasy
= this.area
.h
* point
.y
+ this.area
.y
;
825 this.dygraph_
.warn("Can't use fillGraph option with error bars");
828 for (i
= 0; i
< setCount
; i
++) {
829 setName
= setNames
[i
];
830 axis
= this.dygraph_
.axisPropertiesForSeries(setName
);
831 color
= this.colors
[setName
];
833 var firstIndexInSet
= this.layout
.setPointsOffsets
[i
];
834 var setLength
= this.layout
.setPointsLengths
[i
];
835 var afterLastIndexInSet
= firstIndexInSet
+ setLength
;
837 var next
= DygraphCanvasRenderer
.makeNextPointStep_(
838 this.attr_('connectSeparatedPoints'), points
,
839 afterLastIndexInSet
);
841 // setup graphics context
845 yscale
= axis
.yscale
;
846 // should be same color as the lines but only 15% opaque.
847 rgb
= new RGBColor(color
);
848 err_color
= 'rgba(' + rgb
.r
+ ',' + rgb
.g
+ ',' + rgb
.b
+ ',' +
850 ctx
.fillStyle
= err_color
;
852 for (j
= firstIndexInSet
; j
< afterLastIndexInSet
; j
= next(j
)) {
854 if (point
.name
== setName
) { // TODO(klausw): this is always true
855 if (!Dygraph
.isOK(point
.y
)) {
862 newYs
= [ point
.y_bottom
, point
.y_top
];
865 newYs
= [ point
.y_bottom
, point
.y_top
];
867 newYs
[0] = this.area
.h
* newYs
[0] + this.area
.y
;
868 newYs
[1] = this.area
.h
* newYs
[1] + this.area
.y
;
871 ctx
.moveTo(prevX
, newYs
[0]);
873 ctx
.moveTo(prevX
, prevYs
[0]);
875 ctx
.lineTo(point
.canvasx
, newYs
[0]);
876 ctx
.lineTo(point
.canvasx
, newYs
[1]);
878 ctx
.lineTo(prevX
, newYs
[1]);
880 ctx
.lineTo(prevX
, prevYs
[1]);
885 prevX
= point
.canvasx
;
891 } else if (fillGraph
) {
893 var baseline
= {}; // for stacked graphs: baseline for filling
896 // process sets in reverse order (needed for stacked graphs)
897 for (i
= setCount
- 1; i
>= 0; i
--) {
898 setName
= setNames
[i
];
899 color
= this.colors
[setName
];
900 axis
= this.dygraph_
.axisPropertiesForSeries(setName
);
901 var axisY
= 1.0 + axis
.minyval
* axis
.yscale
;
902 if (axisY
< 0.0) axisY
= 0.0;
903 else if (axisY
> 1.0) axisY
= 1.0;
904 axisY
= this.area
.h
* axisY
+ this.area
.y
;
905 var firstIndexInSet
= this.layout
.setPointsOffsets
[i
];
906 var setLength
= this.layout
.setPointsLengths
[i
];
907 var afterLastIndexInSet
= firstIndexInSet
+ setLength
;
909 var next
= DygraphCanvasRenderer
.makeNextPointStep_(
910 this.attr_('connectSeparatedPoints'), points
,
911 afterLastIndexInSet
);
913 // setup graphics context
916 yscale
= axis
.yscale
;
917 // should be same color as the lines but only 15% opaque.
918 rgb
= new RGBColor(color
);
919 err_color
= 'rgba(' + rgb
.r
+ ',' + rgb
.g
+ ',' + rgb
.b
+ ',' +
921 ctx
.fillStyle
= err_color
;
923 for (j
= firstIndexInSet
; j
< afterLastIndexInSet
; j
= next(j
)) {
925 if (point
.name
== setName
) { // TODO(klausw): this is always true
926 if (!Dygraph
.isOK(point
.y
)) {
931 currBaseline
= baseline
[point
.canvasx
];
933 if (currBaseline
=== undefined
) {
937 lastY
= currBaseline
[0];
939 lastY
= currBaseline
;
942 newYs
= [ point
.canvasy
, lastY
];
945 // Step plots must keep track of the top and bottom of
946 // the baseline at each point.
947 if(prevYs
[0] === -1) {
948 baseline
[point
.canvasx
] = [ point
.canvasy
, axisY
];
950 baseline
[point
.canvasx
] = [ point
.canvasy
, prevYs
[0] ];
953 baseline
[point
.canvasx
] = point
.canvasy
;
957 newYs
= [ point
.canvasy
, axisY
];
960 ctx
.moveTo(prevX
, prevYs
[0]);
963 ctx
.lineTo(point
.canvasx
, prevYs
[0]);
965 // Draw to the bottom of the baseline
966 ctx
.lineTo(point
.canvasx
, currBaseline
[1]);
968 ctx
.lineTo(point
.canvasx
, newYs
[1]);
971 ctx
.lineTo(point
.canvasx
, newYs
[0]);
972 ctx
.lineTo(point
.canvasx
, newYs
[1]);
975 ctx
.lineTo(prevX
, prevYs
[1]);
979 prevX
= point
.canvasx
;
987 // Drawing the lines.
988 for (i
= 0; i
< setCount
; i
+= 1) {
989 this._drawLine(ctx
, i
);
994 * This does dashed lines onto a canvas for a given pattern. You must call
995 * ctx.stroke() after to actually draw it, much line ctx.lineTo(). It remembers
996 * the state of the line in regards to where we left off on drawing the pattern.
997 * You can draw a dashed line in several function calls and the pattern will be
998 * continous as long as you didn't call this function with a different pattern
1000 * @param ctx The canvas 2d context to draw on.
1001 * @param x The start of the line's x coordinate.
1002 * @param y The start of the line's y coordinate.
1003 * @param x2 The end of the line's x coordinate.
1004 * @param y2 The end of the line's y coordinate.
1005 * @param pattern The dash pattern to draw, an array of integers where even
1006 * index is drawn and odd index is not drawn (Ex. [10, 2, 5, 2], 10 is drawn 5
1007 * is drawn, 2 is the space between.). A null pattern, array of length one, or
1008 * empty array will do just a solid line.
1011 DygraphCanvasRenderer
.prototype._dashedLine
= function(ctx
, x
, y
, x2
, y2
, pattern
) {
1012 // Original version http://stackoverflow.com/questions
/4576724/dotted-stroke
-in-canvas
1013 // Modified by Russell Valentine to keep line history and continue the pattern
1014 // where it left off.
1015 var dx
, dy
, len
, rot
, patternIndex
, segment
;
1017 // If we don't have a pattern or it is an empty array or of size one just
1019 if (!pattern
|| pattern
.length
<= 1) {
1025 // If we have a different dash pattern than the last time this was called we
1026 // reset our dash history and start the pattern from the begging
1027 // regardless of state of the last pattern.
1028 if (!Dygraph
.compareArrays(pattern
, this._dashedLineToHistoryPattern
)) {
1029 this._dashedLineToHistoryPattern
= pattern
;
1030 this._dashedLineToHistory
= [0, 0];
1034 // Calculate transformation parameters
1037 len
= Math
.sqrt(dx
*dx
+ dy
*dy
);
1038 rot
= Math
.atan2(dy
, dx
);
1040 // Set transformation
1041 ctx
.translate(x
, y
);
1045 // Set last pattern index we used for this pattern.
1046 patternIndex
= this._dashedLineToHistory
[0];
1049 // Get the length of the pattern segment we are dealing with.
1050 segment
= pattern
[patternIndex
];
1051 // If our last draw didn't complete the pattern segment all the way we
1052 // will try to finish it. Otherwise we will try to do the whole segment.
1053 if (this._dashedLineToHistory
[1]) {
1054 x
+= this._dashedLineToHistory
[1];
1059 // We were unable to complete this pattern index all the way, keep
1060 // where we are the history so our next draw continues where we left off
1062 this._dashedLineToHistory
= [patternIndex
, x
-len
];
1065 // We completed this patternIndex, we put in the history that we are on
1066 // the beginning of the next segment.
1067 this._dashedLineToHistory
= [(patternIndex
+1)%pattern
.length
, 0];
1070 // We do a line on a even pattern index and just move on a odd pattern index.
1071 // The move is the empty space in the dash.
1072 if(patternIndex
% 2 === 0) {
1077 // If we are not done, next loop process the next pattern segment, or the
1078 // first segment again if we are at the end of the pattern.
1079 patternIndex
= (patternIndex
+1) % pattern
.length
;