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