Standardize isNullOrNan.
[dygraphs.git] / dygraph-canvas.js
... / ...
CommitLineData
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
32var 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
78DygraphCanvasRenderer.prototype.attr_ = function(x) {
79 return this.dygraph_.attr_(x);
80};
81
82DygraphCanvasRenderer.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
127DygraphCanvasRenderer.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 */
151DygraphCanvasRenderer.prototype.setColors = function(colors) {
152 this.colorScheme_ = colors;
153};
154
155/**
156 * Draw an X/Y grid on top of the existing plot
157 */
158DygraphCanvasRenderer.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
216DygraphCanvasRenderer.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
285DygraphCanvasRenderer.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 var axisX;
387 if (this.attr_('drawAxesAtZero')) {
388 var r = this.dygraph_.toPercentXCoord(0);
389 if (r > 1 || r < 0) r = 0;
390 axisX = halfUp(this.area.x + r * this.area.w);
391 } else {
392 axisX = halfUp(this.area.x);
393 }
394 context.beginPath();
395 context.moveTo(axisX, halfDown(this.area.y));
396 context.lineTo(axisX, halfDown(this.area.y + this.area.h));
397 context.closePath();
398 context.stroke();
399
400 // if there's a secondary y-axis, draw a vertical line for that, too.
401 if (this.dygraph_.numAxes() == 2) {
402 context.beginPath();
403 context.moveTo(halfDown(this.area.x + this.area.w), halfDown(this.area.y));
404 context.lineTo(halfDown(this.area.x + this.area.w), halfDown(this.area.y + this.area.h));
405 context.closePath();
406 context.stroke();
407 }
408 }
409
410 if (this.attr_('drawXAxis')) {
411 if (this.layout.xticks) {
412 for (i = 0; i < this.layout.xticks.length; i++) {
413 tick = this.layout.xticks[i];
414 x = this.area.x + tick[0] * this.area.w;
415 y = this.area.y + this.area.h;
416
417 /* Tick marks are currently clipped, so don't bother drawing them.
418 context.beginPath();
419 context.moveTo(halfUp(x), halfDown(y));
420 context.lineTo(halfUp(x), halfDown(y + this.attr_('axisTickSize')));
421 context.closePath();
422 context.stroke();
423 */
424
425 label = makeDiv(tick[1], 'x');
426 label.style.textAlign = "center";
427 label.style.top = (y + this.attr_('axisTickSize')) + 'px';
428
429 var left = (x - this.attr_('axisLabelWidth')/2);
430 if (left + this.attr_('axisLabelWidth') > this.width) {
431 left = this.width - this.attr_('xAxisLabelWidth');
432 label.style.textAlign = "right";
433 }
434 if (left < 0) {
435 left = 0;
436 label.style.textAlign = "left";
437 }
438
439 label.style.left = left + "px";
440 label.style.width = this.attr_('xAxisLabelWidth') + "px";
441 this.container.appendChild(label);
442 this.xlabels.push(label);
443 }
444 }
445
446 context.beginPath();
447 var axisY;
448 if (this.attr_('drawAxesAtZero')) {
449 var r = this.dygraph_.toPercentYCoord(0, 0);
450 if (r > 1 || r < 0) r = 1;
451 axisY = halfDown(this.area.y + r * this.area.h);
452 } else {
453 axisY = halfDown(this.area.y + this.area.h);
454 }
455 context.moveTo(halfUp(this.area.x), axisY);
456 context.lineTo(halfUp(this.area.x + this.area.w), axisY);
457 context.closePath();
458 context.stroke();
459 }
460
461 context.restore();
462};
463
464
465DygraphCanvasRenderer.prototype._renderChartLabels = function() {
466 var div, class_div;
467
468 // Generate divs for the chart title, xlabel and ylabel.
469 // Space for these divs has already been taken away from the charting area in
470 // the DygraphCanvasRenderer constructor.
471 if (this.attr_('title')) {
472 div = document.createElement("div");
473 div.style.position = 'absolute';
474 div.style.top = '0px';
475 div.style.left = this.area.x + 'px';
476 div.style.width = this.area.w + 'px';
477 div.style.height = this.attr_('titleHeight') + 'px';
478 div.style.textAlign = 'center';
479 div.style.fontSize = (this.attr_('titleHeight') - 8) + 'px';
480 div.style.fontWeight = 'bold';
481 class_div = document.createElement("div");
482 class_div.className = 'dygraph-label dygraph-title';
483 class_div.innerHTML = this.attr_('title');
484 div.appendChild(class_div);
485 this.container.appendChild(div);
486 this.chartLabels.title = div;
487 }
488
489 if (this.attr_('xlabel')) {
490 div = document.createElement("div");
491 div.style.position = 'absolute';
492 div.style.bottom = 0; // TODO(danvk): this is lazy. Calculate style.top.
493 div.style.left = this.area.x + 'px';
494 div.style.width = this.area.w + 'px';
495 div.style.height = this.attr_('xLabelHeight') + 'px';
496 div.style.textAlign = 'center';
497 div.style.fontSize = (this.attr_('xLabelHeight') - 2) + 'px';
498
499 class_div = document.createElement("div");
500 class_div.className = 'dygraph-label dygraph-xlabel';
501 class_div.innerHTML = this.attr_('xlabel');
502 div.appendChild(class_div);
503 this.container.appendChild(div);
504 this.chartLabels.xlabel = div;
505 }
506
507 var that = this;
508 function createRotatedDiv(axis, classes, html) {
509 var box = {
510 left: 0,
511 top: that.area.y,
512 width: that.attr_('yLabelWidth'),
513 height: that.area.h
514 };
515 // TODO(danvk): is this outer div actually necessary?
516 div = document.createElement("div");
517 div.style.position = 'absolute';
518 if (axis == 1) {
519 div.style.left = box.left;
520 } else {
521 div.style.right = box.left;
522 }
523 div.style.top = box.top + 'px';
524 div.style.width = box.width + 'px';
525 div.style.height = box.height + 'px';
526 div.style.fontSize = (that.attr_('yLabelWidth') - 2) + 'px';
527
528 var inner_div = document.createElement("div");
529 inner_div.style.position = 'absolute';
530 inner_div.style.width = box.height + 'px';
531 inner_div.style.height = box.width + 'px';
532 inner_div.style.top = (box.height / 2 - box.width / 2) + 'px';
533 inner_div.style.left = (box.width / 2 - box.height / 2) + 'px';
534 inner_div.style.textAlign = 'center';
535
536 // CSS rotation is an HTML5 feature which is not standardized. Hence every
537 // browser has its own name for the CSS style.
538 var val = 'rotate(' + (axis == 1 ? '-' : '') + '90deg)';
539 inner_div.style.transform = val; // HTML5
540 inner_div.style.WebkitTransform = val; // Safari/Chrome
541 inner_div.style.MozTransform = val; // Firefox
542 inner_div.style.OTransform = val; // Opera
543 inner_div.style.msTransform = val; // IE9
544
545 if (typeof(document.documentMode) !== 'undefined' &&
546 document.documentMode < 9) {
547 // We're dealing w/ an old version of IE, so we have to rotate the text
548 // using a BasicImage transform. This uses a different origin of rotation
549 // than HTML5 rotation (top left of div vs. its center).
550 inner_div.style.filter =
551 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' +
552 (axis == 1 ? '3' : '1') + ')';
553 inner_div.style.left = '0px';
554 inner_div.style.top = '0px';
555 }
556
557 class_div = document.createElement("div");
558 class_div.className = classes;
559 class_div.innerHTML = html;
560
561 inner_div.appendChild(class_div);
562 div.appendChild(inner_div);
563 return div;
564 }
565
566 var div;
567 if (this.attr_('ylabel')) {
568 div = createRotatedDiv(1, 'dygraph-label dygraph-ylabel',
569 this.attr_('ylabel'));
570 this.container.appendChild(div);
571 this.chartLabels.ylabel = div;
572 }
573 if (this.attr_('y2label') && this.dygraph_.numAxes() == 2) {
574 div = createRotatedDiv(2, 'dygraph-label dygraph-y2label',
575 this.attr_('y2label'));
576 this.container.appendChild(div);
577 this.chartLabels.y2label = div;
578 }
579};
580
581
582DygraphCanvasRenderer.prototype._renderAnnotations = function() {
583 var annotationStyle = {
584 "position": "absolute",
585 "fontSize": this.attr_('axisLabelFontSize') + "px",
586 "zIndex": 10,
587 "overflow": "hidden"
588 };
589
590 var bindEvt = function(eventName, classEventName, p, self) {
591 return function(e) {
592 var a = p.annotation;
593 if (a.hasOwnProperty(eventName)) {
594 a[eventName](a, p, self.dygraph_, e);
595 } else if (self.dygraph_.attr_(classEventName)) {
596 self.dygraph_.attr_(classEventName)(a, p, self.dygraph_,e );
597 }
598 };
599 };
600
601 // Get a list of point with annotations.
602 var points = this.layout.annotated_points;
603 for (var i = 0; i < points.length; i++) {
604 var p = points[i];
605 if (p.canvasx < this.area.x || p.canvasx > this.area.x + this.area.w ||
606 p.canvasy < this.area.y || p.canvasy > this.area.y + this.area.h) {
607 continue;
608 }
609
610 var a = p.annotation;
611 var tick_height = 6;
612 if (a.hasOwnProperty("tickHeight")) {
613 tick_height = a.tickHeight;
614 }
615
616 var div = document.createElement("div");
617 for (var name in annotationStyle) {
618 if (annotationStyle.hasOwnProperty(name)) {
619 div.style[name] = annotationStyle[name];
620 }
621 }
622 if (!a.hasOwnProperty('icon')) {
623 div.className = "dygraphDefaultAnnotation";
624 }
625 if (a.hasOwnProperty('cssClass')) {
626 div.className += " " + a.cssClass;
627 }
628
629 var width = a.hasOwnProperty('width') ? a.width : 16;
630 var height = a.hasOwnProperty('height') ? a.height : 16;
631 if (a.hasOwnProperty('icon')) {
632 var img = document.createElement("img");
633 img.src = a.icon;
634 img.width = width;
635 img.height = height;
636 div.appendChild(img);
637 } else if (p.annotation.hasOwnProperty('shortText')) {
638 div.appendChild(document.createTextNode(p.annotation.shortText));
639 }
640 div.style.left = (p.canvasx - width / 2) + "px";
641 if (a.attachAtBottom) {
642 div.style.top = (this.area.h - height - tick_height) + "px";
643 } else {
644 div.style.top = (p.canvasy - height - tick_height) + "px";
645 }
646 div.style.width = width + "px";
647 div.style.height = height + "px";
648 div.title = p.annotation.text;
649 div.style.color = this.colors[p.name];
650 div.style.borderColor = this.colors[p.name];
651 a.div = div;
652
653 this.dygraph_.addEvent(div, 'click',
654 bindEvt('clickHandler', 'annotationClickHandler', p, this));
655 this.dygraph_.addEvent(div, 'mouseover',
656 bindEvt('mouseOverHandler', 'annotationMouseOverHandler', p, this));
657 this.dygraph_.addEvent(div, 'mouseout',
658 bindEvt('mouseOutHandler', 'annotationMouseOutHandler', p, this));
659 this.dygraph_.addEvent(div, 'dblclick',
660 bindEvt('dblClickHandler', 'annotationDblClickHandler', p, this));
661
662 this.container.appendChild(div);
663 this.annotations.push(div);
664
665 var ctx = this.elementContext;
666 ctx.strokeStyle = this.colors[p.name];
667 ctx.beginPath();
668 if (!a.attachAtBottom) {
669 ctx.moveTo(p.canvasx, p.canvasy);
670 ctx.lineTo(p.canvasx, p.canvasy - 2 - tick_height);
671 } else {
672 ctx.moveTo(p.canvasx, this.area.h);
673 ctx.lineTo(p.canvasx, this.area.h - 2 - tick_height);
674 }
675 ctx.closePath();
676 ctx.stroke();
677 }
678};
679
680DygraphCanvasRenderer.makeNextPointStep_ = function(
681 connect, points, start, end) {
682 if (connect) {
683 return function(j) {
684 while (++j + start < end) {
685 if (!(points[start + j].yval === null)) break;
686 }
687 return j;
688 }
689 } else {
690 return function(j) { return j + 1 };
691 }
692};
693
694DygraphCanvasRenderer.isNullOrNaN_ = function(x) {
695 return (x === null || isNaN(x));
696};
697
698DygraphCanvasRenderer.prototype._drawStyledLine = function(
699 ctx, i, setName, color, strokeWidth, strokePattern, drawPoints,
700 drawPointCallback, pointSize) {
701 var stepPlot = this.attr_("stepPlot");
702 var firstIndexInSet = this.layout.setPointsOffsets[i];
703 var setLength = this.layout.setPointsLengths[i];
704 var points = this.layout.points;
705 if (!Dygraph.isArrayLike(strokePattern)) {
706 strokePattern = null;
707 }
708 var drawGapPoints = this.dygraph_.attr_('drawGapEdgePoints', setName);
709
710 ctx.save();
711 if (strokeWidth && !stepPlot && (!strokePattern || strokePattern.length <= 1)) {
712 this._drawTrivialLine(ctx, points, setLength, firstIndexInSet, setName, color, strokeWidth, drawPointCallback, pointSize, drawPoints, drawGapPoints);
713 } else {
714 this._drawNonTrivialLine(ctx, points, setLength, firstIndexInSet, setName, color, strokeWidth, strokePattern, drawPointCallback, pointSize, drawPoints, drawGapPoints, stepPlot);
715 }
716 ctx.restore();
717};
718
719DygraphCanvasRenderer.prototype._drawNonTrivialLine = function(
720 ctx, points, setLength, firstIndexInSet, setName, color, strokeWidth, strokePattern, drawPointCallback, pointSize, drawPoints, drawGapPoints, stepPlot) {
721 var prevX = null;
722 var prevY = null;
723 var nextY = null;
724 var point, nextPoint;
725 var pointsOnLine = []; // Array of [canvasx, canvasy] pairs.
726 var next = DygraphCanvasRenderer.makeNextPointStep_(
727 this.attr_('connectSeparatedPoints'), points, firstIndexInSet,
728 firstIndexInSet + setLength);
729 for (var j = 0; j < setLength; j = next(j)) {
730 point = points[firstIndexInSet + j];
731 nextY = (next(j) < setLength) ?
732 points[firstIndexInSet + next(j)].canvasy : null;
733 if (DygraphCanvasRenderer.isNullOrNaN_(point.canvasy)) {
734 if (stepPlot && prevX !== null) {
735 // Draw a horizontal line to the start of the missing data
736 ctx.beginPath();
737 ctx.strokeStyle = color;
738 ctx.lineWidth = this.attr_('strokeWidth');
739 this._dashedLine(ctx, prevX, prevY, point.canvasx, prevY, strokePattern);
740 ctx.stroke();
741 }
742 // this will make us move to the next point, not draw a line to it.
743 prevX = prevY = null;
744 } else {
745 // A point is "isolated" if it is non-null but both the previous
746 // and next points are null.
747 var isIsolated = (!prevX && DygraphCanvasRenderer.isNullOrNaN_(nextY));
748 if (drawGapPoints) {
749 // Also consider a point to be is "isolated" if it's adjacent to a
750 // null point, excluding the graph edges.
751 if ((j > 0 && !prevX) ||
752 (next(j) < setLength && DygraphCanvasRenderer.isNullOrNaN_(nextY))) {
753 isIsolated = true;
754 }
755 }
756 if (prevX === null) {
757 prevX = point.canvasx;
758 prevY = point.canvasy;
759 } else {
760 // Skip over points that will be drawn in the same pixel.
761 if (Math.round(prevX) == Math.round(point.canvasx) &&
762 Math.round(prevY) == Math.round(point.canvasy)) {
763 continue;
764 }
765 // TODO(antrob): skip over points that lie on a line that is already
766 // going to be drawn. There is no need to have more than 2
767 // consecutive points that are collinear.
768 if (strokeWidth) {
769 ctx.beginPath();
770 ctx.strokeStyle = color;
771 ctx.lineWidth = strokeWidth;
772 if (stepPlot) {
773 this._dashedLine(ctx, prevX, prevY, point.canvasx, prevY, strokePattern);
774 prevX = point.canvasx;
775 }
776 this._dashedLine(ctx, prevX, prevY, point.canvasx, point.canvasy, strokePattern);
777 prevX = point.canvasx;
778 prevY = point.canvasy;
779 ctx.stroke();
780 }
781 }
782
783 if (drawPoints || isIsolated) {
784 pointsOnLine.push([point.canvasx, point.canvasy]);
785 }
786 }
787 }
788 for (var idx = 0; idx < pointsOnLine.length; idx++) {
789 var cb = pointsOnLine[idx];
790 ctx.save();
791 drawPointCallback(
792 this.dygraph_, setName, ctx, cb[0], cb[1], color, pointSize);
793 ctx.restore();
794 }
795};
796
797DygraphCanvasRenderer.prototype._drawTrivialLine = function(
798 ctx, points, setLength, firstIndexInSet, setName, color, strokeWidth, drawPointCallback, pointSize, drawPoints, drawGapPoints) {
799 var prevX = null;
800 var prevY = null;
801 var nextY = null;
802 var pointsOnLine = []; // Array of [canvasx, canvasy] pairs.
803 ctx.beginPath();
804 ctx.strokeStyle = color;
805 ctx.lineWidth = strokeWidth;
806 for (var j = firstIndexInSet; j < firstIndexInSet + setLength; ++j) {
807 var point = points[j];
808 nextY = (j + 1 < firstIndexInSet + setLength) ? points[j + 1].canvasy : null;
809 if (DygraphCanvasRenderer.isNullOrNaN_(point.canvasy)) {
810 prevX = prevY = null;
811 } else {
812 var isIsolated = (!prevX && DygraphCanvasRenderer.isNullOrNaN_(nextY));
813 if (drawGapPoints) {
814 // Also consider a point to be is "isolated" if it's adjacent to a
815 // null point, excluding the graph edges.
816 if ((j > firstIndexInSet && !prevX) ||
817 ((j + 1 < firstIndexInSet + setLength) && DygraphCanvasRenderer.isNullOrNaN_(nextY))) {
818 isIsolated = true;
819 }
820 }
821 if (prevX === null) {
822 prevX = point.canvasx;
823 prevY = point.canvasy;
824 if (j === firstIndexInSet) {
825 ctx.moveTo(point.canvasx, point.canvasy);
826 }
827 } else {
828 ctx.lineTo(point.canvasx, point.canvasy);
829 }
830 if (drawPoints || isIsolated) {
831 pointsOnLine.push([point.canvasx, point.canvasy]);
832 }
833 }
834 }
835 ctx.stroke();
836 for (var idx = 0; idx < pointsOnLine.length; idx++) {
837 var cb = pointsOnLine[idx];
838 ctx.save();
839 drawPointCallback(
840 this.dygraph_, setName, ctx, cb[0], cb[1], color, pointSize);
841 ctx.restore();
842 }
843};
844
845DygraphCanvasRenderer.prototype._drawLine = function(ctx, i) {
846 var setNames = this.layout.setNames;
847 var setName = setNames[i];
848
849 var strokeWidth = this.dygraph_.attr_("strokeWidth", setName);
850 var borderWidth = this.dygraph_.attr_("strokeBorderWidth", setName);
851 var drawPointCallback = this.dygraph_.attr_("drawPointCallback", setName) ||
852 Dygraph.Circles.DEFAULT;
853 if (borderWidth && strokeWidth) {
854 this._drawStyledLine(ctx, i, setName,
855 this.dygraph_.attr_("strokeBorderColor", setName),
856 strokeWidth + 2 * borderWidth,
857 this.dygraph_.attr_("strokePattern", setName),
858 this.dygraph_.attr_("drawPoints", setName),
859 drawPointCallback,
860 this.dygraph_.attr_("pointSize", setName));
861 }
862
863 this._drawStyledLine(ctx, i, setName,
864 this.colors[setName],
865 strokeWidth,
866 this.dygraph_.attr_("strokePattern", setName),
867 this.dygraph_.attr_("drawPoints", setName),
868 drawPointCallback,
869 this.dygraph_.attr_("pointSize", setName));
870};
871
872/**
873 * Actually draw the lines chart, including error bars.
874 * TODO(danvk): split this into several smaller functions.
875 * @private
876 */
877DygraphCanvasRenderer.prototype._renderLineChart = function() {
878 // TODO(danvk): use this.attr_ for many of these.
879 var ctx = this.elementContext;
880 var fillAlpha = this.attr_('fillAlpha');
881 var errorBars = this.attr_("errorBars") || this.attr_("customBars");
882 var fillGraph = this.attr_("fillGraph");
883 var stackedGraph = this.attr_("stackedGraph");
884 var stepPlot = this.attr_("stepPlot");
885 var points = this.layout.points;
886 var pointsLength = points.length;
887 var point, i, j, prevX, prevY, prevYs, color, setName, newYs, err_color, rgb, yscale, axis;
888
889 var setNames = this.layout.setNames;
890 var setCount = setNames.length;
891
892 // TODO(danvk): Move this mapping into Dygraph and get it out of here.
893 this.colors = {};
894 for (i = 0; i < setCount; i++) {
895 this.colors[setNames[i]] = this.colorScheme_[i % this.colorScheme_.length];
896 }
897
898 // Update Points
899 // TODO(danvk): here
900 //
901 // TODO(bhs): this loop is a hot-spot for high-point-count charts. These
902 // transformations can be pushed into the canvas via linear transformation
903 // matrices.
904 for (i = pointsLength; i--;) {
905 point = points[i];
906 point.canvasx = this.area.w * point.x + this.area.x;
907 point.canvasy = this.area.h * point.y + this.area.y;
908 }
909
910 // create paths
911 if (errorBars) {
912 ctx.save();
913 if (fillGraph) {
914 this.dygraph_.warn("Can't use fillGraph option with error bars");
915 }
916
917 for (i = 0; i < setCount; i++) {
918 setName = setNames[i];
919 axis = this.dygraph_.axisPropertiesForSeries(setName);
920 color = this.colors[setName];
921
922 var firstIndexInSet = this.layout.setPointsOffsets[i];
923 var setLength = this.layout.setPointsLengths[i];
924 var afterLastIndexInSet = firstIndexInSet + setLength;
925
926 var next = DygraphCanvasRenderer.makeNextPointStep_(
927 this.attr_('connectSeparatedPoints'), points,
928 afterLastIndexInSet);
929
930 // setup graphics context
931 prevX = NaN;
932 prevY = NaN;
933 prevYs = [-1, -1];
934 yscale = axis.yscale;
935 // should be same color as the lines but only 15% opaque.
936 rgb = new RGBColor(color);
937 err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
938 fillAlpha + ')';
939 ctx.fillStyle = err_color;
940 ctx.beginPath();
941 for (j = firstIndexInSet; j < afterLastIndexInSet; j = next(j)) {
942 point = points[j];
943 if (point.name == setName) { // TODO(klausw): this is always true
944 if (!Dygraph.isOK(point.y)) {
945 prevX = NaN;
946 continue;
947 }
948
949 // TODO(danvk): here
950 if (stepPlot) {
951 newYs = [ point.y_bottom, point.y_top ];
952 prevY = point.y;
953 } else {
954 newYs = [ point.y_bottom, point.y_top ];
955 }
956 newYs[0] = this.area.h * newYs[0] + this.area.y;
957 newYs[1] = this.area.h * newYs[1] + this.area.y;
958 if (!isNaN(prevX)) {
959 if (stepPlot) {
960 ctx.moveTo(prevX, newYs[0]);
961 } else {
962 ctx.moveTo(prevX, prevYs[0]);
963 }
964 ctx.lineTo(point.canvasx, newYs[0]);
965 ctx.lineTo(point.canvasx, newYs[1]);
966 if (stepPlot) {
967 ctx.lineTo(prevX, newYs[1]);
968 } else {
969 ctx.lineTo(prevX, prevYs[1]);
970 }
971 ctx.closePath();
972 }
973 prevYs = newYs;
974 prevX = point.canvasx;
975 }
976 }
977 ctx.fill();
978 }
979 ctx.restore();
980 } else if (fillGraph) {
981 ctx.save();
982 var baseline = {}; // for stacked graphs: baseline for filling
983 var currBaseline;
984
985 // process sets in reverse order (needed for stacked graphs)
986 for (i = setCount - 1; i >= 0; i--) {
987 setName = setNames[i];
988 color = this.colors[setName];
989 axis = this.dygraph_.axisPropertiesForSeries(setName);
990 var axisY = 1.0 + axis.minyval * axis.yscale;
991 if (axisY < 0.0) axisY = 0.0;
992 else if (axisY > 1.0) axisY = 1.0;
993 axisY = this.area.h * axisY + this.area.y;
994 var firstIndexInSet = this.layout.setPointsOffsets[i];
995 var setLength = this.layout.setPointsLengths[i];
996 var afterLastIndexInSet = firstIndexInSet + setLength;
997
998 var next = DygraphCanvasRenderer.makeNextPointStep_(
999 this.attr_('connectSeparatedPoints'), points,
1000 afterLastIndexInSet);
1001
1002 // setup graphics context
1003 prevX = NaN;
1004 prevYs = [-1, -1];
1005 yscale = axis.yscale;
1006 // should be same color as the lines but only 15% opaque.
1007 rgb = new RGBColor(color);
1008 err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
1009 fillAlpha + ')';
1010 ctx.fillStyle = err_color;
1011 ctx.beginPath();
1012 for (j = firstIndexInSet; j < afterLastIndexInSet; j = next(j)) {
1013 point = points[j];
1014 if (point.name == setName) { // TODO(klausw): this is always true
1015 if (!Dygraph.isOK(point.y)) {
1016 prevX = NaN;
1017 continue;
1018 }
1019 if (stackedGraph) {
1020 currBaseline = baseline[point.canvasx];
1021 var lastY;
1022 if (currBaseline === undefined) {
1023 lastY = axisY;
1024 } else {
1025 if(stepPlot) {
1026 lastY = currBaseline[0];
1027 } else {
1028 lastY = currBaseline;
1029 }
1030 }
1031 newYs = [ point.canvasy, lastY ];
1032
1033 if(stepPlot) {
1034 // Step plots must keep track of the top and bottom of
1035 // the baseline at each point.
1036 if(prevYs[0] === -1) {
1037 baseline[point.canvasx] = [ point.canvasy, axisY ];
1038 } else {
1039 baseline[point.canvasx] = [ point.canvasy, prevYs[0] ];
1040 }
1041 } else {
1042 baseline[point.canvasx] = point.canvasy;
1043 }
1044
1045 } else {
1046 newYs = [ point.canvasy, axisY ];
1047 }
1048 if (!isNaN(prevX)) {
1049 ctx.moveTo(prevX, prevYs[0]);
1050
1051 if (stepPlot) {
1052 ctx.lineTo(point.canvasx, prevYs[0]);
1053 if(currBaseline) {
1054 // Draw to the bottom of the baseline
1055 ctx.lineTo(point.canvasx, currBaseline[1]);
1056 } else {
1057 ctx.lineTo(point.canvasx, newYs[1]);
1058 }
1059 } else {
1060 ctx.lineTo(point.canvasx, newYs[0]);
1061 ctx.lineTo(point.canvasx, newYs[1]);
1062 }
1063
1064 ctx.lineTo(prevX, prevYs[1]);
1065 ctx.closePath();
1066 }
1067 prevYs = newYs;
1068 prevX = point.canvasx;
1069 }
1070 }
1071 ctx.fill();
1072 }
1073 ctx.restore();
1074 }
1075
1076 // Drawing the lines.
1077 for (i = 0; i < setCount; i += 1) {
1078 this._drawLine(ctx, i);
1079 }
1080};
1081
1082/**
1083 * This does dashed lines onto a canvas for a given pattern. You must call
1084 * ctx.stroke() after to actually draw it, much line ctx.lineTo(). It remembers
1085 * the state of the line in regards to where we left off on drawing the pattern.
1086 * You can draw a dashed line in several function calls and the pattern will be
1087 * continous as long as you didn't call this function with a different pattern
1088 * in between.
1089 * @param ctx The canvas 2d context to draw on.
1090 * @param x The start of the line's x coordinate.
1091 * @param y The start of the line's y coordinate.
1092 * @param x2 The end of the line's x coordinate.
1093 * @param y2 The end of the line's y coordinate.
1094 * @param pattern The dash pattern to draw, an array of integers where even
1095 * index is drawn and odd index is not drawn (Ex. [10, 2, 5, 2], 10 is drawn 5
1096 * is drawn, 2 is the space between.). A null pattern, array of length one, or
1097 * empty array will do just a solid line.
1098 * @private
1099 */
1100DygraphCanvasRenderer.prototype._dashedLine = function(ctx, x, y, x2, y2, pattern) {
1101 // Original version http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
1102 // Modified by Russell Valentine to keep line history and continue the pattern
1103 // where it left off.
1104 var dx, dy, len, rot, patternIndex, segment;
1105
1106 // If we don't have a pattern or it is an empty array or of size one just
1107 // do a solid line.
1108 if (!pattern || pattern.length <= 1) {
1109 ctx.moveTo(x, y);
1110 ctx.lineTo(x2, y2);
1111 return;
1112 }
1113
1114 // If we have a different dash pattern than the last time this was called we
1115 // reset our dash history and start the pattern from the begging
1116 // regardless of state of the last pattern.
1117 if (!Dygraph.compareArrays(pattern, this._dashedLineToHistoryPattern)) {
1118 this._dashedLineToHistoryPattern = pattern;
1119 this._dashedLineToHistory = [0, 0];
1120 }
1121 ctx.save();
1122
1123 // Calculate transformation parameters
1124 dx = (x2-x);
1125 dy = (y2-y);
1126 len = Math.sqrt(dx*dx + dy*dy);
1127 rot = Math.atan2(dy, dx);
1128
1129 // Set transformation
1130 ctx.translate(x, y);
1131 ctx.moveTo(0, 0);
1132 ctx.rotate(rot);
1133
1134 // Set last pattern index we used for this pattern.
1135 patternIndex = this._dashedLineToHistory[0];
1136 x = 0;
1137 while (len > x) {
1138 // Get the length of the pattern segment we are dealing with.
1139 segment = pattern[patternIndex];
1140 // If our last draw didn't complete the pattern segment all the way we
1141 // will try to finish it. Otherwise we will try to do the whole segment.
1142 if (this._dashedLineToHistory[1]) {
1143 x += this._dashedLineToHistory[1];
1144 } else {
1145 x += segment;
1146 }
1147 if (x > len) {
1148 // We were unable to complete this pattern index all the way, keep
1149 // where we are the history so our next draw continues where we left off
1150 // in the pattern.
1151 this._dashedLineToHistory = [patternIndex, x-len];
1152 x = len;
1153 } else {
1154 // We completed this patternIndex, we put in the history that we are on
1155 // the beginning of the next segment.
1156 this._dashedLineToHistory = [(patternIndex+1)%pattern.length, 0];
1157 }
1158
1159 // We do a line on a even pattern index and just move on a odd pattern index.
1160 // The move is the empty space in the dash.
1161 if(patternIndex % 2 === 0) {
1162 ctx.lineTo(x, 0);
1163 } else {
1164 ctx.moveTo(x, 0);
1165 }
1166 // If we are not done, next loop process the next pattern segment, or the
1167 // first segment again if we are at the end of the pattern.
1168 patternIndex = (patternIndex+1) % pattern.length;
1169 }
1170 ctx.restore();
1171};