Fix NaN handling for stacked graphs.
[dygraphs.git] / dygraph-canvas.js
1 /**
2 * @license
3 * Copyright 2006 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
5 */
6
7 /**
8 * @fileoverview Based on PlotKit.CanvasRenderer, but modified to meet the
9 * needs of dygraphs.
10 *
11 * In particular, support for:
12 * - grid overlays
13 * - error bars
14 * - dygraphs attribute system
15 */
16
17 /**
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.
24 * @constructor
25 */
26
27 /*jshint globalstrict: true */
28 /*global Dygraph:false,RGBColor:false */
29 "use strict";
30
31
32 var DygraphCanvasRenderer = function(dygraph, element, elementContext, layout) {
33 this.dygraph_ = dygraph;
34
35 this.layout = layout;
36 this.element = element;
37 this.elementContext = elementContext;
38 this.container = this.element.parentNode;
39
40 this.height = this.element.height;
41 this.width = this.element.width;
42
43 // --- check whether everything is ok before we return
44 if (!this.isIE && !(DygraphCanvasRenderer.isSupported(this.element)))
45 throw "Canvas is not supported.";
46
47 // internal state
48 this.xlabels = [];
49 this.ylabels = [];
50 this.annotations = [];
51 this.chartLabels = {};
52
53 this.area = layout.getPlotArea();
54 this.container.style.position = "relative";
55 this.container.style.width = this.width + "px";
56
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();
61 } else {
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_;
66 ctx.beginPath();
67 ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h);
68 ctx.clip();
69
70 ctx = this.dygraph_.hidden_ctx_;
71 ctx.beginPath();
72 ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h);
73 ctx.clip();
74 }
75 }
76 };
77
78 DygraphCanvasRenderer.prototype.attr_ = function(x) {
79 return this.dygraph_.attr_(x);
80 };
81
82 DygraphCanvasRenderer.prototype.clear = function() {
83 var context;
84 if (this.isIE) {
85 // VML takes a while to start up, so we just poll every this.IEDelay
86 try {
87 if (this.clearDelay) {
88 this.clearDelay.cancel();
89 this.clearDelay = null;
90 }
91 context = this.elementContext;
92 }
93 catch (e) {
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));
97 return;
98 }
99 }
100
101 context = this.elementContext;
102 context.clearRect(0, 0, this.width, this.height);
103
104 function removeArray(ary) {
105 for (var i = 0; i < ary.length; i++) {
106 var el = ary[i];
107 if (el.parentNode) el.parentNode.removeChild(el);
108 }
109 }
110
111 removeArray(this.xlabels);
112 removeArray(this.ylabels);
113 removeArray(this.annotations);
114
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);
119 }
120 this.xlabels = [];
121 this.ylabels = [];
122 this.annotations = [];
123 this.chartLabels = {};
124 };
125
126
127 DygraphCanvasRenderer.isSupported = function(canvasName) {
128 var canvas = null;
129 try {
130 if (typeof(canvasName) == 'undefined' || canvasName === null) {
131 canvas = document.createElement("canvas");
132 } else {
133 canvas = canvasName;
134 }
135 canvas.getContext("2d");
136 }
137 catch (e) {
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))
141 return false;
142 return true;
143 }
144 return true;
145 };
146
147 /**
148 * @param { [String] } colors Array of color strings. Should have one entry for
149 * each series to be rendered.
150 */
151 DygraphCanvasRenderer.prototype.setColors = function(colors) {
152 this.colorScheme_ = colors;
153 };
154
155 /**
156 * Draw an X/Y grid on top of the existing plot
157 */
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; }
164
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_);
169 }
170
171 var x, y, i, ticks;
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().
175 ctx.save();
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);
183 ctx.beginPath();
184 ctx.moveTo(x, y);
185 ctx.lineTo(x + this.area.w, y);
186 ctx.closePath();
187 ctx.stroke();
188 }
189 ctx.restore();
190 }
191
192 if (this.attr_('drawXGrid')) {
193 ticks = this.layout.xticks;
194 ctx.save();
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);
200 ctx.beginPath();
201 ctx.moveTo(x, y);
202 ctx.lineTo(x, this.area.y);
203 ctx.closePath();
204 ctx.stroke();
205 }
206 ctx.restore();
207 }
208
209 // Do the ordinary rendering, as before
210 this._renderLineChart();
211 this._renderAxis();
212 this._renderChartLabels();
213 this._renderAnnotations();
214 };
215
216 DygraphCanvasRenderer.prototype._createIEClipArea = function() {
217 var className = 'dygraph-clip-div';
218 var graphDiv = this.dygraph_.graphDiv;
219
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]);
224 }
225 }
226
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;
234 break;
235 }
236 element = element.parentNode;
237 }
238
239 function createClipDiv(area) {
240 if (area.w === 0 || area.h === 0) {
241 return;
242 }
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);
252 }
253
254 var plotArea = this.area;
255 // Left side
256 createClipDiv({
257 x:0, y:0,
258 w:plotArea.x,
259 h:this.height
260 });
261
262 // Top
263 createClipDiv({
264 x: plotArea.x, y: 0,
265 w: this.width - plotArea.x,
266 h: plotArea.y
267 });
268
269 // Right side
270 createClipDiv({
271 x: plotArea.x + plotArea.w, y: 0,
272 w: this.width-plotArea.x - plotArea.w,
273 h: this.height
274 });
275
276 // Bottom
277 createClipDiv({
278 x: plotArea.x,
279 y: plotArea.y + plotArea.h,
280 w: this.width - plotArea.x,
281 h: this.height - plotArea.h - plotArea.y
282 });
283 };
284
285 DygraphCanvasRenderer.prototype._renderAxis = function() {
286 if (!this.attr_('drawXAxis') && !this.attr_('drawYAxis')) return;
287
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; }
291
292 var context = this.elementContext;
293
294 var label, x, y, tick, i;
295
296 var labelStyle = {
297 position: "absolute",
298 fontSize: this.attr_('axisLabelFontSize') + "px",
299 zIndex: 10,
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.
304 overflow: "hidden"
305 };
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];
311 }
312 }
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);
319 return div;
320 };
321
322 // axis lines
323 context.save();
324 context.strokeStyle = this.attr_('axisLineColor');
325 context.lineWidth = this.attr_('axisLineWidth');
326
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;
333 x = this.area.x;
334 var sgn = 1;
335 var prec_axis = 'y1';
336 if (tick[0] == 1) { // right-side y-axis
337 x = this.area.x + this.area.w;
338 sgn = -1;
339 prec_axis = 'y2';
340 }
341 y = this.area.y + tick[1] * this.area.h;
342
343 /* Tick marks are currently clipped, so don't bother drawing them.
344 context.beginPath();
345 context.moveTo(halfUp(x), halfDown(y));
346 context.lineTo(halfUp(x - sgn * this.attr_('axisTickSize')), halfDown(y));
347 context.closePath();
348 context.stroke();
349 */
350
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;
354
355 if (top + this.attr_('axisLabelFontSize') + 3 > this.height) {
356 label.style.bottom = "0px";
357 } else {
358 label.style.top = top + "px";
359 }
360 if (tick[0] === 0) {
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";
367 }
368 label.style.width = this.attr_('yAxisLabelWidth') + "px";
369 this.container.appendChild(label);
370 this.ylabels.push(label);
371 }
372
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";
382 }
383 }
384
385 // draw a vertical line on the left to separate the chart from the labels.
386 context.beginPath();
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));
389 context.closePath();
390 context.stroke();
391
392 // if there's a secondary y-axis, draw a vertical line for that, too.
393 if (this.dygraph_.numAxes() == 2) {
394 context.beginPath();
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));
397 context.closePath();
398 context.stroke();
399 }
400 }
401
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;
408
409 /* Tick marks are currently clipped, so don't bother drawing them.
410 context.beginPath();
411 context.moveTo(halfUp(x), halfDown(y));
412 context.lineTo(halfUp(x), halfDown(y + this.attr_('axisTickSize')));
413 context.closePath();
414 context.stroke();
415 */
416
417 label = makeDiv(tick[1], 'x');
418 label.style.textAlign = "center";
419 label.style.top = (y + this.attr_('axisTickSize')) + 'px';
420
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";
425 }
426 if (left < 0) {
427 left = 0;
428 label.style.textAlign = "left";
429 }
430
431 label.style.left = left + "px";
432 label.style.width = this.attr_('xAxisLabelWidth') + "px";
433 this.container.appendChild(label);
434 this.xlabels.push(label);
435 }
436 }
437
438 context.beginPath();
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));
441 context.closePath();
442 context.stroke();
443 }
444
445 context.restore();
446 };
447
448
449 DygraphCanvasRenderer.prototype._renderChartLabels = function() {
450 var div, class_div;
451
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;
471 }
472
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';
482
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;
489 }
490
491 var that = this;
492 function createRotatedDiv(axis, classes, html) {
493 var box = {
494 left: 0,
495 top: that.area.y,
496 width: that.attr_('yLabelWidth'),
497 height: that.area.h
498 };
499 // TODO(danvk): is this outer div actually necessary?
500 div = document.createElement("div");
501 div.style.position = 'absolute';
502 if (axis == 1) {
503 div.style.left = box.left;
504 } else {
505 div.style.right = box.left;
506 }
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';
511
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';
519
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
528
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';
539 }
540
541 class_div = document.createElement("div");
542 class_div.className = classes;
543 class_div.innerHTML = html;
544
545 inner_div.appendChild(class_div);
546 div.appendChild(inner_div);
547 return div;
548 }
549
550 var 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;
556 }
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;
562 }
563 };
564
565
566 DygraphCanvasRenderer.prototype._renderAnnotations = function() {
567 var annotationStyle = {
568 "position": "absolute",
569 "fontSize": this.attr_('axisLabelFontSize') + "px",
570 "zIndex": 10,
571 "overflow": "hidden"
572 };
573
574 var bindEvt = function(eventName, classEventName, p, self) {
575 return function(e) {
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 );
581 }
582 };
583 };
584
585 // Get a list of point with annotations.
586 var points = this.layout.annotated_points;
587 for (var i = 0; i < points.length; i++) {
588 var p = points[i];
589 if (p.canvasx < this.area.x || p.canvasx > this.area.x + this.area.w) {
590 continue;
591 }
592
593 var a = p.annotation;
594 var tick_height = 6;
595 if (a.hasOwnProperty("tickHeight")) {
596 tick_height = a.tickHeight;
597 }
598
599 var div = document.createElement("div");
600 for (var name in annotationStyle) {
601 if (annotationStyle.hasOwnProperty(name)) {
602 div.style[name] = annotationStyle[name];
603 }
604 }
605 if (!a.hasOwnProperty('icon')) {
606 div.className = "dygraphDefaultAnnotation";
607 }
608 if (a.hasOwnProperty('cssClass')) {
609 div.className += " " + a.cssClass;
610 }
611
612 var width = a.hasOwnProperty('width') ? a.width : 16;
613 var height = a.hasOwnProperty('height') ? a.height : 16;
614 if (a.hasOwnProperty('icon')) {
615 var img = document.createElement("img");
616 img.src = a.icon;
617 img.width = width;
618 img.height = height;
619 div.appendChild(img);
620 } else if (p.annotation.hasOwnProperty('shortText')) {
621 div.appendChild(document.createTextNode(p.annotation.shortText));
622 }
623 div.style.left = (p.canvasx - width / 2) + "px";
624 if (a.attachAtBottom) {
625 div.style.top = (this.area.h - height - tick_height) + "px";
626 } else {
627 div.style.top = (p.canvasy - height - tick_height) + "px";
628 }
629 div.style.width = width + "px";
630 div.style.height = height + "px";
631 div.title = p.annotation.text;
632 div.style.color = this.colors[p.name];
633 div.style.borderColor = this.colors[p.name];
634 a.div = div;
635
636 Dygraph.addEvent(div, 'click',
637 bindEvt('clickHandler', 'annotationClickHandler', p, this));
638 Dygraph.addEvent(div, 'mouseover',
639 bindEvt('mouseOverHandler', 'annotationMouseOverHandler', p, this));
640 Dygraph.addEvent(div, 'mouseout',
641 bindEvt('mouseOutHandler', 'annotationMouseOutHandler', p, this));
642 Dygraph.addEvent(div, 'dblclick',
643 bindEvt('dblClickHandler', 'annotationDblClickHandler', p, this));
644
645 this.container.appendChild(div);
646 this.annotations.push(div);
647
648 var ctx = this.elementContext;
649 ctx.strokeStyle = this.colors[p.name];
650 ctx.beginPath();
651 if (!a.attachAtBottom) {
652 ctx.moveTo(p.canvasx, p.canvasy);
653 ctx.lineTo(p.canvasx, p.canvasy - 2 - tick_height);
654 } else {
655 ctx.moveTo(p.canvasx, this.area.h);
656 ctx.lineTo(p.canvasx, this.area.h - 2 - tick_height);
657 }
658 ctx.closePath();
659 ctx.stroke();
660 }
661 };
662
663 DygraphCanvasRenderer.makeNextPointStep_ = function(connect, points, end) {
664 if (connect) {
665 return function(j) {
666 while (++j < end) {
667 if (!(points[j].yval === null)) break;
668 }
669 return j;
670 }
671 } else {
672 return function(j) { return j + 1 };
673 }
674 };
675
676 DygraphCanvasRenderer.prototype._drawStyledLine = function(
677 ctx, i, setName, color, strokeWidth, strokePattern, drawPoints,
678 drawPointCallback, pointSize) {
679 var isNullOrNaN = function(x) {
680 return (x === null || isNaN(x));
681 };
682
683 var stepPlot = this.attr_("stepPlot");
684 var firstIndexInSet = this.layout.setPointsOffsets[i];
685 var setLength = this.layout.setPointsLengths[i];
686 var afterLastIndexInSet = firstIndexInSet + setLength;
687 var points = this.layout.points;
688 var prevX = null;
689 var prevY = null;
690 var pointsOnLine = []; // Array of [canvasx, canvasy] pairs.
691 if (!Dygraph.isArrayLike(strokePattern)) {
692 strokePattern = null;
693 }
694
695 var point;
696 var next = DygraphCanvasRenderer.makeNextPointStep_(
697 this.attr_('connectSeparatedPoints'), points, afterLastIndexInSet);
698 ctx.save();
699 for (var j = firstIndexInSet; j < afterLastIndexInSet; j = next(j)) {
700 point = points[j];
701 if (isNullOrNaN(point.canvasy)) {
702 if (stepPlot && prevX !== null) {
703 // Draw a horizontal line to the start of the missing data
704 ctx.beginPath();
705 ctx.strokeStyle = color;
706 ctx.lineWidth = this.attr_('strokeWidth');
707 this._dashedLine(ctx, prevX, prevY, point.canvasx, prevY, strokePattern);
708 ctx.stroke();
709 }
710 // this will make us move to the next point, not draw a line to it.
711 prevX = prevY = null;
712 } else {
713 // A point is "isolated" if it is non-null but both the previous
714 // and next points are null.
715 var isIsolated = (!prevX && (j == points.length - 1 ||
716 isNullOrNaN(points[j+1].canvasy)));
717 if (prevX === null) {
718 prevX = point.canvasx;
719 prevY = point.canvasy;
720 } else {
721 // Skip over points that will be drawn in the same pixel.
722 if (Math.round(prevX) == Math.round(point.canvasx) &&
723 Math.round(prevY) == Math.round(point.canvasy)) {
724 continue;
725 }
726 // TODO(antrob): skip over points that lie on a line that is already
727 // going to be drawn. There is no need to have more than 2
728 // consecutive points that are collinear.
729 if (strokeWidth) {
730 ctx.beginPath();
731 ctx.strokeStyle = color;
732 ctx.lineWidth = strokeWidth;
733 if (stepPlot) {
734 this._dashedLine(ctx, prevX, prevY, point.canvasx, prevY, strokePattern);
735 prevX = point.canvasx;
736 }
737 this._dashedLine(ctx, prevX, prevY, point.canvasx, point.canvasy, strokePattern);
738 prevX = point.canvasx;
739 prevY = point.canvasy;
740 ctx.stroke();
741 }
742 }
743
744 if (drawPoints || isIsolated) {
745 pointsOnLine.push([point.canvasx, point.canvasy]);
746 }
747 }
748 }
749 for (var idx = 0; idx < pointsOnLine.length; idx++) {
750 var cb = pointsOnLine[idx];
751 ctx.save();
752 drawPointCallback(
753 this.dygraph_, setName, ctx, cb[0], cb[1], color, pointSize);
754 ctx.restore();
755 }
756 ctx.restore();
757 };
758
759 DygraphCanvasRenderer.prototype._drawLine = function(ctx, i) {
760 var setNames = this.layout.setNames;
761 var setName = setNames[i];
762
763 var strokeWidth = this.dygraph_.attr_("strokeWidth", setName);
764 var borderWidth = this.dygraph_.attr_("strokeBorderWidth", setName);
765 var drawPointCallback = this.dygraph_.attr_("drawPointCallback", setName) ||
766 Dygraph.Circles.DEFAULT;
767 if (borderWidth && strokeWidth) {
768 this._drawStyledLine(ctx, i, setName,
769 this.dygraph_.attr_("strokeBorderColor", setName),
770 strokeWidth + 2 * borderWidth,
771 this.dygraph_.attr_("strokePattern", setName),
772 this.dygraph_.attr_("drawPoints", setName),
773 drawPointCallback,
774 this.dygraph_.attr_("pointSize", setName));
775 }
776
777 this._drawStyledLine(ctx, i, setName,
778 this.colors[setName],
779 strokeWidth,
780 this.dygraph_.attr_("strokePattern", setName),
781 this.dygraph_.attr_("drawPoints", setName),
782 drawPointCallback,
783 this.dygraph_.attr_("pointSize", setName));
784 };
785
786 /**
787 * Actually draw the lines chart, including error bars.
788 * TODO(danvk): split this into several smaller functions.
789 * @private
790 */
791 DygraphCanvasRenderer.prototype._renderLineChart = function() {
792 // TODO(danvk): use this.attr_ for many of these.
793 var ctx = this.elementContext;
794 var fillAlpha = this.attr_('fillAlpha');
795 var errorBars = this.attr_("errorBars") || this.attr_("customBars");
796 var fillGraph = this.attr_("fillGraph");
797 var stackedGraph = this.attr_("stackedGraph");
798 var stepPlot = this.attr_("stepPlot");
799 var points = this.layout.points;
800 var pointsLength = points.length;
801 var point, i, j, prevX, prevY, prevYs, color, setName, newYs, err_color, rgb, yscale, axis;
802
803 var setNames = this.layout.setNames;
804 var setCount = setNames.length;
805
806 // TODO(danvk): Move this mapping into Dygraph and get it out of here.
807 this.colors = {};
808 for (i = 0; i < setCount; i++) {
809 this.colors[setNames[i]] = this.colorScheme_[i % this.colorScheme_.length];
810 }
811
812 // Update Points
813 // TODO(danvk): here
814 for (i = pointsLength; i--;) {
815 point = points[i];
816 point.canvasx = this.area.w * point.x + this.area.x;
817 point.canvasy = this.area.h * point.y + this.area.y;
818 }
819
820 // create paths
821 if (errorBars) {
822 ctx.save();
823 if (fillGraph) {
824 this.dygraph_.warn("Can't use fillGraph option with error bars");
825 }
826
827 for (i = 0; i < setCount; i++) {
828 setName = setNames[i];
829 axis = this.dygraph_.axisPropertiesForSeries(setName);
830 color = this.colors[setName];
831
832 var firstIndexInSet = this.layout.setPointsOffsets[i];
833 var setLength = this.layout.setPointsLengths[i];
834 var afterLastIndexInSet = firstIndexInSet + setLength;
835
836 var next = DygraphCanvasRenderer.makeNextPointStep_(
837 this.attr_('connectSeparatedPoints'), points,
838 afterLastIndexInSet);
839
840 // setup graphics context
841 prevX = NaN;
842 prevY = NaN;
843 prevYs = [-1, -1];
844 yscale = axis.yscale;
845 // should be same color as the lines but only 15% opaque.
846 rgb = new RGBColor(color);
847 err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
848 fillAlpha + ')';
849 ctx.fillStyle = err_color;
850 ctx.beginPath();
851 for (j = firstIndexInSet; j < afterLastIndexInSet; j = next(j)) {
852 point = points[j];
853 if (point.name == setName) { // TODO(klausw): this is always true
854 if (!Dygraph.isOK(point.y)) {
855 prevX = NaN;
856 continue;
857 }
858
859 // TODO(danvk): here
860 if (stepPlot) {
861 newYs = [ point.y_bottom, point.y_top ];
862 prevY = point.y;
863 } else {
864 newYs = [ point.y_bottom, point.y_top ];
865 }
866 newYs[0] = this.area.h * newYs[0] + this.area.y;
867 newYs[1] = this.area.h * newYs[1] + this.area.y;
868 if (!isNaN(prevX)) {
869 if (stepPlot) {
870 ctx.moveTo(prevX, newYs[0]);
871 } else {
872 ctx.moveTo(prevX, prevYs[0]);
873 }
874 ctx.lineTo(point.canvasx, newYs[0]);
875 ctx.lineTo(point.canvasx, newYs[1]);
876 if (stepPlot) {
877 ctx.lineTo(prevX, newYs[1]);
878 } else {
879 ctx.lineTo(prevX, prevYs[1]);
880 }
881 ctx.closePath();
882 }
883 prevYs = newYs;
884 prevX = point.canvasx;
885 }
886 }
887 ctx.fill();
888 }
889 ctx.restore();
890 } else if (fillGraph) {
891 ctx.save();
892 var baseline = []; // for stacked graphs: baseline for filling
893
894 // process sets in reverse order (needed for stacked graphs)
895 for (i = setCount - 1; i >= 0; i--) {
896 setName = setNames[i];
897 color = this.colors[setName];
898 axis = this.dygraph_.axisPropertiesForSeries(setName);
899 var axisY = 1.0 + axis.minyval * axis.yscale;
900 if (axisY < 0.0) axisY = 0.0;
901 else if (axisY > 1.0) axisY = 1.0;
902 axisY = this.area.h * axisY + this.area.y;
903 var firstIndexInSet = this.layout.setPointsOffsets[i];
904 var setLength = this.layout.setPointsLengths[i];
905 var afterLastIndexInSet = firstIndexInSet + setLength;
906
907 var next = DygraphCanvasRenderer.makeNextPointStep_(
908 this.attr_('connectSeparatedPoints'), points,
909 afterLastIndexInSet);
910
911 // setup graphics context
912 prevX = NaN;
913 prevYs = [-1, -1];
914 yscale = axis.yscale;
915 // should be same color as the lines but only 15% opaque.
916 rgb = new RGBColor(color);
917 err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
918 fillAlpha + ')';
919 ctx.fillStyle = err_color;
920 ctx.beginPath();
921 for (j = firstIndexInSet; j < afterLastIndexInSet; j = next(j)) {
922 point = points[j];
923 if (point.name == setName) { // TODO(klausw): this is always true
924 if (!Dygraph.isOK(point.y)) {
925 prevX = NaN;
926 continue;
927 }
928 if (stackedGraph) {
929 var lastY = baseline[point.canvasx];
930 if (lastY === undefined) lastY = axisY;
931 baseline[point.canvasx] = point.canvasy;
932 newYs = [ point.canvasy, lastY ];
933 } else {
934 newYs = [ point.canvasy, axisY ];
935 }
936 if (!isNaN(prevX)) {
937 ctx.moveTo(prevX, prevYs[0]);
938 if (stepPlot) {
939 ctx.lineTo(point.canvasx, prevYs[0]);
940 } else {
941 ctx.lineTo(point.canvasx, newYs[0]);
942 }
943 ctx.lineTo(point.canvasx, newYs[1]);
944 ctx.lineTo(prevX, prevYs[1]);
945 ctx.closePath();
946 }
947 prevYs = newYs;
948 prevX = point.canvasx;
949 }
950 }
951 ctx.fill();
952 }
953 ctx.restore();
954 }
955
956 // Drawing the lines.
957 for (i = 0; i < setCount; i += 1) {
958 this._drawLine(ctx, i);
959 }
960 };
961
962 /**
963 * This does dashed lines onto a canvas for a given pattern. You must call
964 * ctx.stroke() after to actually draw it, much line ctx.lineTo(). It remembers
965 * the state of the line in regards to where we left off on drawing the pattern.
966 * You can draw a dashed line in several function calls and the pattern will be
967 * continous as long as you didn't call this function with a different pattern
968 * in between.
969 * @param ctx The canvas 2d context to draw on.
970 * @param x The start of the line's x coordinate.
971 * @param y The start of the line's y coordinate.
972 * @param x2 The end of the line's x coordinate.
973 * @param y2 The end of the line's y coordinate.
974 * @param pattern The dash pattern to draw, an array of integers where even
975 * index is drawn and odd index is not drawn (Ex. [10, 2, 5, 2], 10 is drawn 5
976 * is drawn, 2 is the space between.). A null pattern, array of length one, or
977 * empty array will do just a solid line.
978 * @private
979 */
980 DygraphCanvasRenderer.prototype._dashedLine = function(ctx, x, y, x2, y2, pattern) {
981 // Original version http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
982 // Modified by Russell Valentine to keep line history and continue the pattern
983 // where it left off.
984 var dx, dy, len, rot, patternIndex, segment;
985
986 // If we don't have a pattern or it is an empty array or of size one just
987 // do a solid line.
988 if (!pattern || pattern.length <= 1) {
989 ctx.moveTo(x, y);
990 ctx.lineTo(x2, y2);
991 return;
992 }
993
994 // If we have a different dash pattern than the last time this was called we
995 // reset our dash history and start the pattern from the begging
996 // regardless of state of the last pattern.
997 if (!Dygraph.compareArrays(pattern, this._dashedLineToHistoryPattern)) {
998 this._dashedLineToHistoryPattern = pattern;
999 this._dashedLineToHistory = [0, 0];
1000 }
1001 ctx.save();
1002
1003 // Calculate transformation parameters
1004 dx = (x2-x);
1005 dy = (y2-y);
1006 len = Math.sqrt(dx*dx + dy*dy);
1007 rot = Math.atan2(dy, dx);
1008
1009 // Set transformation
1010 ctx.translate(x, y);
1011 ctx.moveTo(0, 0);
1012 ctx.rotate(rot);
1013
1014 // Set last pattern index we used for this pattern.
1015 patternIndex = this._dashedLineToHistory[0];
1016 x = 0;
1017 while (len > x) {
1018 // Get the length of the pattern segment we are dealing with.
1019 segment = pattern[patternIndex];
1020 // If our last draw didn't complete the pattern segment all the way we
1021 // will try to finish it. Otherwise we will try to do the whole segment.
1022 if (this._dashedLineToHistory[1]) {
1023 x += this._dashedLineToHistory[1];
1024 } else {
1025 x += segment;
1026 }
1027 if (x > len) {
1028 // We were unable to complete this pattern index all the way, keep
1029 // where we are the history so our next draw continues where we left off
1030 // in the pattern.
1031 this._dashedLineToHistory = [patternIndex, x-len];
1032 x = len;
1033 } else {
1034 // We completed this patternIndex, we put in the history that we are on
1035 // the beginning of the next segment.
1036 this._dashedLineToHistory = [(patternIndex+1)%pattern.length, 0];
1037 }
1038
1039 // We do a line on a even pattern index and just move on a odd pattern index.
1040 // The move is the empty space in the dash.
1041 if(patternIndex % 2 === 0) {
1042 ctx.lineTo(x, 0);
1043 } else {
1044 ctx.moveTo(x, 0);
1045 }
1046 // If we are not done, next loop process the next pattern segment, or the
1047 // first segment again if we are at the end of the pattern.
1048 patternIndex = (patternIndex+1) % pattern.length;
1049 }
1050 ctx.restore();
1051 };