Update plugin registry
[dygraphs.git] / dygraph-canvas.js
CommitLineData
88e95c46
DV
1/**
2 * @license
3 * Copyright 2006 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
5 */
6a1aa64f
DV
6
7/**
74a5af31
DV
8 * @fileoverview Based on PlotKit.CanvasRenderer, but modified to meet the
9 * needs of dygraphs.
10 *
3df0ccf0 11 * In particular, support for:
0abfbd7e 12 * - grid overlays
3df0ccf0
DV
13 * - error bars
14 * - dygraphs attribute system
6a1aa64f
DV
15 */
16
6a1aa64f 17/**
423f5ed3
DV
18 * The DygraphCanvasRenderer class does the actual rendering of the chart onto
19 * a canvas. It's based on PlotKit.CanvasRenderer.
6a1aa64f 20 * @param {Object} element The canvas to attach to
2cf95fff
RK
21 * @param {Object} elementContext The 2d context of the canvas (injected so it
22 * can be mocked for testing.)
285a6bda 23 * @param {Layout} layout The DygraphLayout object for this graph.
74a5af31 24 * @constructor
6a1aa64f 25 */
c0f54d4f 26
758a629f
DV
27/*jshint globalstrict: true */
28/*global Dygraph:false,RGBColor:false */
c0f54d4f
DV
29"use strict";
30
79253bd0 31
c0f54d4f 32var DygraphCanvasRenderer = function(dygraph, element, elementContext, layout) {
9317362d 33 this.dygraph_ = dygraph;
fbe31dc8 34
fbe31dc8 35 this.layout = layout;
b0c3b730 36 this.element = element;
2cf95fff 37 this.elementContext = elementContext;
fbe31dc8
DV
38 this.container = this.element.parentNode;
39
fbe31dc8
DV
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
758a629f
DV
48 this.xlabels = [];
49 this.ylabels = [];
50 this.annotations = [];
ad1798c2 51 this.chartLabels = {};
fbe31dc8 52
70be5ed1 53 this.area = layout.getPlotArea();
423f5ed3
DV
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.
920208fb
PF
59 if (this.dygraph_.isUsingExcanvas_) {
60 this._createIEClipArea();
61 } else {
971870e5
DV
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();
920208fb 69
971870e5
DV
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 }
920208fb 75 }
423f5ed3
DV
76};
77
78DygraphCanvasRenderer.prototype.attr_ = function(x) {
79 return this.dygraph_.attr_(x);
80};
81
fbe31dc8 82DygraphCanvasRenderer.prototype.clear = function() {
758a629f 83 var context;
fbe31dc8
DV
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 }
758a629f 91 context = this.elementContext;
fbe31dc8
DV
92 }
93 catch (e) {
76171648 94 // TODO(danvk): this is broken, since MochiKit.Async is gone.
758a629f
DV
95 // this.clearDelay = MochiKit.Async.wait(this.IEDelay);
96 // this.clearDelay.addCallback(bind(this.clear, this));
fbe31dc8
DV
97 return;
98 }
99 }
100
758a629f 101 context = this.elementContext;
fbe31dc8
DV
102 context.clearRect(0, 0, this.width, this.height);
103
758a629f
DV
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 }
ce49c2fa 109 }
758a629f
DV
110
111 removeArray(this.xlabels);
112 removeArray(this.ylabels);
113 removeArray(this.annotations);
114
ad1798c2
DV
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 }
758a629f
DV
120 this.xlabels = [];
121 this.ylabels = [];
122 this.annotations = [];
ad1798c2 123 this.chartLabels = {};
fbe31dc8
DV
124};
125
126
127DygraphCanvasRenderer.isSupported = function(canvasName) {
128 var canvas = null;
129 try {
758a629f 130 if (typeof(canvasName) == 'undefined' || canvasName === null) {
b0c3b730 131 canvas = document.createElement("canvas");
758a629f 132 } else {
b0c3b730 133 canvas = canvasName;
758a629f
DV
134 }
135 canvas.getContext("2d");
fbe31dc8
DV
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;
6a1aa64f 145};
6a1aa64f
DV
146
147/**
600d841a
DV
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/**
6a1aa64f
DV
156 * Draw an X/Y grid on top of the existing plot
157 */
285a6bda 158DygraphCanvasRenderer.prototype.render = function() {
528ce7e5
DV
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.
2cf95fff 161 var ctx = this.elementContext;
758a629f
DV
162 function halfUp(x) { return Math.round(x) + 0.5; }
163 function halfDown(y){ return Math.round(y) - 0.5; }
e7746234 164
423f5ed3 165 if (this.attr_('underlayCallback')) {
1e41bd2d
DV
166 // NOTE: we pass the dygraph object to this callback twice to avoid breaking
167 // users who expect a deprecated form of this callback.
423f5ed3 168 this.attr_('underlayCallback')(ctx, this.area, this.dygraph_, this.dygraph_);
e7746234
EC
169 }
170
758a629f 171 var x, y, i, ticks;
423f5ed3 172 if (this.attr_('drawYGrid')) {
758a629f 173 ticks = this.layout.yticks;
bbba718a 174 // TODO(konigsberg): I don't think these calls to save() have a corresponding restore().
6a1aa64f 175 ctx.save();
423f5ed3 176 ctx.strokeStyle = this.attr_('gridLineColor');
990d6a35 177 ctx.lineWidth = this.attr_('gridLineWidth');
758a629f 178 for (i = 0; i < ticks.length; i++) {
880a574f 179 // TODO(danvk): allow secondary axes to draw a grid, too.
758a629f
DV
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);
6a1aa64f
DV
183 ctx.beginPath();
184 ctx.moveTo(x, y);
185 ctx.lineTo(x + this.area.w, y);
186 ctx.closePath();
187 ctx.stroke();
188 }
6bf4df7f 189 ctx.restore();
6a1aa64f
DV
190 }
191
423f5ed3 192 if (this.attr_('drawXGrid')) {
758a629f 193 ticks = this.layout.xticks;
6a1aa64f 194 ctx.save();
423f5ed3 195 ctx.strokeStyle = this.attr_('gridLineColor');
990d6a35 196 ctx.lineWidth = this.attr_('gridLineWidth');
758a629f
DV
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);
6a1aa64f 200 ctx.beginPath();
880a574f 201 ctx.moveTo(x, y);
6a1aa64f
DV
202 ctx.lineTo(x, this.area.y);
203 ctx.closePath();
204 ctx.stroke();
205 }
6bf4df7f 206 ctx.restore();
6a1aa64f 207 }
2ce09b19
DV
208
209 // Do the ordinary rendering, as before
2ce09b19 210 this._renderLineChart();
fbe31dc8 211 this._renderAxis();
ccd9d7c2 212 this._renderChartLabels();
ce49c2fa 213 this._renderAnnotations();
fbe31dc8
DV
214};
215
920208fb
PF
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) {
758a629f 240 if (area.w === 0 || area.h === 0) {
920208fb
PF
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
758a629f
DV
256 createClipDiv({
257 x:0, y:0,
258 w:plotArea.x,
259 h:this.height
260 });
261
920208fb 262 // Top
758a629f
DV
263 createClipDiv({
264 x: plotArea.x, y: 0,
265 w: this.width - plotArea.x,
266 h: plotArea.y
267 });
268
920208fb 269 // Right side
758a629f
DV
270 createClipDiv({
271 x: plotArea.x + plotArea.w, y: 0,
272 w: this.width-plotArea.x - plotArea.w,
273 h: this.height
274 });
275
920208fb 276 // Bottom
758a629f
DV
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};
fbe31dc8
DV
284
285DygraphCanvasRenderer.prototype._renderAxis = function() {
423f5ed3 286 if (!this.attr_('drawXAxis') && !this.attr_('drawYAxis')) return;
fbe31dc8 287
528ce7e5 288 // Round pixels to half-integer boundaries for crisper drawing.
758a629f
DV
289 function halfUp(x) { return Math.round(x) + 0.5; }
290 function halfDown(y){ return Math.round(y) - 0.5; }
528ce7e5 291
2cf95fff 292 var context = this.elementContext;
fbe31dc8 293
758a629f
DV
294 var label, x, y, tick, i;
295
34fedff8 296 var labelStyle = {
423f5ed3
DV
297 position: "absolute",
298 fontSize: this.attr_('axisLabelFontSize') + "px",
299 zIndex: 10,
300 color: this.attr_('axisLabelColor'),
301 width: this.attr_('axisLabelWidth') + "px",
74a5af31 302 // height: this.attr_('axisLabelFontSize') + 2 + "px",
758a629f 303 lineHeight: "normal", // Something other than "normal" line-height screws up label positioning.
423f5ed3 304 overflow: "hidden"
34fedff8 305 };
48e614ac 306 var makeDiv = function(txt, axis, prec_axis) {
34fedff8
DV
307 var div = document.createElement("div");
308 for (var name in labelStyle) {
85b99f0b
DV
309 if (labelStyle.hasOwnProperty(name)) {
310 div.style[name] = labelStyle[name];
311 }
fbe31dc8 312 }
ba451526 313 var inner_div = document.createElement("div");
48e614ac
DV
314 inner_div.className = 'dygraph-axis-label' +
315 ' dygraph-axis-label-' + axis +
316 (prec_axis ? ' dygraph-axis-label-' + prec_axis : '');
3bdf7140 317 inner_div.innerHTML=txt;
ba451526 318 div.appendChild(inner_div);
34fedff8 319 return div;
fbe31dc8
DV
320 };
321
322 // axis lines
323 context.save();
423f5ed3
DV
324 context.strokeStyle = this.attr_('axisLineColor');
325 context.lineWidth = this.attr_('axisLineWidth');
fbe31dc8 326
423f5ed3 327 if (this.attr_('drawYAxis')) {
8b7a0cc3 328 if (this.layout.yticks && this.layout.yticks.length > 0) {
48e614ac 329 var num_axes = this.dygraph_.numAxes();
758a629f
DV
330 for (i = 0; i < this.layout.yticks.length; i++) {
331 tick = this.layout.yticks[i];
fbe31dc8 332 if (typeof(tick) == "function") return;
758a629f 333 x = this.area.x;
880a574f 334 var sgn = 1;
48e614ac 335 var prec_axis = 'y1';
880a574f
DV
336 if (tick[0] == 1) { // right-side y-axis
337 x = this.area.x + this.area.w;
338 sgn = -1;
48e614ac 339 prec_axis = 'y2';
9012dd21 340 }
758a629f 341 y = this.area.y + tick[1] * this.area.h;
920208fb
PF
342
343 /* Tick marks are currently clipped, so don't bother drawing them.
fbe31dc8 344 context.beginPath();
528ce7e5 345 context.moveTo(halfUp(x), halfDown(y));
0e23cfc6 346 context.lineTo(halfUp(x - sgn * this.attr_('axisTickSize')), halfDown(y));
fbe31dc8
DV
347 context.closePath();
348 context.stroke();
920208fb 349 */
fbe31dc8 350
758a629f 351 label = makeDiv(tick[2], 'y', num_axes == 2 ? prec_axis : null);
423f5ed3 352 var top = (y - this.attr_('axisLabelFontSize') / 2);
fbe31dc8
DV
353 if (top < 0) top = 0;
354
423f5ed3 355 if (top + this.attr_('axisLabelFontSize') + 3 > this.height) {
fbe31dc8
DV
356 label.style.bottom = "0px";
357 } else {
358 label.style.top = top + "px";
359 }
758a629f 360 if (tick[0] === 0) {
423f5ed3 361 label.style.left = (this.area.x - this.attr_('yAxisLabelWidth') - this.attr_('axisTickSize')) + "px";
9012dd21
DV
362 label.style.textAlign = "right";
363 } else if (tick[0] == 1) {
364 label.style.left = (this.area.x + this.area.w +
423f5ed3 365 this.attr_('axisTickSize')) + "px";
9012dd21
DV
366 label.style.textAlign = "left";
367 }
423f5ed3 368 label.style.width = this.attr_('yAxisLabelWidth') + "px";
b0c3b730 369 this.container.appendChild(label);
fbe31dc8 370 this.ylabels.push(label);
2160ed4a 371 }
fbe31dc8
DV
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];
423f5ed3 377 var fontSize = this.attr_('axisLabelFontSize');
758a629f 378 var bottom = parseInt(bottomTick.style.top, 10) + fontSize;
fbe31dc8 379 if (bottom > this.height - fontSize) {
758a629f 380 bottomTick.style.top = (parseInt(bottomTick.style.top, 10) -
fbe31dc8
DV
381 fontSize / 2) + "px";
382 }
383 }
384
528ce7e5 385 // draw a vertical line on the left to separate the chart from the labels.
fbe31dc8 386 context.beginPath();
528ce7e5
DV
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));
fbe31dc8
DV
389 context.closePath();
390 context.stroke();
c1dbeb10 391
528ce7e5 392 // if there's a secondary y-axis, draw a vertical line for that, too.
c1dbeb10
DV
393 if (this.dygraph_.numAxes() == 2) {
394 context.beginPath();
528ce7e5
DV
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));
c1dbeb10
DV
397 context.closePath();
398 context.stroke();
399 }
fbe31dc8
DV
400 }
401
423f5ed3 402 if (this.attr_('drawXAxis')) {
fbe31dc8 403 if (this.layout.xticks) {
758a629f
DV
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;
920208fb
PF
408
409 /* Tick marks are currently clipped, so don't bother drawing them.
fbe31dc8 410 context.beginPath();
528ce7e5 411 context.moveTo(halfUp(x), halfDown(y));
423f5ed3 412 context.lineTo(halfUp(x), halfDown(y + this.attr_('axisTickSize')));
fbe31dc8
DV
413 context.closePath();
414 context.stroke();
920208fb 415 */
fbe31dc8 416
758a629f 417 label = makeDiv(tick[1], 'x');
fbe31dc8 418 label.style.textAlign = "center";
423f5ed3 419 label.style.top = (y + this.attr_('axisTickSize')) + 'px';
fbe31dc8 420
423f5ed3
DV
421 var left = (x - this.attr_('axisLabelWidth')/2);
422 if (left + this.attr_('axisLabelWidth') > this.width) {
423 left = this.width - this.attr_('xAxisLabelWidth');
fbe31dc8
DV
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";
423f5ed3 432 label.style.width = this.attr_('xAxisLabelWidth') + "px";
b0c3b730 433 this.container.appendChild(label);
fbe31dc8 434 this.xlabels.push(label);
2160ed4a 435 }
fbe31dc8
DV
436 }
437
438 context.beginPath();
528ce7e5
DV
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));
fbe31dc8
DV
441 context.closePath();
442 context.stroke();
443 }
444
445 context.restore();
6a1aa64f
DV
446};
447
fbe31dc8 448
ad1798c2 449DygraphCanvasRenderer.prototype._renderChartLabels = function() {
758a629f
DV
450 var div, class_div;
451
ad1798c2
DV
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')) {
758a629f 456 div = document.createElement("div");
ad1798c2
DV
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';
b4202b3d 463 div.style.fontSize = (this.attr_('titleHeight') - 8) + 'px';
ad1798c2 464 div.style.fontWeight = 'bold';
758a629f 465 class_div = document.createElement("div");
ca49434a
DV
466 class_div.className = 'dygraph-label dygraph-title';
467 class_div.innerHTML = this.attr_('title');
468 div.appendChild(class_div);
ad1798c2
DV
469 this.container.appendChild(div);
470 this.chartLabels.title = div;
471 }
472
473 if (this.attr_('xlabel')) {
758a629f 474 div = document.createElement("div");
ad1798c2
DV
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';
86cce9e8 481 div.style.fontSize = (this.attr_('xLabelHeight') - 2) + 'px';
ca49434a 482
758a629f 483 class_div = document.createElement("div");
ca49434a
DV
484 class_div.className = 'dygraph-label dygraph-xlabel';
485 class_div.innerHTML = this.attr_('xlabel');
486 div.appendChild(class_div);
ad1798c2
DV
487 this.container.appendChild(div);
488 this.chartLabels.xlabel = div;
489 }
490
d0c39108
DV
491 var that = this;
492 function createRotatedDiv(axis, classes, html) {
ad1798c2
DV
493 var box = {
494 left: 0,
d0c39108
DV
495 top: that.area.y,
496 width: that.attr_('yLabelWidth'),
497 height: that.area.h
ad1798c2 498 };
ca49434a 499 // TODO(danvk): is this outer div actually necessary?
758a629f 500 div = document.createElement("div");
ad1798c2 501 div.style.position = 'absolute';
d0c39108
DV
502 if (axis == 1) {
503 div.style.left = box.left;
504 } else {
505 div.style.right = box.left;
506 }
ad1798c2
DV
507 div.style.top = box.top + 'px';
508 div.style.width = box.width + 'px';
509 div.style.height = box.height + 'px';
d0c39108 510 div.style.fontSize = (that.attr_('yLabelWidth') - 2) + 'px';
ad1798c2
DV
511
512 var inner_div = document.createElement("div");
513 inner_div.style.position = 'absolute';
ad1798c2
DV
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';
b56b6993
DV
519
520 // CSS rotation is an HTML5 feature which is not standardized. Hence every
521 // browser has its own name for the CSS style.
d0c39108
DV
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
b56b6993
DV
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 =
d0c39108
DV
535 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' +
536 (axis == 1 ? '3' : '1') + ')';
b56b6993
DV
537 inner_div.style.left = '0px';
538 inner_div.style.top = '0px';
539 }
ad1798c2 540
758a629f 541 class_div = document.createElement("div");
d0c39108
DV
542 class_div.className = classes;
543 class_div.innerHTML = html;
ca49434a
DV
544
545 inner_div.appendChild(class_div);
ad1798c2 546 div.appendChild(inner_div);
d0c39108
DV
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'));
ad1798c2
DV
554 this.container.appendChild(div);
555 this.chartLabels.ylabel = div;
556 }
107f9d8e 557 if (this.attr_('y2label') && this.dygraph_.numAxes() == 2) {
d0c39108
DV
558 div = createRotatedDiv(2, 'dygraph-label dygraph-y2label',
559 this.attr_('y2label'));
560 this.container.appendChild(div);
561 this.chartLabels.y2label = div;
562 }
ad1798c2
DV
563};
564
565
ce49c2fa
DV
566DygraphCanvasRenderer.prototype._renderAnnotations = function() {
567 var annotationStyle = {
568 "position": "absolute",
423f5ed3 569 "fontSize": this.attr_('axisLabelFontSize') + "px",
ce49c2fa 570 "zIndex": 10,
3bf2fa91 571 "overflow": "hidden"
ce49c2fa
DV
572 };
573
ab5e5c75
DV
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 };
758a629f 583 };
ab5e5c75 584
ce49c2fa
DV
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];
4c919f55
DV
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) {
e6d53148
DV
591 continue;
592 }
593
ce5e8d36
DV
594 var a = p.annotation;
595 var tick_height = 6;
596 if (a.hasOwnProperty("tickHeight")) {
597 tick_height = a.tickHeight;
9a40897e
DV
598 }
599
ce49c2fa
DV
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 }
ce5e8d36
DV
606 if (!a.hasOwnProperty('icon')) {
607 div.className = "dygraphDefaultAnnotation";
608 }
609 if (a.hasOwnProperty('cssClass')) {
610 div.className += " " + a.cssClass;
611 }
612
a5ad69cc
DV
613 var width = a.hasOwnProperty('width') ? a.width : 16;
614 var height = a.hasOwnProperty('height') ? a.height : 16;
ce5e8d36
DV
615 if (a.hasOwnProperty('icon')) {
616 var img = document.createElement("img");
617 img.src = a.icon;
33030f33
DV
618 img.width = width;
619 img.height = height;
ce5e8d36
DV
620 div.appendChild(img);
621 } else if (p.annotation.hasOwnProperty('shortText')) {
622 div.appendChild(document.createTextNode(p.annotation.shortText));
5c528fa2 623 }
ce5e8d36 624 div.style.left = (p.canvasx - width / 2) + "px";
d14b9eed
DV
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 }
ce5e8d36
DV
630 div.style.width = width + "px";
631 div.style.height = height + "px";
ce49c2fa
DV
632 div.title = p.annotation.text;
633 div.style.color = this.colors[p.name];
634 div.style.borderColor = this.colors[p.name];
e6d53148 635 a.div = div;
ab5e5c75 636
9a40897e
DV
637 Dygraph.addEvent(div, 'click',
638 bindEvt('clickHandler', 'annotationClickHandler', p, this));
639 Dygraph.addEvent(div, 'mouseover',
640 bindEvt('mouseOverHandler', 'annotationMouseOverHandler', p, this));
641 Dygraph.addEvent(div, 'mouseout',
642 bindEvt('mouseOutHandler', 'annotationMouseOutHandler', p, this));
643 Dygraph.addEvent(div, 'dblclick',
644 bindEvt('dblClickHandler', 'annotationDblClickHandler', p, this));
ab5e5c75 645
ce49c2fa
DV
646 this.container.appendChild(div);
647 this.annotations.push(div);
9a40897e 648
2cf95fff 649 var ctx = this.elementContext;
9a40897e
DV
650 ctx.strokeStyle = this.colors[p.name];
651 ctx.beginPath();
d14b9eed
DV
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 }
9a40897e
DV
659 ctx.closePath();
660 ctx.stroke();
ce49c2fa
DV
661 }
662};
663
04c104d7
KW
664DygraphCanvasRenderer.makeNextPointStep_ = function(connect, points, end) {
665 if (connect) {
666 return function(j) {
667 while (++j < end) {
668 if (!(points[j].yval === null)) break;
669 }
670 return j;
671 }
672 } else {
673 return function(j) { return j + 1 };
674 }
675};
676
857a6931 677DygraphCanvasRenderer.prototype._drawStyledLine = function(
5469113b
KW
678 ctx, i, setName, color, strokeWidth, strokePattern, drawPoints,
679 drawPointCallback, pointSize) {
857a6931
KW
680 var isNullOrNaN = function(x) {
681 return (x === null || isNaN(x));
682 };
683
684 var stepPlot = this.attr_("stepPlot");
685 var firstIndexInSet = this.layout.setPointsOffsets[i];
686 var setLength = this.layout.setPointsLengths[i];
687 var afterLastIndexInSet = firstIndexInSet + setLength;
688 var points = this.layout.points;
689 var prevX = null;
690 var prevY = null;
5469113b 691 var pointsOnLine = []; // Array of [canvasx, canvasy] pairs.
857a6931
KW
692 if (!Dygraph.isArrayLike(strokePattern)) {
693 strokePattern = null;
694 }
695
696 var point;
04c104d7
KW
697 var next = DygraphCanvasRenderer.makeNextPointStep_(
698 this.attr_('connectSeparatedPoints'), points, afterLastIndexInSet);
857a6931 699 ctx.save();
04c104d7 700 for (var j = firstIndexInSet; j < afterLastIndexInSet; j = next(j)) {
857a6931
KW
701 point = points[j];
702 if (isNullOrNaN(point.canvasy)) {
703 if (stepPlot && prevX !== null) {
704 // Draw a horizontal line to the start of the missing data
705 ctx.beginPath();
706 ctx.strokeStyle = color;
707 ctx.lineWidth = this.attr_('strokeWidth');
708 this._dashedLine(ctx, prevX, prevY, point.canvasx, prevY, strokePattern);
709 ctx.stroke();
710 }
711 // this will make us move to the next point, not draw a line to it.
712 prevX = prevY = null;
713 } else {
714 // A point is "isolated" if it is non-null but both the previous
715 // and next points are null.
716 var isIsolated = (!prevX && (j == points.length - 1 ||
717 isNullOrNaN(points[j+1].canvasy)));
718 if (prevX === null) {
719 prevX = point.canvasx;
720 prevY = point.canvasy;
721 } else {
722 // Skip over points that will be drawn in the same pixel.
723 if (Math.round(prevX) == Math.round(point.canvasx) &&
724 Math.round(prevY) == Math.round(point.canvasy)) {
725 continue;
726 }
727 // TODO(antrob): skip over points that lie on a line that is already
728 // going to be drawn. There is no need to have more than 2
729 // consecutive points that are collinear.
730 if (strokeWidth) {
731 ctx.beginPath();
732 ctx.strokeStyle = color;
733 ctx.lineWidth = strokeWidth;
734 if (stepPlot) {
735 this._dashedLine(ctx, prevX, prevY, point.canvasx, prevY, strokePattern);
736 prevX = point.canvasx;
737 }
738 this._dashedLine(ctx, prevX, prevY, point.canvasx, point.canvasy, strokePattern);
739 prevX = point.canvasx;
740 prevY = point.canvasy;
741 ctx.stroke();
742 }
743 }
744
745 if (drawPoints || isIsolated) {
5469113b 746 pointsOnLine.push([point.canvasx, point.canvasy]);
857a6931
KW
747 }
748 }
749 }
5469113b
KW
750 for (var idx = 0; idx < pointsOnLine.length; idx++) {
751 var cb = pointsOnLine[idx];
752 ctx.save();
753 drawPointCallback(
754 this.dygraph_, setName, ctx, cb[0], cb[1], color, pointSize);
755 ctx.restore();
756 }
857a6931
KW
757 ctx.restore();
758};
759
760DygraphCanvasRenderer.prototype._drawLine = function(ctx, i) {
761 var setNames = this.layout.setNames;
762 var setName = setNames[i];
763
764 var strokeWidth = this.dygraph_.attr_("strokeWidth", setName);
765 var borderWidth = this.dygraph_.attr_("strokeBorderWidth", setName);
5469113b
KW
766 var drawPointCallback = this.dygraph_.attr_("drawPointCallback", setName) ||
767 Dygraph.Circles.DEFAULT;
857a6931 768 if (borderWidth && strokeWidth) {
5469113b 769 this._drawStyledLine(ctx, i, setName,
857a6931
KW
770 this.dygraph_.attr_("strokeBorderColor", setName),
771 strokeWidth + 2 * borderWidth,
772 this.dygraph_.attr_("strokePattern", setName),
773 this.dygraph_.attr_("drawPoints", setName),
5469113b 774 drawPointCallback,
857a6931
KW
775 this.dygraph_.attr_("pointSize", setName));
776 }
777
5469113b 778 this._drawStyledLine(ctx, i, setName,
857a6931
KW
779 this.colors[setName],
780 strokeWidth,
781 this.dygraph_.attr_("strokePattern", setName),
782 this.dygraph_.attr_("drawPoints", setName),
5469113b 783 drawPointCallback,
857a6931
KW
784 this.dygraph_.attr_("pointSize", setName));
785};
ce49c2fa 786
6a1aa64f 787/**
758a629f
DV
788 * Actually draw the lines chart, including error bars.
789 * TODO(danvk): split this into several smaller functions.
790 * @private
6a1aa64f 791 */
285a6bda 792DygraphCanvasRenderer.prototype._renderLineChart = function() {
44c6bc29 793 // TODO(danvk): use this.attr_ for many of these.
857a6931 794 var ctx = this.elementContext;
423f5ed3 795 var fillAlpha = this.attr_('fillAlpha');
e4182459 796 var errorBars = this.attr_("errorBars") || this.attr_("customBars");
44c6bc29 797 var fillGraph = this.attr_("fillGraph");
b2c9222a
DV
798 var stackedGraph = this.attr_("stackedGraph");
799 var stepPlot = this.attr_("stepPlot");
c3e1495b
AR
800 var points = this.layout.points;
801 var pointsLength = points.length;
758a629f 802 var point, i, j, prevX, prevY, prevYs, color, setName, newYs, err_color, rgb, yscale, axis;
21d3323f 803
82c6fe4d 804 var setNames = this.layout.setNames;
21d3323f 805 var setCount = setNames.length;
6a1aa64f 806
0e23cfc6 807 // TODO(danvk): Move this mapping into Dygraph and get it out of here.
758a629f
DV
808 this.colors = {};
809 for (i = 0; i < setCount; i++) {
600d841a 810 this.colors[setNames[i]] = this.colorScheme_[i % this.colorScheme_.length];
f032c51d
AV
811 }
812
ff00d3e2
DV
813 // Update Points
814 // TODO(danvk): here
758a629f
DV
815 for (i = pointsLength; i--;) {
816 point = points[i];
6a1aa64f
DV
817 point.canvasx = this.area.w * point.x + this.area.x;
818 point.canvasy = this.area.h * point.y + this.area.y;
819 }
6a1aa64f
DV
820
821 // create paths
80aaae18 822 if (errorBars) {
857a6931 823 ctx.save();
6a834bbb
DV
824 if (fillGraph) {
825 this.dygraph_.warn("Can't use fillGraph option with error bars");
826 }
827
758a629f
DV
828 for (i = 0; i < setCount; i++) {
829 setName = setNames[i];
830 axis = this.dygraph_.axisPropertiesForSeries(setName);
831 color = this.colors[setName];
6a1aa64f 832
04c104d7
KW
833 var firstIndexInSet = this.layout.setPointsOffsets[i];
834 var setLength = this.layout.setPointsLengths[i];
835 var afterLastIndexInSet = firstIndexInSet + setLength;
836
837 var next = DygraphCanvasRenderer.makeNextPointStep_(
838 this.attr_('connectSeparatedPoints'), points,
839 afterLastIndexInSet);
840
6a1aa64f 841 // setup graphics context
758a629f
DV
842 prevX = NaN;
843 prevY = NaN;
844 prevYs = [-1, -1];
845 yscale = axis.yscale;
f474c2a3 846 // should be same color as the lines but only 15% opaque.
758a629f
DV
847 rgb = new RGBColor(color);
848 err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
43af96e7 849 fillAlpha + ')';
f474c2a3 850 ctx.fillStyle = err_color;
05c9d0c4 851 ctx.beginPath();
04c104d7 852 for (j = firstIndexInSet; j < afterLastIndexInSet; j = next(j)) {
758a629f 853 point = points[j];
04c104d7 854 if (point.name == setName) { // TODO(klausw): this is always true
e9fe4a2f 855 if (!Dygraph.isOK(point.y)) {
56623f3b 856 prevX = NaN;
ae85914a 857 continue;
5011e7a1 858 }
ce49c2fa 859
3637724f 860 // TODO(danvk): here
afdc483f 861 if (stepPlot) {
758a629f 862 newYs = [ point.y_bottom, point.y_top ];
afdc483f
NN
863 prevY = point.y;
864 } else {
758a629f 865 newYs = [ point.y_bottom, point.y_top ];
afdc483f 866 }
6a1aa64f
DV
867 newYs[0] = this.area.h * newYs[0] + this.area.y;
868 newYs[1] = this.area.h * newYs[1] + this.area.y;
56623f3b 869 if (!isNaN(prevX)) {
afdc483f 870 if (stepPlot) {
47600757 871 ctx.moveTo(prevX, newYs[0]);
afdc483f 872 } else {
47600757 873 ctx.moveTo(prevX, prevYs[0]);
afdc483f 874 }
5954ef32
DV
875 ctx.lineTo(point.canvasx, newYs[0]);
876 ctx.lineTo(point.canvasx, newYs[1]);
afdc483f 877 if (stepPlot) {
47600757 878 ctx.lineTo(prevX, newYs[1]);
afdc483f 879 } else {
47600757 880 ctx.lineTo(prevX, prevYs[1]);
afdc483f 881 }
5954ef32
DV
882 ctx.closePath();
883 }
354e15ab 884 prevYs = newYs;
5954ef32
DV
885 prevX = point.canvasx;
886 }
887 }
888 ctx.fill();
889 }
857a6931 890 ctx.restore();
5954ef32 891 } else if (fillGraph) {
857a6931 892 ctx.save();
758a629f 893 var baseline = []; // for stacked graphs: baseline for filling
354e15ab
DE
894
895 // process sets in reverse order (needed for stacked graphs)
758a629f
DV
896 for (i = setCount - 1; i >= 0; i--) {
897 setName = setNames[i];
898 color = this.colors[setName];
899 axis = this.dygraph_.axisPropertiesForSeries(setName);
ea4942ed
DV
900 var axisY = 1.0 + axis.minyval * axis.yscale;
901 if (axisY < 0.0) axisY = 0.0;
902 else if (axisY > 1.0) axisY = 1.0;
903 axisY = this.area.h * axisY + this.area.y;
04c104d7
KW
904 var firstIndexInSet = this.layout.setPointsOffsets[i];
905 var setLength = this.layout.setPointsLengths[i];
906 var afterLastIndexInSet = firstIndexInSet + setLength;
907
908 var next = DygraphCanvasRenderer.makeNextPointStep_(
909 this.attr_('connectSeparatedPoints'), points,
910 afterLastIndexInSet);
5954ef32
DV
911
912 // setup graphics context
758a629f
DV
913 prevX = NaN;
914 prevYs = [-1, -1];
915 yscale = axis.yscale;
5954ef32 916 // should be same color as the lines but only 15% opaque.
758a629f
DV
917 rgb = new RGBColor(color);
918 err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
43af96e7 919 fillAlpha + ')';
5954ef32
DV
920 ctx.fillStyle = err_color;
921 ctx.beginPath();
04c104d7 922 for (j = firstIndexInSet; j < afterLastIndexInSet; j = next(j)) {
758a629f 923 point = points[j];
04c104d7 924 if (point.name == setName) { // TODO(klausw): this is always true
e9fe4a2f 925 if (!Dygraph.isOK(point.y)) {
56623f3b 926 prevX = NaN;
5954ef32
DV
927 continue;
928 }
354e15ab 929 if (stackedGraph) {
47927039 930 var lastY = baseline[point.canvasx];
354e15ab
DE
931 if (lastY === undefined) lastY = axisY;
932 baseline[point.canvasx] = point.canvasy;
933 newYs = [ point.canvasy, lastY ];
934 } else {
935 newYs = [ point.canvasy, axisY ];
936 }
56623f3b 937 if (!isNaN(prevX)) {
05c9d0c4 938 ctx.moveTo(prevX, prevYs[0]);
afdc483f 939 if (stepPlot) {
47600757 940 ctx.lineTo(point.canvasx, prevYs[0]);
afdc483f 941 } else {
47600757 942 ctx.lineTo(point.canvasx, newYs[0]);
afdc483f 943 }
05c9d0c4
DV
944 ctx.lineTo(point.canvasx, newYs[1]);
945 ctx.lineTo(prevX, prevYs[1]);
946 ctx.closePath();
6a1aa64f 947 }
354e15ab 948 prevYs = newYs;
6a1aa64f
DV
949 prevX = point.canvasx;
950 }
05c9d0c4 951 }
6a1aa64f
DV
952 ctx.fill();
953 }
857a6931 954 ctx.restore();
80aaae18
DV
955 }
956
f9414b11 957 // Drawing the lines.
758a629f 958 for (i = 0; i < setCount; i += 1) {
857a6931 959 this._drawLine(ctx, i);
80aaae18 960 }
6a1aa64f 961};
79253bd0 962
963/**
964 * This does dashed lines onto a canvas for a given pattern. You must call
965 * ctx.stroke() after to actually draw it, much line ctx.lineTo(). It remembers
966 * the state of the line in regards to where we left off on drawing the pattern.
967 * You can draw a dashed line in several function calls and the pattern will be
968 * continous as long as you didn't call this function with a different pattern
969 * in between.
970 * @param ctx The canvas 2d context to draw on.
971 * @param x The start of the line's x coordinate.
972 * @param y The start of the line's y coordinate.
973 * @param x2 The end of the line's x coordinate.
974 * @param y2 The end of the line's y coordinate.
975 * @param pattern The dash pattern to draw, an array of integers where even
976 * index is drawn and odd index is not drawn (Ex. [10, 2, 5, 2], 10 is drawn 5
977 * is drawn, 2 is the space between.). A null pattern, array of length one, or
978 * empty array will do just a solid line.
979 * @private
980 */
981DygraphCanvasRenderer.prototype._dashedLine = function(ctx, x, y, x2, y2, pattern) {
982 // Original version http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
983 // Modified by Russell Valentine to keep line history and continue the pattern
984 // where it left off.
985 var dx, dy, len, rot, patternIndex, segment;
986
987 // If we don't have a pattern or it is an empty array or of size one just
988 // do a solid line.
989 if (!pattern || pattern.length <= 1) {
990 ctx.moveTo(x, y);
991 ctx.lineTo(x2, y2);
992 return;
993 }
994
995 // If we have a different dash pattern than the last time this was called we
996 // reset our dash history and start the pattern from the begging
997 // regardless of state of the last pattern.
998 if (!Dygraph.compareArrays(pattern, this._dashedLineToHistoryPattern)) {
999 this._dashedLineToHistoryPattern = pattern;
1000 this._dashedLineToHistory = [0, 0];
1001 }
1002 ctx.save();
1003
1004 // Calculate transformation parameters
1005 dx = (x2-x);
1006 dy = (y2-y);
1007 len = Math.sqrt(dx*dx + dy*dy);
1008 rot = Math.atan2(dy, dx);
1009
1010 // Set transformation
1011 ctx.translate(x, y);
1012 ctx.moveTo(0, 0);
1013 ctx.rotate(rot);
1014
1015 // Set last pattern index we used for this pattern.
1016 patternIndex = this._dashedLineToHistory[0];
1017 x = 0;
1018 while (len > x) {
1019 // Get the length of the pattern segment we are dealing with.
1020 segment = pattern[patternIndex];
1021 // If our last draw didn't complete the pattern segment all the way we
1022 // will try to finish it. Otherwise we will try to do the whole segment.
1023 if (this._dashedLineToHistory[1]) {
1024 x += this._dashedLineToHistory[1];
1025 } else {
1026 x += segment;
1027 }
1028 if (x > len) {
1029 // We were unable to complete this pattern index all the way, keep
1030 // where we are the history so our next draw continues where we left off
1031 // in the pattern.
1032 this._dashedLineToHistory = [patternIndex, x-len];
1033 x = len;
1034 } else {
1035 // We completed this patternIndex, we put in the history that we are on
1036 // the beginning of the next segment.
1037 this._dashedLineToHistory = [(patternIndex+1)%pattern.length, 0];
1038 }
1039
1040 // We do a line on a even pattern index and just move on a odd pattern index.
1041 // The move is the empty space in the dash.
1042 if(patternIndex % 2 === 0) {
1043 ctx.lineTo(x, 0);
1044 } else {
1045 ctx.moveTo(x, 0);
1046 }
1047 // If we are not done, next loop process the next pattern segment, or the
1048 // first segment again if we are at the end of the pattern.
1049 patternIndex = (patternIndex+1) % pattern.length;
1050 }
1051 ctx.restore();
1052};