Log scale panning. I'm feeling really good about just how damn well this lined up...
[dygraphs.git] / dygraph-canvas.js
CommitLineData
6a1aa64f
DV
1// Copyright 2006 Dan Vanderkam (danvdk@gmail.com)
2// All Rights Reserved.
3
4/**
3df0ccf0
DV
5 * @fileoverview Based on PlotKit, but modified to meet the needs of dygraphs.
6 * In particular, support for:
0abfbd7e 7 * - grid overlays
3df0ccf0
DV
8 * - error bars
9 * - dygraphs attribute system
6a1aa64f
DV
10 */
11
6a1aa64f 12/**
3df0ccf0 13 * Creates a new DygraphLayout object.
6a1aa64f 14 * @param {Object} options Options for PlotKit.Layout
285a6bda 15 * @return {Object} The DygraphLayout object
6a1aa64f 16 */
efe0829a
DV
17DygraphLayout = function(dygraph, options) {
18 this.dygraph_ = dygraph;
19 this.options = {}; // TODO(danvk): remove, use attr_ instead.
fc80a396 20 Dygraph.update(this.options, options ? options : {});
efe0829a 21 this.datasets = new Array();
937029df 22 this.annotations = new Array();
6a1aa64f 23};
efe0829a
DV
24
25DygraphLayout.prototype.attr_ = function(name) {
26 return this.dygraph_.attr_(name);
27};
28
29DygraphLayout.prototype.addDataset = function(setname, set_xy) {
30 this.datasets[setname] = set_xy;
31};
32
5c528fa2
DV
33DygraphLayout.prototype.setAnnotations = function(ann) {
34 // The Dygraph object's annotations aren't parsed. We parse them here and
35 // save a copy.
973e2b79 36 this.annotations = [];
5c528fa2
DV
37 var parse = this.attr_('xValueParser');
38 for (var i = 0; i < ann.length; i++) {
39 var a = {};
a685723c 40 if (!ann[i].xval && !ann[i].x) {
5c528fa2
DV
41 this.dygraph_.error("Annotations must have an 'x' property");
42 return;
43 }
ce5e8d36 44 if (ann[i].icon &&
33030f33
DV
45 !(ann[i].hasOwnProperty('width') &&
46 ann[i].hasOwnProperty('height'))) {
47 this.dygraph_.error("Must set width and height when setting " +
ce5e8d36
DV
48 "annotation.icon property");
49 return;
50 }
5c528fa2 51 Dygraph.update(a, ann[i]);
a685723c 52 if (!a.xval) a.xval = parse(a.x);
5c528fa2 53 this.annotations.push(a);
ce49c2fa 54 }
ce49c2fa
DV
55};
56
efe0829a
DV
57DygraphLayout.prototype.evaluate = function() {
58 this._evaluateLimits();
59 this._evaluateLineCharts();
60 this._evaluateLineTicks();
ce49c2fa 61 this._evaluateAnnotations();
efe0829a
DV
62};
63
64DygraphLayout.prototype._evaluateLimits = function() {
65 this.minxval = this.maxxval = null;
f6401bf6
DV
66 if (this.options.dateWindow) {
67 this.minxval = this.options.dateWindow[0];
68 this.maxxval = this.options.dateWindow[1];
69 } else {
70 for (var name in this.datasets) {
71 if (!this.datasets.hasOwnProperty(name)) continue;
72 var series = this.datasets[name];
48841144
NN
73 if (series.length > 1) {
74 var x1 = series[0][0];
75 if (!this.minxval || x1 < this.minxval) this.minxval = x1;
76
77 var x2 = series[series.length - 1][0];
78 if (!this.maxxval || x2 > this.maxxval) this.maxxval = x2;
79 }
f6401bf6 80 }
efe0829a
DV
81 }
82 this.xrange = this.maxxval - this.minxval;
83 this.xscale = (this.xrange != 0 ? 1/this.xrange : 1.0);
84
ea4942ed
DV
85 for (var i = 0; i < this.options.yAxes.length; i++) {
86 var axis = this.options.yAxes[i];
26ca7938
DV
87 axis.minyval = axis.computedValueRange[0];
88 axis.maxyval = axis.computedValueRange[1];
ea4942ed
DV
89 axis.yrange = axis.maxyval - axis.minyval;
90 axis.yscale = (axis.yrange != 0 ? 1.0 / axis.yrange : 1.0);
ff022deb 91
0037b2a4 92 axis.ylogrange = Dygraph.log10(axis.maxyval) - Dygraph.log10(axis.minyval);
ff022deb 93 axis.ylogscale = (axis.ylogrange != 0 ? 1.0 / axis.ylogrange : 1.0);
ea4942ed 94 }
efe0829a
DV
95};
96
97DygraphLayout.prototype._evaluateLineCharts = function() {
98 // add all the rects
99 this.points = new Array();
100 for (var setName in this.datasets) {
85b99f0b
DV
101 if (!this.datasets.hasOwnProperty(setName)) continue;
102
103 var dataset = this.datasets[setName];
ea4942ed
DV
104 var axis = this.options.yAxes[this.options.seriesToAxisMap[setName]];
105
85b99f0b
DV
106 for (var j = 0; j < dataset.length; j++) {
107 var item = dataset[j];
ff022deb 108
3637724f 109 var yval;
7d0e7a0d 110 if (axis.logscale) {
0037b2a4 111 yval = 1.0 - ((Dygraph.log10(parseFloat(item[1])) - Dygraph.log10(axis.minyval)) * axis.ylogscale); // really should just be yscale.
ff022deb 112 } else {
3637724f 113 yval = 1.0 - ((parseFloat(item[1]) - axis.minyval) * axis.yscale);
ff022deb 114 }
85b99f0b 115 var point = {
ff00d3e2 116 // TODO(danvk): here
85b99f0b 117 x: ((parseFloat(item[0]) - this.minxval) * this.xscale),
3637724f 118 y: yval,
85b99f0b
DV
119 xval: parseFloat(item[0]),
120 yval: parseFloat(item[1]),
121 name: setName
122 };
123
1a26f3fb 124 this.points.push(point);
85b99f0b 125 }
efe0829a
DV
126 }
127};
128
129DygraphLayout.prototype._evaluateLineTicks = function() {
130 this.xticks = new Array();
131 for (var i = 0; i < this.options.xTicks.length; i++) {
132 var tick = this.options.xTicks[i];
133 var label = tick.label;
134 var pos = this.xscale * (tick.v - this.minxval);
135 if ((pos >= 0.0) && (pos <= 1.0)) {
136 this.xticks.push([pos, label]);
137 }
138 }
139
140 this.yticks = new Array();
9012dd21 141 for (var i = 0; i < this.options.yAxes.length; i++ ) {
67076b22
DV
142 var axis = this.options.yAxes[i];
143 for (var j = 0; j < axis.ticks.length; j++) {
144 var tick = axis.ticks[j];
145 var label = tick.label;
ff022deb 146 var pos = this.dygraph_.toPercentYCoord(tick.v, i);
67076b22 147 if ((pos >= 0.0) && (pos <= 1.0)) {
9012dd21 148 this.yticks.push([i, pos, label]);
67076b22 149 }
efe0829a
DV
150 }
151 }
152};
153
6a1aa64f
DV
154
155/**
156 * Behaves the same way as PlotKit.Layout, but also copies the errors
157 * @private
158 */
285a6bda 159DygraphLayout.prototype.evaluateWithError = function() {
6a1aa64f
DV
160 this.evaluate();
161 if (!this.options.errorBars) return;
162
163 // Copy over the error terms
164 var i = 0; // index in this.points
165 for (var setName in this.datasets) {
85b99f0b
DV
166 if (!this.datasets.hasOwnProperty(setName)) continue;
167 var j = 0;
168 var dataset = this.datasets[setName];
169 for (var j = 0; j < dataset.length; j++, i++) {
170 var item = dataset[j];
171 var xv = parseFloat(item[0]);
172 var yv = parseFloat(item[1]);
173
174 if (xv == this.points[i].xval &&
175 yv == this.points[i].yval) {
176 this.points[i].errorMinus = parseFloat(item[2]);
177 this.points[i].errorPlus = parseFloat(item[3]);
178 }
179 }
6a1aa64f
DV
180 }
181};
182
ce49c2fa
DV
183DygraphLayout.prototype._evaluateAnnotations = function() {
184 // Add the annotations to the point to which they belong.
185 // Make a map from (setName, xval) to annotation for quick lookups.
186 var annotations = {};
187 for (var i = 0; i < this.annotations.length; i++) {
188 var a = this.annotations[i];
189 annotations[a.xval + "," + a.series] = a;
190 }
191
192 this.annotated_points = [];
193 for (var i = 0; i < this.points.length; i++) {
194 var p = this.points[i];
195 var k = p.xval + "," + p.name;
196 if (k in annotations) {
197 p.annotation = annotations[k];
198 this.annotated_points.push(p);
199 }
200 }
201};
202
6a1aa64f
DV
203/**
204 * Convenience function to remove all the data sets from a graph
205 */
285a6bda 206DygraphLayout.prototype.removeAllDatasets = function() {
6a1aa64f
DV
207 delete this.datasets;
208 this.datasets = new Array();
209};
210
211/**
212 * Change the values of various layout options
213 * @param {Object} new_options an associative array of new properties
214 */
285a6bda 215DygraphLayout.prototype.updateOptions = function(new_options) {
fc80a396 216 Dygraph.update(this.options, new_options ? new_options : {});
6a1aa64f
DV
217};
218
667d510b 219/**
220 * Return a copy of the point at the indicated index, with its yval unstacked.
221 * @param int index of point in layout_.points
222 */
8c03ba63 223DygraphLayout.prototype.unstackPointAtIndex = function(idx) {
667d510b 224 var point = this.points[idx];
225
226 // Clone the point since we modify it
227 var unstackedPoint = {};
228 for (var i in point) {
229 unstackedPoint[i] = point[i];
230 }
231
232 if (!this.attr_("stackedGraph")) {
233 return unstackedPoint;
234 }
235
236 // The unstacked yval is equal to the current yval minus the yval of the
237 // next point at the same xval.
238 for (var i = idx+1; i < this.points.length; i++) {
239 if (this.points[i].xval == point.xval) {
240 unstackedPoint.yval -= this.points[i].yval;
241 break;
242 }
243 }
244
245 return unstackedPoint;
246}
247
6a1aa64f
DV
248// Subclass PlotKit.CanvasRenderer to add:
249// 1. X/Y grid overlay
250// 2. Ability to draw error bars (if required)
251
252/**
253 * Sets some PlotKit.CanvasRenderer options
254 * @param {Object} element The canvas to attach to
285a6bda 255 * @param {Layout} layout The DygraphLayout object for this graph.
6a1aa64f
DV
256 * @param {Object} options Options to pass on to CanvasRenderer
257 */
9317362d
DV
258DygraphCanvasRenderer = function(dygraph, element, layout, options) {
259 // TODO(danvk): remove options, just use dygraph.attr_.
9317362d 260 this.dygraph_ = dygraph;
fbe31dc8
DV
261
262 // default options
263 this.options = {
f474c2a3
DV
264 "strokeWidth": 0.5,
265 "drawXAxis": true,
266 "drawYAxis": true,
267 "axisLineColor": "black",
268 "axisLineWidth": 0.5,
269 "axisTickSize": 3,
270 "axisLabelColor": "black",
271 "axisLabelFont": "Arial",
272 "axisLabelFontSize": 9,
273 "axisLabelWidth": 50,
274 "drawYGrid": true,
275 "drawXGrid": true,
43af96e7 276 "gridLineColor": "rgb(128,128,128)",
e7746234
EC
277 "fillAlpha": 0.15,
278 "underlayCallback": null
fbe31dc8 279 };
fc80a396 280 Dygraph.update(this.options, options);
6a1aa64f 281
fbe31dc8 282 this.layout = layout;
b0c3b730 283 this.element = element;
fbe31dc8
DV
284 this.container = this.element.parentNode;
285
fbe31dc8
DV
286 this.height = this.element.height;
287 this.width = this.element.width;
288
289 // --- check whether everything is ok before we return
290 if (!this.isIE && !(DygraphCanvasRenderer.isSupported(this.element)))
291 throw "Canvas is not supported.";
292
293 // internal state
294 this.xlabels = new Array();
295 this.ylabels = new Array();
ce49c2fa 296 this.annotations = new Array();
fbe31dc8 297
ea4942ed 298 // TODO(danvk): consider all axes in this computation.
fbe31dc8 299 this.area = {
9012dd21 300 // TODO(danvk): per-axis setting.
fbe31dc8
DV
301 x: this.options.yAxisLabelWidth + 2 * this.options.axisTickSize,
302 y: 0
303 };
304 this.area.w = this.width - this.area.x - this.options.rightGap;
305 this.area.h = this.height - this.options.axisLabelFontSize -
306 2 * this.options.axisTickSize;
307
26ca7938
DV
308 // Shrink the drawing area to accomodate additional y-axes.
309 if (this.dygraph_.numAxes() == 2) {
310 // TODO(danvk): per-axis setting.
311 this.area.w -= (this.options.yAxisLabelWidth + 2 * this.options.axisTickSize);
312 } else if (this.dygraph_.numAxes() > 2) {
313 this.dygraph_.error("Only two y-axes are supported at this time. (Trying " +
34de8b76 314 "to use " + this.dygraph_.numAxes() + ")");
26ca7938
DV
315 }
316
b0c3b730
DV
317 this.container.style.position = "relative";
318 this.container.style.width = this.width + "px";
26ca7938
DV
319
320 // Set up a clipping area for the canvas (and the interaction canvas).
321 // This ensures that we don't overdraw.
8c21adcf 322 var ctx = this.dygraph_.canvas_.getContext("2d");
26ca7938
DV
323 ctx.beginPath();
324 ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h);
325 ctx.clip();
326
8c21adcf 327 ctx = this.dygraph_.hidden_.getContext("2d");
26ca7938
DV
328 ctx.beginPath();
329 ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h);
330 ctx.clip();
fbe31dc8
DV
331};
332
44c6bc29
DV
333DygraphCanvasRenderer.prototype.attr_ = function(x) {
334 return this.dygraph_.attr_(x);
335};
336
fbe31dc8
DV
337DygraphCanvasRenderer.prototype.clear = function() {
338 if (this.isIE) {
339 // VML takes a while to start up, so we just poll every this.IEDelay
340 try {
341 if (this.clearDelay) {
342 this.clearDelay.cancel();
343 this.clearDelay = null;
344 }
345 var context = this.element.getContext("2d");
346 }
347 catch (e) {
76171648 348 // TODO(danvk): this is broken, since MochiKit.Async is gone.
fbe31dc8
DV
349 this.clearDelay = MochiKit.Async.wait(this.IEDelay);
350 this.clearDelay.addCallback(bind(this.clear, this));
351 return;
352 }
353 }
354
355 var context = this.element.getContext("2d");
356 context.clearRect(0, 0, this.width, this.height);
357
2160ed4a 358 for (var i = 0; i < this.xlabels.length; i++) {
b0c3b730 359 var el = this.xlabels[i];
b304aaec 360 if (el.parentNode) el.parentNode.removeChild(el);
2160ed4a
DV
361 }
362 for (var i = 0; i < this.ylabels.length; i++) {
b0c3b730 363 var el = this.ylabels[i];
b304aaec 364 if (el.parentNode) el.parentNode.removeChild(el);
2160ed4a 365 }
ce49c2fa
DV
366 for (var i = 0; i < this.annotations.length; i++) {
367 var el = this.annotations[i];
b304aaec 368 if (el.parentNode) el.parentNode.removeChild(el);
ce49c2fa 369 }
fbe31dc8
DV
370 this.xlabels = new Array();
371 this.ylabels = new Array();
ce49c2fa 372 this.annotations = new Array();
fbe31dc8
DV
373};
374
375
376DygraphCanvasRenderer.isSupported = function(canvasName) {
377 var canvas = null;
378 try {
21d3323f 379 if (typeof(canvasName) == 'undefined' || canvasName == null)
b0c3b730 380 canvas = document.createElement("canvas");
fbe31dc8 381 else
b0c3b730 382 canvas = canvasName;
fbe31dc8
DV
383 var context = canvas.getContext("2d");
384 }
385 catch (e) {
386 var ie = navigator.appVersion.match(/MSIE (\d\.\d)/);
387 var opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
388 if ((!ie) || (ie[1] < 6) || (opera))
389 return false;
390 return true;
391 }
392 return true;
6a1aa64f 393};
6a1aa64f
DV
394
395/**
396 * Draw an X/Y grid on top of the existing plot
397 */
285a6bda 398DygraphCanvasRenderer.prototype.render = function() {
528ce7e5
DV
399 // Draw the new X/Y grid. Lines appear crisper when pixels are rounded to
400 // half-integers. This prevents them from drawing in two rows/cols.
6a1aa64f 401 var ctx = this.element.getContext("2d");
528ce7e5
DV
402 function halfUp(x){return Math.round(x)+0.5};
403 function halfDown(y){return Math.round(y)-0.5};
e7746234
EC
404
405 if (this.options.underlayCallback) {
1e41bd2d
DV
406 // NOTE: we pass the dygraph object to this callback twice to avoid breaking
407 // users who expect a deprecated form of this callback.
408 this.options.underlayCallback(ctx, this.area, this.dygraph_, this.dygraph_);
e7746234
EC
409 }
410
6a1aa64f
DV
411 if (this.options.drawYGrid) {
412 var ticks = this.layout.yticks;
413 ctx.save();
f2f24402 414 ctx.strokeStyle = this.options.gridLineColor;
6a1aa64f
DV
415 ctx.lineWidth = this.options.axisLineWidth;
416 for (var i = 0; i < ticks.length; i++) {
880a574f
DV
417 // TODO(danvk): allow secondary axes to draw a grid, too.
418 if (ticks[i][0] != 0) continue;
528ce7e5
DV
419 var x = halfUp(this.area.x);
420 var y = halfDown(this.area.y + ticks[i][1] * this.area.h);
6a1aa64f
DV
421 ctx.beginPath();
422 ctx.moveTo(x, y);
423 ctx.lineTo(x + this.area.w, y);
424 ctx.closePath();
425 ctx.stroke();
426 }
427 }
428
429 if (this.options.drawXGrid) {
430 var ticks = this.layout.xticks;
431 ctx.save();
f2f24402 432 ctx.strokeStyle = this.options.gridLineColor;
6a1aa64f
DV
433 ctx.lineWidth = this.options.axisLineWidth;
434 for (var i=0; i<ticks.length; i++) {
528ce7e5
DV
435 var x = halfUp(this.area.x + ticks[i][0] * this.area.w);
436 var y = halfDown(this.area.y + this.area.h);
6a1aa64f 437 ctx.beginPath();
880a574f 438 ctx.moveTo(x, y);
6a1aa64f
DV
439 ctx.lineTo(x, this.area.y);
440 ctx.closePath();
441 ctx.stroke();
442 }
443 }
2ce09b19
DV
444
445 // Do the ordinary rendering, as before
2ce09b19 446 this._renderLineChart();
fbe31dc8 447 this._renderAxis();
ce49c2fa 448 this._renderAnnotations();
fbe31dc8
DV
449};
450
451
452DygraphCanvasRenderer.prototype._renderAxis = function() {
453 if (!this.options.drawXAxis && !this.options.drawYAxis)
454 return;
455
528ce7e5
DV
456 // Round pixels to half-integer boundaries for crisper drawing.
457 function halfUp(x){return Math.round(x)+0.5};
458 function halfDown(y){return Math.round(y)-0.5};
459
fbe31dc8
DV
460 var context = this.element.getContext("2d");
461
34fedff8
DV
462 var labelStyle = {
463 "position": "absolute",
464 "fontSize": this.options.axisLabelFontSize + "px",
465 "zIndex": 10,
f474c2a3 466 "color": this.options.axisLabelColor,
34fedff8
DV
467 "width": this.options.axisLabelWidth + "px",
468 "overflow": "hidden"
469 };
470 var makeDiv = function(txt) {
471 var div = document.createElement("div");
472 for (var name in labelStyle) {
85b99f0b
DV
473 if (labelStyle.hasOwnProperty(name)) {
474 div.style[name] = labelStyle[name];
475 }
fbe31dc8 476 }
34fedff8
DV
477 div.appendChild(document.createTextNode(txt));
478 return div;
fbe31dc8
DV
479 };
480
481 // axis lines
482 context.save();
f474c2a3 483 context.strokeStyle = this.options.axisLineColor;
fbe31dc8
DV
484 context.lineWidth = this.options.axisLineWidth;
485
fbe31dc8 486 if (this.options.drawYAxis) {
8b7a0cc3 487 if (this.layout.yticks && this.layout.yticks.length > 0) {
2160ed4a
DV
488 for (var i = 0; i < this.layout.yticks.length; i++) {
489 var tick = this.layout.yticks[i];
fbe31dc8
DV
490 if (typeof(tick) == "function") return;
491 var x = this.area.x;
880a574f
DV
492 var sgn = 1;
493 if (tick[0] == 1) { // right-side y-axis
494 x = this.area.x + this.area.w;
495 sgn = -1;
9012dd21
DV
496 }
497 var y = this.area.y + tick[1] * this.area.h;
fbe31dc8 498 context.beginPath();
528ce7e5
DV
499 context.moveTo(halfUp(x), halfDown(y));
500 context.lineTo(halfUp(x - sgn * this.options.axisTickSize), halfDown(y));
fbe31dc8
DV
501 context.closePath();
502 context.stroke();
503
9012dd21 504 var label = makeDiv(tick[2]);
fbe31dc8
DV
505 var top = (y - this.options.axisLabelFontSize / 2);
506 if (top < 0) top = 0;
507
508 if (top + this.options.axisLabelFontSize + 3 > this.height) {
509 label.style.bottom = "0px";
510 } else {
511 label.style.top = top + "px";
512 }
9012dd21
DV
513 if (tick[0] == 0) {
514 label.style.left = "0px";
515 label.style.textAlign = "right";
516 } else if (tick[0] == 1) {
517 label.style.left = (this.area.x + this.area.w +
518 this.options.axisTickSize) + "px";
519 label.style.textAlign = "left";
520 }
fbe31dc8 521 label.style.width = this.options.yAxisLabelWidth + "px";
b0c3b730 522 this.container.appendChild(label);
fbe31dc8 523 this.ylabels.push(label);
2160ed4a 524 }
fbe31dc8
DV
525
526 // The lowest tick on the y-axis often overlaps with the leftmost
527 // tick on the x-axis. Shift the bottom tick up a little bit to
528 // compensate if necessary.
529 var bottomTick = this.ylabels[0];
530 var fontSize = this.options.axisLabelFontSize;
531 var bottom = parseInt(bottomTick.style.top) + fontSize;
532 if (bottom > this.height - fontSize) {
533 bottomTick.style.top = (parseInt(bottomTick.style.top) -
534 fontSize / 2) + "px";
535 }
536 }
537
528ce7e5 538 // draw a vertical line on the left to separate the chart from the labels.
fbe31dc8 539 context.beginPath();
528ce7e5
DV
540 context.moveTo(halfUp(this.area.x), halfDown(this.area.y));
541 context.lineTo(halfUp(this.area.x), halfDown(this.area.y + this.area.h));
fbe31dc8
DV
542 context.closePath();
543 context.stroke();
c1dbeb10 544
528ce7e5 545 // if there's a secondary y-axis, draw a vertical line for that, too.
c1dbeb10
DV
546 if (this.dygraph_.numAxes() == 2) {
547 context.beginPath();
528ce7e5
DV
548 context.moveTo(halfDown(this.area.x + this.area.w), halfDown(this.area.y));
549 context.lineTo(halfDown(this.area.x + this.area.w), halfDown(this.area.y + this.area.h));
c1dbeb10
DV
550 context.closePath();
551 context.stroke();
552 }
fbe31dc8
DV
553 }
554
555 if (this.options.drawXAxis) {
556 if (this.layout.xticks) {
2160ed4a
DV
557 for (var i = 0; i < this.layout.xticks.length; i++) {
558 var tick = this.layout.xticks[i];
fbe31dc8
DV
559 if (typeof(dataset) == "function") return;
560
561 var x = this.area.x + tick[0] * this.area.w;
562 var y = this.area.y + this.area.h;
563 context.beginPath();
528ce7e5
DV
564 context.moveTo(halfUp(x), halfDown(y));
565 context.lineTo(halfUp(x), halfDown(y + this.options.axisTickSize));
fbe31dc8
DV
566 context.closePath();
567 context.stroke();
568
34fedff8 569 var label = makeDiv(tick[1]);
fbe31dc8
DV
570 label.style.textAlign = "center";
571 label.style.bottom = "0px";
572
573 var left = (x - this.options.axisLabelWidth/2);
574 if (left + this.options.axisLabelWidth > this.width) {
575 left = this.width - this.options.xAxisLabelWidth;
576 label.style.textAlign = "right";
577 }
578 if (left < 0) {
579 left = 0;
580 label.style.textAlign = "left";
581 }
582
583 label.style.left = left + "px";
584 label.style.width = this.options.xAxisLabelWidth + "px";
b0c3b730 585 this.container.appendChild(label);
fbe31dc8 586 this.xlabels.push(label);
2160ed4a 587 }
fbe31dc8
DV
588 }
589
590 context.beginPath();
528ce7e5
DV
591 context.moveTo(halfUp(this.area.x), halfDown(this.area.y + this.area.h));
592 context.lineTo(halfUp(this.area.x + this.area.w), halfDown(this.area.y + this.area.h));
fbe31dc8
DV
593 context.closePath();
594 context.stroke();
595 }
596
597 context.restore();
6a1aa64f
DV
598};
599
fbe31dc8 600
ce49c2fa
DV
601DygraphCanvasRenderer.prototype._renderAnnotations = function() {
602 var annotationStyle = {
603 "position": "absolute",
604 "fontSize": this.options.axisLabelFontSize + "px",
605 "zIndex": 10,
3bf2fa91 606 "overflow": "hidden"
ce49c2fa
DV
607 };
608
ab5e5c75
DV
609 var bindEvt = function(eventName, classEventName, p, self) {
610 return function(e) {
611 var a = p.annotation;
612 if (a.hasOwnProperty(eventName)) {
613 a[eventName](a, p, self.dygraph_, e);
614 } else if (self.dygraph_.attr_(classEventName)) {
615 self.dygraph_.attr_(classEventName)(a, p, self.dygraph_,e );
616 }
617 };
618 }
619
ce49c2fa
DV
620 // Get a list of point with annotations.
621 var points = this.layout.annotated_points;
622 for (var i = 0; i < points.length; i++) {
623 var p = points[i];
e6d53148
DV
624 if (p.canvasx < this.area.x || p.canvasx > this.area.x + this.area.w) {
625 continue;
626 }
627
ce5e8d36
DV
628 var a = p.annotation;
629 var tick_height = 6;
630 if (a.hasOwnProperty("tickHeight")) {
631 tick_height = a.tickHeight;
9a40897e
DV
632 }
633
ce49c2fa
DV
634 var div = document.createElement("div");
635 for (var name in annotationStyle) {
636 if (annotationStyle.hasOwnProperty(name)) {
637 div.style[name] = annotationStyle[name];
638 }
639 }
ce5e8d36
DV
640 if (!a.hasOwnProperty('icon')) {
641 div.className = "dygraphDefaultAnnotation";
642 }
643 if (a.hasOwnProperty('cssClass')) {
644 div.className += " " + a.cssClass;
645 }
646
a5ad69cc
DV
647 var width = a.hasOwnProperty('width') ? a.width : 16;
648 var height = a.hasOwnProperty('height') ? a.height : 16;
ce5e8d36
DV
649 if (a.hasOwnProperty('icon')) {
650 var img = document.createElement("img");
651 img.src = a.icon;
33030f33
DV
652 img.width = width;
653 img.height = height;
ce5e8d36
DV
654 div.appendChild(img);
655 } else if (p.annotation.hasOwnProperty('shortText')) {
656 div.appendChild(document.createTextNode(p.annotation.shortText));
5c528fa2 657 }
ce5e8d36 658 div.style.left = (p.canvasx - width / 2) + "px";
d14b9eed
DV
659 if (a.attachAtBottom) {
660 div.style.top = (this.area.h - height - tick_height) + "px";
661 } else {
662 div.style.top = (p.canvasy - height - tick_height) + "px";
663 }
ce5e8d36
DV
664 div.style.width = width + "px";
665 div.style.height = height + "px";
ce49c2fa
DV
666 div.title = p.annotation.text;
667 div.style.color = this.colors[p.name];
668 div.style.borderColor = this.colors[p.name];
e6d53148 669 a.div = div;
ab5e5c75 670
9a40897e
DV
671 Dygraph.addEvent(div, 'click',
672 bindEvt('clickHandler', 'annotationClickHandler', p, this));
673 Dygraph.addEvent(div, 'mouseover',
674 bindEvt('mouseOverHandler', 'annotationMouseOverHandler', p, this));
675 Dygraph.addEvent(div, 'mouseout',
676 bindEvt('mouseOutHandler', 'annotationMouseOutHandler', p, this));
677 Dygraph.addEvent(div, 'dblclick',
678 bindEvt('dblClickHandler', 'annotationDblClickHandler', p, this));
ab5e5c75 679
ce49c2fa
DV
680 this.container.appendChild(div);
681 this.annotations.push(div);
9a40897e
DV
682
683 var ctx = this.element.getContext("2d");
684 ctx.strokeStyle = this.colors[p.name];
685 ctx.beginPath();
d14b9eed
DV
686 if (!a.attachAtBottom) {
687 ctx.moveTo(p.canvasx, p.canvasy);
688 ctx.lineTo(p.canvasx, p.canvasy - 2 - tick_height);
689 } else {
690 ctx.moveTo(p.canvasx, this.area.h);
691 ctx.lineTo(p.canvasx, this.area.h - 2 - tick_height);
692 }
9a40897e
DV
693 ctx.closePath();
694 ctx.stroke();
ce49c2fa
DV
695 }
696};
697
698
6a1aa64f
DV
699/**
700 * Overrides the CanvasRenderer method to draw error bars
701 */
285a6bda 702DygraphCanvasRenderer.prototype._renderLineChart = function() {
44c6bc29 703 // TODO(danvk): use this.attr_ for many of these.
6a1aa64f
DV
704 var context = this.element.getContext("2d");
705 var colorCount = this.options.colorScheme.length;
706 var colorScheme = this.options.colorScheme;
43af96e7 707 var fillAlpha = this.options.fillAlpha;
6a1aa64f 708 var errorBars = this.layout.options.errorBars;
44c6bc29 709 var fillGraph = this.attr_("fillGraph");
354e15ab 710 var stackedGraph = this.layout.options.stackedGraph;
afdc483f 711 var stepPlot = this.layout.options.stepPlot;
21d3323f
DV
712
713 var setNames = [];
ca43052c 714 for (var name in this.layout.datasets) {
85b99f0b
DV
715 if (this.layout.datasets.hasOwnProperty(name)) {
716 setNames.push(name);
717 }
ca43052c 718 }
21d3323f 719 var setCount = setNames.length;
6a1aa64f 720
f032c51d
AV
721 this.colors = {}
722 for (var i = 0; i < setCount; i++) {
723 this.colors[setNames[i]] = colorScheme[i % colorCount];
724 }
725
ff00d3e2
DV
726 // Update Points
727 // TODO(danvk): here
2160ed4a
DV
728 for (var i = 0; i < this.layout.points.length; i++) {
729 var point = this.layout.points[i];
6a1aa64f
DV
730 point.canvasx = this.area.w * point.x + this.area.x;
731 point.canvasy = this.area.h * point.y + this.area.y;
732 }
6a1aa64f
DV
733
734 // create paths
9317362d 735 var isOK = function(x) { return x && !isNaN(x); };
6a1aa64f 736
80aaae18
DV
737 var ctx = context;
738 if (errorBars) {
6a834bbb
DV
739 if (fillGraph) {
740 this.dygraph_.warn("Can't use fillGraph option with error bars");
741 }
742
6a1aa64f
DV
743 for (var i = 0; i < setCount; i++) {
744 var setName = setNames[i];
ea4942ed
DV
745 var axis = this.layout.options.yAxes[
746 this.layout.options.seriesToAxisMap[setName]];
f032c51d 747 var color = this.colors[setName];
6a1aa64f
DV
748
749 // setup graphics context
80aaae18 750 ctx.save();
56623f3b 751 var prevX = NaN;
afdc483f 752 var prevY = NaN;
6a1aa64f 753 var prevYs = [-1, -1];
ea4942ed 754 var yscale = axis.yscale;
f474c2a3
DV
755 // should be same color as the lines but only 15% opaque.
756 var rgb = new RGBColor(color);
43af96e7
NK
757 var err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
758 fillAlpha + ')';
f474c2a3 759 ctx.fillStyle = err_color;
05c9d0c4
DV
760 ctx.beginPath();
761 for (var j = 0; j < this.layout.points.length; j++) {
762 var point = this.layout.points[j];
6a1aa64f 763 if (point.name == setName) {
5954ef32 764 if (!isOK(point.y)) {
56623f3b 765 prevX = NaN;
ae85914a 766 continue;
5011e7a1 767 }
ce49c2fa 768
3637724f 769 // TODO(danvk): here
afdc483f
NN
770 if (stepPlot) {
771 var newYs = [ prevY - point.errorPlus * yscale,
47600757 772 prevY + point.errorMinus * yscale ];
afdc483f
NN
773 prevY = point.y;
774 } else {
775 var newYs = [ point.y - point.errorPlus * yscale,
47600757 776 point.y + point.errorMinus * yscale ];
afdc483f 777 }
6a1aa64f
DV
778 newYs[0] = this.area.h * newYs[0] + this.area.y;
779 newYs[1] = this.area.h * newYs[1] + this.area.y;
56623f3b 780 if (!isNaN(prevX)) {
afdc483f 781 if (stepPlot) {
47600757 782 ctx.moveTo(prevX, newYs[0]);
afdc483f 783 } else {
47600757 784 ctx.moveTo(prevX, prevYs[0]);
afdc483f 785 }
5954ef32
DV
786 ctx.lineTo(point.canvasx, newYs[0]);
787 ctx.lineTo(point.canvasx, newYs[1]);
afdc483f 788 if (stepPlot) {
47600757 789 ctx.lineTo(prevX, newYs[1]);
afdc483f 790 } else {
47600757 791 ctx.lineTo(prevX, prevYs[1]);
afdc483f 792 }
5954ef32
DV
793 ctx.closePath();
794 }
354e15ab 795 prevYs = newYs;
5954ef32
DV
796 prevX = point.canvasx;
797 }
798 }
799 ctx.fill();
800 }
801 } else if (fillGraph) {
354e15ab
DE
802 var baseline = [] // for stacked graphs: baseline for filling
803
804 // process sets in reverse order (needed for stacked graphs)
805 for (var i = setCount - 1; i >= 0; i--) {
5954ef32 806 var setName = setNames[i];
f032c51d 807 var color = this.colors[setName];
ea4942ed
DV
808 var axis = this.layout.options.yAxes[
809 this.layout.options.seriesToAxisMap[setName]];
810 var axisY = 1.0 + axis.minyval * axis.yscale;
811 if (axisY < 0.0) axisY = 0.0;
812 else if (axisY > 1.0) axisY = 1.0;
813 axisY = this.area.h * axisY + this.area.y;
5954ef32
DV
814
815 // setup graphics context
816 ctx.save();
56623f3b 817 var prevX = NaN;
5954ef32 818 var prevYs = [-1, -1];
ea4942ed 819 var yscale = axis.yscale;
5954ef32
DV
820 // should be same color as the lines but only 15% opaque.
821 var rgb = new RGBColor(color);
43af96e7
NK
822 var err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
823 fillAlpha + ')';
5954ef32
DV
824 ctx.fillStyle = err_color;
825 ctx.beginPath();
826 for (var j = 0; j < this.layout.points.length; j++) {
827 var point = this.layout.points[j];
5954ef32
DV
828 if (point.name == setName) {
829 if (!isOK(point.y)) {
56623f3b 830 prevX = NaN;
5954ef32
DV
831 continue;
832 }
354e15ab
DE
833 var newYs;
834 if (stackedGraph) {
835 lastY = baseline[point.canvasx];
836 if (lastY === undefined) lastY = axisY;
837 baseline[point.canvasx] = point.canvasy;
838 newYs = [ point.canvasy, lastY ];
839 } else {
840 newYs = [ point.canvasy, axisY ];
841 }
56623f3b 842 if (!isNaN(prevX)) {
05c9d0c4 843 ctx.moveTo(prevX, prevYs[0]);
afdc483f 844 if (stepPlot) {
47600757 845 ctx.lineTo(point.canvasx, prevYs[0]);
afdc483f 846 } else {
47600757 847 ctx.lineTo(point.canvasx, newYs[0]);
afdc483f 848 }
05c9d0c4
DV
849 ctx.lineTo(point.canvasx, newYs[1]);
850 ctx.lineTo(prevX, prevYs[1]);
851 ctx.closePath();
6a1aa64f 852 }
354e15ab 853 prevYs = newYs;
6a1aa64f
DV
854 prevX = point.canvasx;
855 }
05c9d0c4 856 }
6a1aa64f
DV
857 ctx.fill();
858 }
80aaae18
DV
859 }
860
861 for (var i = 0; i < setCount; i++) {
862 var setName = setNames[i];
f032c51d 863 var color = this.colors[setName];
227b93cc 864 var strokeWidth = this.dygraph_.attr_("strokeWidth", setName);
80aaae18
DV
865
866 // setup graphics context
867 context.save();
868 var point = this.layout.points[0];
227b93cc 869 var pointSize = this.dygraph_.attr_("pointSize", setName);
80aaae18 870 var prevX = null, prevY = null;
227b93cc 871 var drawPoints = this.dygraph_.attr_("drawPoints", setName);
80aaae18
DV
872 var points = this.layout.points;
873 for (var j = 0; j < points.length; j++) {
874 var point = points[j];
875 if (point.name == setName) {
876 if (!isOK(point.canvasy)) {
5d13ef68 877 if (stepPlot && prevX != null) {
0599d13b
NN
878 // Draw a horizontal line to the start of the missing data
879 ctx.beginPath();
880 ctx.strokeStyle = color;
881 ctx.lineWidth = this.options.strokeWidth;
882 ctx.moveTo(prevX, prevY);
883 ctx.lineTo(point.canvasx, prevY);
884 ctx.stroke();
885 }
80aaae18
DV
886 // this will make us move to the next point, not draw a line to it.
887 prevX = prevY = null;
888 } else {
889 // A point is "isolated" if it is non-null but both the previous
890 // and next points are null.
891 var isIsolated = (!prevX && (j == points.length - 1 ||
892 !isOK(points[j+1].canvasy)));
893
894 if (!prevX) {
895 prevX = point.canvasx;
896 prevY = point.canvasy;
897 } else {
46dde5f9
DV
898 // TODO(danvk): figure out why this conditional is necessary.
899 if (strokeWidth) {
900 ctx.beginPath();
901 ctx.strokeStyle = color;
902 ctx.lineWidth = strokeWidth;
903 ctx.moveTo(prevX, prevY);
904 if (stepPlot) {
905 ctx.lineTo(point.canvasx, prevY);
906 }
907 prevX = point.canvasx;
908 prevY = point.canvasy;
909 ctx.lineTo(prevX, prevY);
910 ctx.stroke();
afdc483f 911 }
80aaae18
DV
912 }
913
914 if (drawPoints || isIsolated) {
915 ctx.beginPath();
916 ctx.fillStyle = color;
7bf6a9fe
DV
917 ctx.arc(point.canvasx, point.canvasy, pointSize,
918 0, 2 * Math.PI, false);
80aaae18
DV
919 ctx.fill();
920 }
921 }
922 }
923 }
924 }
6a1aa64f 925
6a1aa64f
DV
926 context.restore();
927};