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