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