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