Merge pull request #148 from klausw-g/edge-points
[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 p.canvasy < this.area.y || p.canvasy > this.area.y + this.area.h) {
591 continue;
592 }
593
594 var a = p.annotation;
595 var tick_height = 6;
596 if (a.hasOwnProperty("tickHeight")) {
597 tick_height = a.tickHeight;
598 }
599
600 var div = document.createElement("div");
601 for (var name in annotationStyle) {
602 if (annotationStyle.hasOwnProperty(name)) {
603 div.style[name] = annotationStyle[name];
604 }
605 }
606 if (!a.hasOwnProperty('icon')) {
607 div.className = "dygraphDefaultAnnotation";
608 }
609 if (a.hasOwnProperty('cssClass')) {
610 div.className += " " + a.cssClass;
611 }
612
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");
617 img.src = a.icon;
618 img.width = width;
619 img.height = height;
620 div.appendChild(img);
621 } else if (p.annotation.hasOwnProperty('shortText')) {
622 div.appendChild(document.createTextNode(p.annotation.shortText));
623 }
624 div.style.left = (p.canvasx - width / 2) + "px";
625 if (a.attachAtBottom) {
626 div.style.top = (this.area.h - height - tick_height) + "px";
627 } else {
628 div.style.top = (p.canvasy - height - tick_height) + "px";
629 }
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];
635 a.div = div;
636
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));
645
646 this.container.appendChild(div);
647 this.annotations.push(div);
648
649 var ctx = this.elementContext;
650 ctx.strokeStyle = this.colors[p.name];
651 ctx.beginPath();
652 if (!a.attachAtBottom) {
653 ctx.moveTo(p.canvasx, p.canvasy);
654 ctx.lineTo(p.canvasx, p.canvasy - 2 - tick_height);
655 } else {
656 ctx.moveTo(p.canvasx, this.area.h);
657 ctx.lineTo(p.canvasx, this.area.h - 2 - tick_height);
658 }
659 ctx.closePath();
660 ctx.stroke();
661 }
662 };
663
664 DygraphCanvasRenderer.makeNextPointStep_ = function(
665 connect, points, start, end) {
666 if (connect) {
667 return function(j) {
668 while (++j + start < end) {
669 if (!(points[start + j].yval === null)) break;
670 }
671 return j;
672 }
673 } else {
674 return function(j) { return j + 1 };
675 }
676 };
677
678 DygraphCanvasRenderer.prototype._drawStyledLine = function(
679 ctx, i, setName, color, strokeWidth, strokePattern, drawPoints,
680 drawPointCallback, pointSize) {
681 var isNullOrNaN = function(x) {
682 return (x === null || isNaN(x));
683 };
684
685 var stepPlot = this.attr_("stepPlot");
686 var firstIndexInSet = this.layout.setPointsOffsets[i];
687 var setLength = this.layout.setPointsLengths[i];
688 var afterLastIndexInSet = firstIndexInSet + setLength;
689 var points = this.layout.points;
690 var prevX = null;
691 var prevY = null;
692 var nextY = null;
693 var pointsOnLine = []; // Array of [canvasx, canvasy] pairs.
694 if (!Dygraph.isArrayLike(strokePattern)) {
695 strokePattern = null;
696 }
697 var drawGapPoints = this.dygraph_.attr_('drawGapEdgePoints', setName);
698
699 var point, nextPoint;
700 var next = DygraphCanvasRenderer.makeNextPointStep_(
701 this.attr_('connectSeparatedPoints'), points, firstIndexInSet,
702 afterLastIndexInSet);
703 ctx.save();
704 for (var j = 0; j < setLength; j = next(j)) {
705 point = points[firstIndexInSet + j];
706 nextY = (next(j) < setLength) ?
707 points[firstIndexInSet + next(j)].canvasy : null;
708 if (isNullOrNaN(point.canvasy)) {
709 if (stepPlot && prevX !== null) {
710 // Draw a horizontal line to the start of the missing data
711 ctx.beginPath();
712 ctx.strokeStyle = color;
713 ctx.lineWidth = this.attr_('strokeWidth');
714 this._dashedLine(ctx, prevX, prevY, point.canvasx, prevY, strokePattern);
715 ctx.stroke();
716 }
717 // this will make us move to the next point, not draw a line to it.
718 prevX = prevY = null;
719 } else {
720 // A point is "isolated" if it is non-null but both the previous
721 // and next points are null.
722 var isIsolated = (!prevX && isNullOrNaN(nextY));
723 if (drawGapPoints) {
724 // Also consider a point to be is "isolated" if it's adjacent to a
725 // null point, excluding the graph edges.
726 if ((j > 0 && !prevX) ||
727 (next(j) < setLength && isNullOrNaN(nextY))) {
728 isIsolated = true;
729 }
730 }
731 if (prevX === null) {
732 prevX = point.canvasx;
733 prevY = point.canvasy;
734 } else {
735 // Skip over points that will be drawn in the same pixel.
736 if (Math.round(prevX) == Math.round(point.canvasx) &&
737 Math.round(prevY) == Math.round(point.canvasy)) {
738 continue;
739 }
740 // TODO(antrob): skip over points that lie on a line that is already
741 // going to be drawn. There is no need to have more than 2
742 // consecutive points that are collinear.
743 if (strokeWidth) {
744 ctx.beginPath();
745 ctx.strokeStyle = color;
746 ctx.lineWidth = strokeWidth;
747 if (stepPlot) {
748 this._dashedLine(ctx, prevX, prevY, point.canvasx, prevY, strokePattern);
749 prevX = point.canvasx;
750 }
751 this._dashedLine(ctx, prevX, prevY, point.canvasx, point.canvasy, strokePattern);
752 prevX = point.canvasx;
753 prevY = point.canvasy;
754 ctx.stroke();
755 }
756 }
757
758 if (drawPoints || isIsolated) {
759 pointsOnLine.push([point.canvasx, point.canvasy]);
760 }
761 }
762 }
763 for (var idx = 0; idx < pointsOnLine.length; idx++) {
764 var cb = pointsOnLine[idx];
765 ctx.save();
766 drawPointCallback(
767 this.dygraph_, setName, ctx, cb[0], cb[1], color, pointSize);
768 ctx.restore();
769 }
770 ctx.restore();
771 };
772
773 DygraphCanvasRenderer.prototype._drawLine = function(ctx, i) {
774 var setNames = this.layout.setNames;
775 var setName = setNames[i];
776
777 var strokeWidth = this.dygraph_.attr_("strokeWidth", setName);
778 var borderWidth = this.dygraph_.attr_("strokeBorderWidth", setName);
779 var drawPointCallback = this.dygraph_.attr_("drawPointCallback", setName) ||
780 Dygraph.Circles.DEFAULT;
781 if (borderWidth && strokeWidth) {
782 this._drawStyledLine(ctx, i, setName,
783 this.dygraph_.attr_("strokeBorderColor", setName),
784 strokeWidth + 2 * borderWidth,
785 this.dygraph_.attr_("strokePattern", setName),
786 this.dygraph_.attr_("drawPoints", setName),
787 drawPointCallback,
788 this.dygraph_.attr_("pointSize", setName));
789 }
790
791 this._drawStyledLine(ctx, i, setName,
792 this.colors[setName],
793 strokeWidth,
794 this.dygraph_.attr_("strokePattern", setName),
795 this.dygraph_.attr_("drawPoints", setName),
796 drawPointCallback,
797 this.dygraph_.attr_("pointSize", setName));
798 };
799
800 /**
801 * Actually draw the lines chart, including error bars.
802 * TODO(danvk): split this into several smaller functions.
803 * @private
804 */
805 DygraphCanvasRenderer.prototype._renderLineChart = function() {
806 // TODO(danvk): use this.attr_ for many of these.
807 var ctx = this.elementContext;
808 var fillAlpha = this.attr_('fillAlpha');
809 var errorBars = this.attr_("errorBars") || this.attr_("customBars");
810 var fillGraph = this.attr_("fillGraph");
811 var stackedGraph = this.attr_("stackedGraph");
812 var stepPlot = this.attr_("stepPlot");
813 var points = this.layout.points;
814 var pointsLength = points.length;
815 var point, i, j, prevX, prevY, prevYs, color, setName, newYs, err_color, rgb, yscale, axis;
816
817 var setNames = this.layout.setNames;
818 var setCount = setNames.length;
819
820 // TODO(danvk): Move this mapping into Dygraph and get it out of here.
821 this.colors = {};
822 for (i = 0; i < setCount; i++) {
823 this.colors[setNames[i]] = this.colorScheme_[i % this.colorScheme_.length];
824 }
825
826 // Update Points
827 // TODO(danvk): here
828 for (i = pointsLength; i--;) {
829 point = points[i];
830 point.canvasx = this.area.w * point.x + this.area.x;
831 point.canvasy = this.area.h * point.y + this.area.y;
832 }
833
834 // create paths
835 if (errorBars) {
836 ctx.save();
837 if (fillGraph) {
838 this.dygraph_.warn("Can't use fillGraph option with error bars");
839 }
840
841 for (i = 0; i < setCount; i++) {
842 setName = setNames[i];
843 axis = this.dygraph_.axisPropertiesForSeries(setName);
844 color = this.colors[setName];
845
846 var firstIndexInSet = this.layout.setPointsOffsets[i];
847 var setLength = this.layout.setPointsLengths[i];
848 var afterLastIndexInSet = firstIndexInSet + setLength;
849
850 var next = DygraphCanvasRenderer.makeNextPointStep_(
851 this.attr_('connectSeparatedPoints'), points,
852 afterLastIndexInSet);
853
854 // setup graphics context
855 prevX = NaN;
856 prevY = NaN;
857 prevYs = [-1, -1];
858 yscale = axis.yscale;
859 // should be same color as the lines but only 15% opaque.
860 rgb = new RGBColor(color);
861 err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
862 fillAlpha + ')';
863 ctx.fillStyle = err_color;
864 ctx.beginPath();
865 for (j = firstIndexInSet; j < afterLastIndexInSet; j = next(j)) {
866 point = points[j];
867 if (point.name == setName) { // TODO(klausw): this is always true
868 if (!Dygraph.isOK(point.y)) {
869 prevX = NaN;
870 continue;
871 }
872
873 // TODO(danvk): here
874 if (stepPlot) {
875 newYs = [ point.y_bottom, point.y_top ];
876 prevY = point.y;
877 } else {
878 newYs = [ point.y_bottom, point.y_top ];
879 }
880 newYs[0] = this.area.h * newYs[0] + this.area.y;
881 newYs[1] = this.area.h * newYs[1] + this.area.y;
882 if (!isNaN(prevX)) {
883 if (stepPlot) {
884 ctx.moveTo(prevX, newYs[0]);
885 } else {
886 ctx.moveTo(prevX, prevYs[0]);
887 }
888 ctx.lineTo(point.canvasx, newYs[0]);
889 ctx.lineTo(point.canvasx, newYs[1]);
890 if (stepPlot) {
891 ctx.lineTo(prevX, newYs[1]);
892 } else {
893 ctx.lineTo(prevX, prevYs[1]);
894 }
895 ctx.closePath();
896 }
897 prevYs = newYs;
898 prevX = point.canvasx;
899 }
900 }
901 ctx.fill();
902 }
903 ctx.restore();
904 } else if (fillGraph) {
905 ctx.save();
906 var baseline = {}; // for stacked graphs: baseline for filling
907 var currBaseline;
908
909 // process sets in reverse order (needed for stacked graphs)
910 for (i = setCount - 1; i >= 0; i--) {
911 setName = setNames[i];
912 color = this.colors[setName];
913 axis = this.dygraph_.axisPropertiesForSeries(setName);
914 var axisY = 1.0 + axis.minyval * axis.yscale;
915 if (axisY < 0.0) axisY = 0.0;
916 else if (axisY > 1.0) axisY = 1.0;
917 axisY = this.area.h * axisY + this.area.y;
918 var firstIndexInSet = this.layout.setPointsOffsets[i];
919 var setLength = this.layout.setPointsLengths[i];
920 var afterLastIndexInSet = firstIndexInSet + setLength;
921
922 var next = DygraphCanvasRenderer.makeNextPointStep_(
923 this.attr_('connectSeparatedPoints'), points,
924 afterLastIndexInSet);
925
926 // setup graphics context
927 prevX = NaN;
928 prevYs = [-1, -1];
929 yscale = axis.yscale;
930 // should be same color as the lines but only 15% opaque.
931 rgb = new RGBColor(color);
932 err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
933 fillAlpha + ')';
934 ctx.fillStyle = err_color;
935 ctx.beginPath();
936 for (j = firstIndexInSet; j < afterLastIndexInSet; j = next(j)) {
937 point = points[j];
938 if (point.name == setName) { // TODO(klausw): this is always true
939 if (!Dygraph.isOK(point.y)) {
940 prevX = NaN;
941 continue;
942 }
943 if (stackedGraph) {
944 currBaseline = baseline[point.canvasx];
945 var lastY;
946 if (currBaseline === undefined) {
947 lastY = axisY;
948 } else {
949 if(stepPlot) {
950 lastY = currBaseline[0];
951 } else {
952 lastY = currBaseline;
953 }
954 }
955 newYs = [ point.canvasy, lastY ];
956
957 if(stepPlot) {
958 // Step plots must keep track of the top and bottom of
959 // the baseline at each point.
960 if(prevYs[0] === -1) {
961 baseline[point.canvasx] = [ point.canvasy, axisY ];
962 } else {
963 baseline[point.canvasx] = [ point.canvasy, prevYs[0] ];
964 }
965 } else {
966 baseline[point.canvasx] = point.canvasy;
967 }
968
969 } else {
970 newYs = [ point.canvasy, axisY ];
971 }
972 if (!isNaN(prevX)) {
973 ctx.moveTo(prevX, prevYs[0]);
974
975 if (stepPlot) {
976 ctx.lineTo(point.canvasx, prevYs[0]);
977 if(currBaseline) {
978 // Draw to the bottom of the baseline
979 ctx.lineTo(point.canvasx, currBaseline[1]);
980 } else {
981 ctx.lineTo(point.canvasx, newYs[1]);
982 }
983 } else {
984 ctx.lineTo(point.canvasx, newYs[0]);
985 ctx.lineTo(point.canvasx, newYs[1]);
986 }
987
988 ctx.lineTo(prevX, prevYs[1]);
989 ctx.closePath();
990 }
991 prevYs = newYs;
992 prevX = point.canvasx;
993 }
994 }
995 ctx.fill();
996 }
997 ctx.restore();
998 }
999
1000 // Drawing the lines.
1001 for (i = 0; i < setCount; i += 1) {
1002 this._drawLine(ctx, i);
1003 }
1004 };
1005
1006 /**
1007 * This does dashed lines onto a canvas for a given pattern. You must call
1008 * ctx.stroke() after to actually draw it, much line ctx.lineTo(). It remembers
1009 * the state of the line in regards to where we left off on drawing the pattern.
1010 * You can draw a dashed line in several function calls and the pattern will be
1011 * continous as long as you didn't call this function with a different pattern
1012 * in between.
1013 * @param ctx The canvas 2d context to draw on.
1014 * @param x The start of the line's x coordinate.
1015 * @param y The start of the line's y coordinate.
1016 * @param x2 The end of the line's x coordinate.
1017 * @param y2 The end of the line's y coordinate.
1018 * @param pattern The dash pattern to draw, an array of integers where even
1019 * index is drawn and odd index is not drawn (Ex. [10, 2, 5, 2], 10 is drawn 5
1020 * is drawn, 2 is the space between.). A null pattern, array of length one, or
1021 * empty array will do just a solid line.
1022 * @private
1023 */
1024 DygraphCanvasRenderer.prototype._dashedLine = function(ctx, x, y, x2, y2, pattern) {
1025 // Original version http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
1026 // Modified by Russell Valentine to keep line history and continue the pattern
1027 // where it left off.
1028 var dx, dy, len, rot, patternIndex, segment;
1029
1030 // If we don't have a pattern or it is an empty array or of size one just
1031 // do a solid line.
1032 if (!pattern || pattern.length <= 1) {
1033 ctx.moveTo(x, y);
1034 ctx.lineTo(x2, y2);
1035 return;
1036 }
1037
1038 // If we have a different dash pattern than the last time this was called we
1039 // reset our dash history and start the pattern from the begging
1040 // regardless of state of the last pattern.
1041 if (!Dygraph.compareArrays(pattern, this._dashedLineToHistoryPattern)) {
1042 this._dashedLineToHistoryPattern = pattern;
1043 this._dashedLineToHistory = [0, 0];
1044 }
1045 ctx.save();
1046
1047 // Calculate transformation parameters
1048 dx = (x2-x);
1049 dy = (y2-y);
1050 len = Math.sqrt(dx*dx + dy*dy);
1051 rot = Math.atan2(dy, dx);
1052
1053 // Set transformation
1054 ctx.translate(x, y);
1055 ctx.moveTo(0, 0);
1056 ctx.rotate(rot);
1057
1058 // Set last pattern index we used for this pattern.
1059 patternIndex = this._dashedLineToHistory[0];
1060 x = 0;
1061 while (len > x) {
1062 // Get the length of the pattern segment we are dealing with.
1063 segment = pattern[patternIndex];
1064 // If our last draw didn't complete the pattern segment all the way we
1065 // will try to finish it. Otherwise we will try to do the whole segment.
1066 if (this._dashedLineToHistory[1]) {
1067 x += this._dashedLineToHistory[1];
1068 } else {
1069 x += segment;
1070 }
1071 if (x > len) {
1072 // We were unable to complete this pattern index all the way, keep
1073 // where we are the history so our next draw continues where we left off
1074 // in the pattern.
1075 this._dashedLineToHistory = [patternIndex, x-len];
1076 x = len;
1077 } else {
1078 // We completed this patternIndex, we put in the history that we are on
1079 // the beginning of the next segment.
1080 this._dashedLineToHistory = [(patternIndex+1)%pattern.length, 0];
1081 }
1082
1083 // We do a line on a even pattern index and just move on a odd pattern index.
1084 // The move is the empty space in the dash.
1085 if(patternIndex % 2 === 0) {
1086 ctx.lineTo(x, 0);
1087 } else {
1088 ctx.moveTo(x, 0);
1089 }
1090 // If we are not done, next loop process the next pattern segment, or the
1091 // first segment again if we are at the end of the pattern.
1092 patternIndex = (patternIndex+1) % pattern.length;
1093 }
1094 ctx.restore();
1095 };