more warnings on CSV parsing
[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
9317362d 742 var isOK = function(x) { return x && !isNaN(x); };
6a1aa64f 743
80aaae18
DV
744 var ctx = context;
745 if (errorBars) {
6a834bbb
DV
746 if (fillGraph) {
747 this.dygraph_.warn("Can't use fillGraph option with error bars");
748 }
749
6a1aa64f
DV
750 for (var i = 0; i < setCount; i++) {
751 var setName = setNames[i];
ea4942ed
DV
752 var axis = this.layout.options.yAxes[
753 this.layout.options.seriesToAxisMap[setName]];
f032c51d 754 var color = this.colors[setName];
6a1aa64f
DV
755
756 // setup graphics context
80aaae18 757 ctx.save();
56623f3b 758 var prevX = NaN;
afdc483f 759 var prevY = NaN;
6a1aa64f 760 var prevYs = [-1, -1];
ea4942ed 761 var yscale = axis.yscale;
f474c2a3
DV
762 // should be same color as the lines but only 15% opaque.
763 var rgb = new RGBColor(color);
43af96e7
NK
764 var err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
765 fillAlpha + ')';
f474c2a3 766 ctx.fillStyle = err_color;
05c9d0c4
DV
767 ctx.beginPath();
768 for (var j = 0; j < this.layout.points.length; j++) {
769 var point = this.layout.points[j];
6a1aa64f 770 if (point.name == setName) {
5954ef32 771 if (!isOK(point.y)) {
56623f3b 772 prevX = NaN;
ae85914a 773 continue;
5011e7a1 774 }
ce49c2fa 775
3637724f 776 // TODO(danvk): here
afdc483f
NN
777 if (stepPlot) {
778 var newYs = [ prevY - point.errorPlus * yscale,
47600757 779 prevY + point.errorMinus * yscale ];
afdc483f
NN
780 prevY = point.y;
781 } else {
782 var newYs = [ point.y - point.errorPlus * yscale,
47600757 783 point.y + point.errorMinus * yscale ];
afdc483f 784 }
6a1aa64f
DV
785 newYs[0] = this.area.h * newYs[0] + this.area.y;
786 newYs[1] = this.area.h * newYs[1] + this.area.y;
56623f3b 787 if (!isNaN(prevX)) {
afdc483f 788 if (stepPlot) {
47600757 789 ctx.moveTo(prevX, newYs[0]);
afdc483f 790 } else {
47600757 791 ctx.moveTo(prevX, prevYs[0]);
afdc483f 792 }
5954ef32
DV
793 ctx.lineTo(point.canvasx, newYs[0]);
794 ctx.lineTo(point.canvasx, newYs[1]);
afdc483f 795 if (stepPlot) {
47600757 796 ctx.lineTo(prevX, newYs[1]);
afdc483f 797 } else {
47600757 798 ctx.lineTo(prevX, prevYs[1]);
afdc483f 799 }
5954ef32
DV
800 ctx.closePath();
801 }
354e15ab 802 prevYs = newYs;
5954ef32
DV
803 prevX = point.canvasx;
804 }
805 }
806 ctx.fill();
807 }
808 } else if (fillGraph) {
354e15ab
DE
809 var baseline = [] // for stacked graphs: baseline for filling
810
811 // process sets in reverse order (needed for stacked graphs)
812 for (var i = setCount - 1; i >= 0; i--) {
5954ef32 813 var setName = setNames[i];
f032c51d 814 var color = this.colors[setName];
ea4942ed
DV
815 var axis = this.layout.options.yAxes[
816 this.layout.options.seriesToAxisMap[setName]];
817 var axisY = 1.0 + axis.minyval * axis.yscale;
818 if (axisY < 0.0) axisY = 0.0;
819 else if (axisY > 1.0) axisY = 1.0;
820 axisY = this.area.h * axisY + this.area.y;
5954ef32
DV
821
822 // setup graphics context
823 ctx.save();
56623f3b 824 var prevX = NaN;
5954ef32 825 var prevYs = [-1, -1];
ea4942ed 826 var yscale = axis.yscale;
5954ef32
DV
827 // should be same color as the lines but only 15% opaque.
828 var rgb = new RGBColor(color);
43af96e7
NK
829 var err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
830 fillAlpha + ')';
5954ef32
DV
831 ctx.fillStyle = err_color;
832 ctx.beginPath();
833 for (var j = 0; j < this.layout.points.length; j++) {
834 var point = this.layout.points[j];
5954ef32
DV
835 if (point.name == setName) {
836 if (!isOK(point.y)) {
56623f3b 837 prevX = NaN;
5954ef32
DV
838 continue;
839 }
354e15ab
DE
840 var newYs;
841 if (stackedGraph) {
842 lastY = baseline[point.canvasx];
843 if (lastY === undefined) lastY = axisY;
844 baseline[point.canvasx] = point.canvasy;
845 newYs = [ point.canvasy, lastY ];
846 } else {
847 newYs = [ point.canvasy, axisY ];
848 }
56623f3b 849 if (!isNaN(prevX)) {
05c9d0c4 850 ctx.moveTo(prevX, prevYs[0]);
afdc483f 851 if (stepPlot) {
47600757 852 ctx.lineTo(point.canvasx, prevYs[0]);
afdc483f 853 } else {
47600757 854 ctx.lineTo(point.canvasx, newYs[0]);
afdc483f 855 }
05c9d0c4
DV
856 ctx.lineTo(point.canvasx, newYs[1]);
857 ctx.lineTo(prevX, prevYs[1]);
858 ctx.closePath();
6a1aa64f 859 }
354e15ab 860 prevYs = newYs;
6a1aa64f
DV
861 prevX = point.canvasx;
862 }
05c9d0c4 863 }
6a1aa64f
DV
864 ctx.fill();
865 }
80aaae18
DV
866 }
867
868 for (var i = 0; i < setCount; i++) {
869 var setName = setNames[i];
f032c51d 870 var color = this.colors[setName];
227b93cc 871 var strokeWidth = this.dygraph_.attr_("strokeWidth", setName);
80aaae18
DV
872
873 // setup graphics context
874 context.save();
875 var point = this.layout.points[0];
227b93cc 876 var pointSize = this.dygraph_.attr_("pointSize", setName);
80aaae18 877 var prevX = null, prevY = null;
227b93cc 878 var drawPoints = this.dygraph_.attr_("drawPoints", setName);
80aaae18
DV
879 var points = this.layout.points;
880 for (var j = 0; j < points.length; j++) {
881 var point = points[j];
882 if (point.name == setName) {
883 if (!isOK(point.canvasy)) {
5d13ef68 884 if (stepPlot && prevX != null) {
0599d13b
NN
885 // Draw a horizontal line to the start of the missing data
886 ctx.beginPath();
887 ctx.strokeStyle = color;
888 ctx.lineWidth = this.options.strokeWidth;
889 ctx.moveTo(prevX, prevY);
890 ctx.lineTo(point.canvasx, prevY);
891 ctx.stroke();
892 }
80aaae18
DV
893 // this will make us move to the next point, not draw a line to it.
894 prevX = prevY = null;
895 } else {
896 // A point is "isolated" if it is non-null but both the previous
897 // and next points are null.
898 var isIsolated = (!prevX && (j == points.length - 1 ||
899 !isOK(points[j+1].canvasy)));
900
901 if (!prevX) {
902 prevX = point.canvasx;
903 prevY = point.canvasy;
904 } else {
46dde5f9
DV
905 // TODO(danvk): figure out why this conditional is necessary.
906 if (strokeWidth) {
907 ctx.beginPath();
908 ctx.strokeStyle = color;
909 ctx.lineWidth = strokeWidth;
910 ctx.moveTo(prevX, prevY);
911 if (stepPlot) {
912 ctx.lineTo(point.canvasx, prevY);
913 }
914 prevX = point.canvasx;
915 prevY = point.canvasy;
916 ctx.lineTo(prevX, prevY);
917 ctx.stroke();
afdc483f 918 }
80aaae18
DV
919 }
920
921 if (drawPoints || isIsolated) {
922 ctx.beginPath();
923 ctx.fillStyle = color;
7bf6a9fe
DV
924 ctx.arc(point.canvasx, point.canvasy, pointSize,
925 0, 2 * Math.PI, false);
80aaae18
DV
926 ctx.fill();
927 }
928 }
929 }
930 }
931 }
6a1aa64f 932
6a1aa64f
DV
933 context.restore();
934};