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