fix color-visibility test
[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.
312 var ctx = this.element.getContext("2d");
313 ctx.beginPath();
314 ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h);
315 ctx.clip();
316
317 var ctx = this.dygraph_.hidden_.getContext("2d");
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
323DygraphCanvasRenderer.prototype.clear = function() {
324 if (this.isIE) {
325 // VML takes a while to start up, so we just poll every this.IEDelay
326 try {
327 if (this.clearDelay) {
328 this.clearDelay.cancel();
329 this.clearDelay = null;
330 }
331 var context = this.element.getContext("2d");
332 }
333 catch (e) {
76171648 334 // TODO(danvk): this is broken, since MochiKit.Async is gone.
fbe31dc8
DV
335 this.clearDelay = MochiKit.Async.wait(this.IEDelay);
336 this.clearDelay.addCallback(bind(this.clear, this));
337 return;
338 }
339 }
340
341 var context = this.element.getContext("2d");
342 context.clearRect(0, 0, this.width, this.height);
343
2160ed4a 344 for (var i = 0; i < this.xlabels.length; i++) {
b0c3b730
DV
345 var el = this.xlabels[i];
346 el.parentNode.removeChild(el);
2160ed4a
DV
347 }
348 for (var i = 0; i < this.ylabels.length; i++) {
b0c3b730
DV
349 var el = this.ylabels[i];
350 el.parentNode.removeChild(el);
2160ed4a 351 }
ce49c2fa
DV
352 for (var i = 0; i < this.annotations.length; i++) {
353 var el = this.annotations[i];
354 el.parentNode.removeChild(el);
355 }
fbe31dc8
DV
356 this.xlabels = new Array();
357 this.ylabels = new Array();
ce49c2fa 358 this.annotations = new Array();
fbe31dc8
DV
359};
360
361
362DygraphCanvasRenderer.isSupported = function(canvasName) {
363 var canvas = null;
364 try {
21d3323f 365 if (typeof(canvasName) == 'undefined' || canvasName == null)
b0c3b730 366 canvas = document.createElement("canvas");
fbe31dc8 367 else
b0c3b730 368 canvas = canvasName;
fbe31dc8
DV
369 var context = canvas.getContext("2d");
370 }
371 catch (e) {
372 var ie = navigator.appVersion.match(/MSIE (\d\.\d)/);
373 var opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
374 if ((!ie) || (ie[1] < 6) || (opera))
375 return false;
376 return true;
377 }
378 return true;
6a1aa64f 379};
6a1aa64f
DV
380
381/**
382 * Draw an X/Y grid on top of the existing plot
383 */
285a6bda 384DygraphCanvasRenderer.prototype.render = function() {
6a1aa64f
DV
385 // Draw the new X/Y grid
386 var ctx = this.element.getContext("2d");
e7746234
EC
387
388 if (this.options.underlayCallback) {
d9e6fa47 389 this.options.underlayCallback(ctx, this.area, this.layout, this.dygraph_);
e7746234
EC
390 }
391
6a1aa64f
DV
392 if (this.options.drawYGrid) {
393 var ticks = this.layout.yticks;
394 ctx.save();
f2f24402 395 ctx.strokeStyle = this.options.gridLineColor;
6a1aa64f
DV
396 ctx.lineWidth = this.options.axisLineWidth;
397 for (var i = 0; i < ticks.length; i++) {
880a574f
DV
398 // TODO(danvk): allow secondary axes to draw a grid, too.
399 if (ticks[i][0] != 0) continue;
6a1aa64f 400 var x = this.area.x;
9012dd21 401 var y = this.area.y + ticks[i][1] * this.area.h;
6a1aa64f
DV
402 ctx.beginPath();
403 ctx.moveTo(x, y);
404 ctx.lineTo(x + this.area.w, y);
405 ctx.closePath();
406 ctx.stroke();
407 }
408 }
409
410 if (this.options.drawXGrid) {
411 var ticks = this.layout.xticks;
412 ctx.save();
f2f24402 413 ctx.strokeStyle = this.options.gridLineColor;
6a1aa64f
DV
414 ctx.lineWidth = this.options.axisLineWidth;
415 for (var i=0; i<ticks.length; i++) {
880a574f 416 var x = this.area.x + ticks[i][0] * this.area.w;
6a1aa64f
DV
417 var y = this.area.y + this.area.h;
418 ctx.beginPath();
880a574f 419 ctx.moveTo(x, y);
6a1aa64f
DV
420 ctx.lineTo(x, this.area.y);
421 ctx.closePath();
422 ctx.stroke();
423 }
424 }
2ce09b19
DV
425
426 // Do the ordinary rendering, as before
2ce09b19 427 this._renderLineChart();
fbe31dc8 428 this._renderAxis();
ce49c2fa 429 this._renderAnnotations();
fbe31dc8
DV
430};
431
432
433DygraphCanvasRenderer.prototype._renderAxis = function() {
434 if (!this.options.drawXAxis && !this.options.drawYAxis)
435 return;
436
437 var context = this.element.getContext("2d");
438
34fedff8
DV
439 var labelStyle = {
440 "position": "absolute",
441 "fontSize": this.options.axisLabelFontSize + "px",
442 "zIndex": 10,
f474c2a3 443 "color": this.options.axisLabelColor,
34fedff8
DV
444 "width": this.options.axisLabelWidth + "px",
445 "overflow": "hidden"
446 };
447 var makeDiv = function(txt) {
448 var div = document.createElement("div");
449 for (var name in labelStyle) {
85b99f0b
DV
450 if (labelStyle.hasOwnProperty(name)) {
451 div.style[name] = labelStyle[name];
452 }
fbe31dc8 453 }
34fedff8
DV
454 div.appendChild(document.createTextNode(txt));
455 return div;
fbe31dc8
DV
456 };
457
458 // axis lines
459 context.save();
f474c2a3 460 context.strokeStyle = this.options.axisLineColor;
fbe31dc8
DV
461 context.lineWidth = this.options.axisLineWidth;
462
fbe31dc8 463 if (this.options.drawYAxis) {
8b7a0cc3 464 if (this.layout.yticks && this.layout.yticks.length > 0) {
2160ed4a
DV
465 for (var i = 0; i < this.layout.yticks.length; i++) {
466 var tick = this.layout.yticks[i];
fbe31dc8
DV
467 if (typeof(tick) == "function") return;
468 var x = this.area.x;
880a574f
DV
469 var sgn = 1;
470 if (tick[0] == 1) { // right-side y-axis
471 x = this.area.x + this.area.w;
472 sgn = -1;
9012dd21
DV
473 }
474 var y = this.area.y + tick[1] * this.area.h;
fbe31dc8
DV
475 context.beginPath();
476 context.moveTo(x, y);
880a574f 477 context.lineTo(x - sgn * this.options.axisTickSize, y);
fbe31dc8
DV
478 context.closePath();
479 context.stroke();
480
9012dd21 481 var label = makeDiv(tick[2]);
fbe31dc8
DV
482 var top = (y - this.options.axisLabelFontSize / 2);
483 if (top < 0) top = 0;
484
485 if (top + this.options.axisLabelFontSize + 3 > this.height) {
486 label.style.bottom = "0px";
487 } else {
488 label.style.top = top + "px";
489 }
9012dd21
DV
490 if (tick[0] == 0) {
491 label.style.left = "0px";
492 label.style.textAlign = "right";
493 } else if (tick[0] == 1) {
494 label.style.left = (this.area.x + this.area.w +
495 this.options.axisTickSize) + "px";
496 label.style.textAlign = "left";
497 }
fbe31dc8 498 label.style.width = this.options.yAxisLabelWidth + "px";
b0c3b730 499 this.container.appendChild(label);
fbe31dc8 500 this.ylabels.push(label);
2160ed4a 501 }
fbe31dc8
DV
502
503 // The lowest tick on the y-axis often overlaps with the leftmost
504 // tick on the x-axis. Shift the bottom tick up a little bit to
505 // compensate if necessary.
506 var bottomTick = this.ylabels[0];
507 var fontSize = this.options.axisLabelFontSize;
508 var bottom = parseInt(bottomTick.style.top) + fontSize;
509 if (bottom > this.height - fontSize) {
510 bottomTick.style.top = (parseInt(bottomTick.style.top) -
511 fontSize / 2) + "px";
512 }
513 }
514
515 context.beginPath();
516 context.moveTo(this.area.x, this.area.y);
517 context.lineTo(this.area.x, this.area.y + this.area.h);
518 context.closePath();
519 context.stroke();
c1dbeb10
DV
520
521 if (this.dygraph_.numAxes() == 2) {
522 context.beginPath();
523 context.moveTo(this.area.x + this.area.w, this.area.y);
524 context.lineTo(this.area.x + this.area.w, this.area.y + this.area.h);
525 context.closePath();
526 context.stroke();
527 }
fbe31dc8
DV
528 }
529
530 if (this.options.drawXAxis) {
531 if (this.layout.xticks) {
2160ed4a
DV
532 for (var i = 0; i < this.layout.xticks.length; i++) {
533 var tick = this.layout.xticks[i];
fbe31dc8
DV
534 if (typeof(dataset) == "function") return;
535
536 var x = this.area.x + tick[0] * this.area.w;
537 var y = this.area.y + this.area.h;
538 context.beginPath();
539 context.moveTo(x, y);
540 context.lineTo(x, y + this.options.axisTickSize);
541 context.closePath();
542 context.stroke();
543
34fedff8 544 var label = makeDiv(tick[1]);
fbe31dc8
DV
545 label.style.textAlign = "center";
546 label.style.bottom = "0px";
547
548 var left = (x - this.options.axisLabelWidth/2);
549 if (left + this.options.axisLabelWidth > this.width) {
550 left = this.width - this.options.xAxisLabelWidth;
551 label.style.textAlign = "right";
552 }
553 if (left < 0) {
554 left = 0;
555 label.style.textAlign = "left";
556 }
557
558 label.style.left = left + "px";
559 label.style.width = this.options.xAxisLabelWidth + "px";
b0c3b730 560 this.container.appendChild(label);
fbe31dc8 561 this.xlabels.push(label);
2160ed4a 562 }
fbe31dc8
DV
563 }
564
565 context.beginPath();
566 context.moveTo(this.area.x, this.area.y + this.area.h);
567 context.lineTo(this.area.x + this.area.w, this.area.y + this.area.h);
568 context.closePath();
569 context.stroke();
570 }
571
572 context.restore();
6a1aa64f
DV
573};
574
fbe31dc8 575
ce49c2fa
DV
576DygraphCanvasRenderer.prototype._renderAnnotations = function() {
577 var annotationStyle = {
578 "position": "absolute",
579 "fontSize": this.options.axisLabelFontSize + "px",
580 "zIndex": 10,
3bf2fa91 581 "overflow": "hidden"
ce49c2fa
DV
582 };
583
ab5e5c75
DV
584 var bindEvt = function(eventName, classEventName, p, self) {
585 return function(e) {
586 var a = p.annotation;
587 if (a.hasOwnProperty(eventName)) {
588 a[eventName](a, p, self.dygraph_, e);
589 } else if (self.dygraph_.attr_(classEventName)) {
590 self.dygraph_.attr_(classEventName)(a, p, self.dygraph_,e );
591 }
592 };
593 }
594
ce49c2fa
DV
595 // Get a list of point with annotations.
596 var points = this.layout.annotated_points;
597 for (var i = 0; i < points.length; i++) {
598 var p = points[i];
e6d53148
DV
599 if (p.canvasx < this.area.x || p.canvasx > this.area.x + this.area.w) {
600 continue;
601 }
602
ce5e8d36
DV
603 var a = p.annotation;
604 var tick_height = 6;
605 if (a.hasOwnProperty("tickHeight")) {
606 tick_height = a.tickHeight;
9a40897e
DV
607 }
608
ce49c2fa
DV
609 var div = document.createElement("div");
610 for (var name in annotationStyle) {
611 if (annotationStyle.hasOwnProperty(name)) {
612 div.style[name] = annotationStyle[name];
613 }
614 }
ce5e8d36
DV
615 if (!a.hasOwnProperty('icon')) {
616 div.className = "dygraphDefaultAnnotation";
617 }
618 if (a.hasOwnProperty('cssClass')) {
619 div.className += " " + a.cssClass;
620 }
621
a5ad69cc
DV
622 var width = a.hasOwnProperty('width') ? a.width : 16;
623 var height = a.hasOwnProperty('height') ? a.height : 16;
ce5e8d36
DV
624 if (a.hasOwnProperty('icon')) {
625 var img = document.createElement("img");
626 img.src = a.icon;
33030f33
DV
627 img.width = width;
628 img.height = height;
ce5e8d36
DV
629 div.appendChild(img);
630 } else if (p.annotation.hasOwnProperty('shortText')) {
631 div.appendChild(document.createTextNode(p.annotation.shortText));
5c528fa2 632 }
ce5e8d36 633 div.style.left = (p.canvasx - width / 2) + "px";
d14b9eed
DV
634 if (a.attachAtBottom) {
635 div.style.top = (this.area.h - height - tick_height) + "px";
636 } else {
637 div.style.top = (p.canvasy - height - tick_height) + "px";
638 }
ce5e8d36
DV
639 div.style.width = width + "px";
640 div.style.height = height + "px";
ce49c2fa
DV
641 div.title = p.annotation.text;
642 div.style.color = this.colors[p.name];
643 div.style.borderColor = this.colors[p.name];
e6d53148 644 a.div = div;
ab5e5c75 645
9a40897e
DV
646 Dygraph.addEvent(div, 'click',
647 bindEvt('clickHandler', 'annotationClickHandler', p, this));
648 Dygraph.addEvent(div, 'mouseover',
649 bindEvt('mouseOverHandler', 'annotationMouseOverHandler', p, this));
650 Dygraph.addEvent(div, 'mouseout',
651 bindEvt('mouseOutHandler', 'annotationMouseOutHandler', p, this));
652 Dygraph.addEvent(div, 'dblclick',
653 bindEvt('dblClickHandler', 'annotationDblClickHandler', p, this));
ab5e5c75 654
ce49c2fa
DV
655 this.container.appendChild(div);
656 this.annotations.push(div);
9a40897e
DV
657
658 var ctx = this.element.getContext("2d");
659 ctx.strokeStyle = this.colors[p.name];
660 ctx.beginPath();
d14b9eed
DV
661 if (!a.attachAtBottom) {
662 ctx.moveTo(p.canvasx, p.canvasy);
663 ctx.lineTo(p.canvasx, p.canvasy - 2 - tick_height);
664 } else {
665 ctx.moveTo(p.canvasx, this.area.h);
666 ctx.lineTo(p.canvasx, this.area.h - 2 - tick_height);
667 }
9a40897e
DV
668 ctx.closePath();
669 ctx.stroke();
ce49c2fa
DV
670 }
671};
672
673
6a1aa64f
DV
674/**
675 * Overrides the CanvasRenderer method to draw error bars
676 */
285a6bda 677DygraphCanvasRenderer.prototype._renderLineChart = function() {
6a1aa64f
DV
678 var context = this.element.getContext("2d");
679 var colorCount = this.options.colorScheme.length;
680 var colorScheme = this.options.colorScheme;
43af96e7 681 var fillAlpha = this.options.fillAlpha;
6a1aa64f 682 var errorBars = this.layout.options.errorBars;
5954ef32 683 var fillGraph = this.layout.options.fillGraph;
354e15ab 684 var stackedGraph = this.layout.options.stackedGraph;
afdc483f 685 var stepPlot = this.layout.options.stepPlot;
21d3323f
DV
686
687 var setNames = [];
ca43052c 688 for (var name in this.layout.datasets) {
85b99f0b
DV
689 if (this.layout.datasets.hasOwnProperty(name)) {
690 setNames.push(name);
691 }
ca43052c 692 }
21d3323f 693 var setCount = setNames.length;
6a1aa64f 694
f032c51d
AV
695 this.colors = {}
696 for (var i = 0; i < setCount; i++) {
697 this.colors[setNames[i]] = colorScheme[i % colorCount];
698 }
699
ff00d3e2
DV
700 // Update Points
701 // TODO(danvk): here
2160ed4a
DV
702 for (var i = 0; i < this.layout.points.length; i++) {
703 var point = this.layout.points[i];
6a1aa64f
DV
704 point.canvasx = this.area.w * point.x + this.area.x;
705 point.canvasy = this.area.h * point.y + this.area.y;
706 }
6a1aa64f
DV
707
708 // create paths
9317362d 709 var isOK = function(x) { return x && !isNaN(x); };
6a1aa64f 710
80aaae18
DV
711 var ctx = context;
712 if (errorBars) {
6a834bbb
DV
713 if (fillGraph) {
714 this.dygraph_.warn("Can't use fillGraph option with error bars");
715 }
716
6a1aa64f
DV
717 for (var i = 0; i < setCount; i++) {
718 var setName = setNames[i];
ea4942ed
DV
719 var axis = this.layout.options.yAxes[
720 this.layout.options.seriesToAxisMap[setName]];
f032c51d 721 var color = this.colors[setName];
6a1aa64f
DV
722
723 // setup graphics context
80aaae18 724 ctx.save();
56623f3b 725 var prevX = NaN;
afdc483f 726 var prevY = NaN;
6a1aa64f 727 var prevYs = [-1, -1];
ea4942ed 728 var yscale = axis.yscale;
f474c2a3
DV
729 // should be same color as the lines but only 15% opaque.
730 var rgb = new RGBColor(color);
43af96e7
NK
731 var err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
732 fillAlpha + ')';
f474c2a3 733 ctx.fillStyle = err_color;
05c9d0c4
DV
734 ctx.beginPath();
735 for (var j = 0; j < this.layout.points.length; j++) {
736 var point = this.layout.points[j];
6a1aa64f 737 if (point.name == setName) {
5954ef32 738 if (!isOK(point.y)) {
56623f3b 739 prevX = NaN;
ae85914a 740 continue;
5011e7a1 741 }
ce49c2fa 742
ff00d3e2 743 // TODO(danvk): here
afdc483f
NN
744 if (stepPlot) {
745 var newYs = [ prevY - point.errorPlus * yscale,
47600757 746 prevY + point.errorMinus * yscale ];
afdc483f
NN
747 prevY = point.y;
748 } else {
749 var newYs = [ point.y - point.errorPlus * yscale,
47600757 750 point.y + point.errorMinus * yscale ];
afdc483f 751 }
6a1aa64f
DV
752 newYs[0] = this.area.h * newYs[0] + this.area.y;
753 newYs[1] = this.area.h * newYs[1] + this.area.y;
56623f3b 754 if (!isNaN(prevX)) {
afdc483f 755 if (stepPlot) {
47600757 756 ctx.moveTo(prevX, newYs[0]);
afdc483f 757 } else {
47600757 758 ctx.moveTo(prevX, prevYs[0]);
afdc483f 759 }
5954ef32
DV
760 ctx.lineTo(point.canvasx, newYs[0]);
761 ctx.lineTo(point.canvasx, newYs[1]);
afdc483f 762 if (stepPlot) {
47600757 763 ctx.lineTo(prevX, newYs[1]);
afdc483f 764 } else {
47600757 765 ctx.lineTo(prevX, prevYs[1]);
afdc483f 766 }
5954ef32
DV
767 ctx.closePath();
768 }
354e15ab 769 prevYs = newYs;
5954ef32
DV
770 prevX = point.canvasx;
771 }
772 }
773 ctx.fill();
774 }
775 } else if (fillGraph) {
354e15ab
DE
776 var baseline = [] // for stacked graphs: baseline for filling
777
778 // process sets in reverse order (needed for stacked graphs)
779 for (var i = setCount - 1; i >= 0; i--) {
5954ef32 780 var setName = setNames[i];
f032c51d 781 var color = this.colors[setName];
ea4942ed
DV
782 var axis = this.layout.options.yAxes[
783 this.layout.options.seriesToAxisMap[setName]];
784 var axisY = 1.0 + axis.minyval * axis.yscale;
785 if (axisY < 0.0) axisY = 0.0;
786 else if (axisY > 1.0) axisY = 1.0;
787 axisY = this.area.h * axisY + this.area.y;
5954ef32
DV
788
789 // setup graphics context
790 ctx.save();
56623f3b 791 var prevX = NaN;
5954ef32 792 var prevYs = [-1, -1];
ea4942ed 793 var yscale = axis.yscale;
5954ef32
DV
794 // should be same color as the lines but only 15% opaque.
795 var rgb = new RGBColor(color);
43af96e7
NK
796 var err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
797 fillAlpha + ')';
5954ef32
DV
798 ctx.fillStyle = err_color;
799 ctx.beginPath();
800 for (var j = 0; j < this.layout.points.length; j++) {
801 var point = this.layout.points[j];
5954ef32
DV
802 if (point.name == setName) {
803 if (!isOK(point.y)) {
56623f3b 804 prevX = NaN;
5954ef32
DV
805 continue;
806 }
354e15ab
DE
807 var newYs;
808 if (stackedGraph) {
809 lastY = baseline[point.canvasx];
810 if (lastY === undefined) lastY = axisY;
811 baseline[point.canvasx] = point.canvasy;
812 newYs = [ point.canvasy, lastY ];
813 } else {
814 newYs = [ point.canvasy, axisY ];
815 }
56623f3b 816 if (!isNaN(prevX)) {
05c9d0c4 817 ctx.moveTo(prevX, prevYs[0]);
afdc483f 818 if (stepPlot) {
47600757 819 ctx.lineTo(point.canvasx, prevYs[0]);
afdc483f 820 } else {
47600757 821 ctx.lineTo(point.canvasx, newYs[0]);
afdc483f 822 }
05c9d0c4
DV
823 ctx.lineTo(point.canvasx, newYs[1]);
824 ctx.lineTo(prevX, prevYs[1]);
825 ctx.closePath();
6a1aa64f 826 }
354e15ab 827 prevYs = newYs;
6a1aa64f
DV
828 prevX = point.canvasx;
829 }
05c9d0c4 830 }
6a1aa64f
DV
831 ctx.fill();
832 }
80aaae18
DV
833 }
834
835 for (var i = 0; i < setCount; i++) {
836 var setName = setNames[i];
f032c51d 837 var color = this.colors[setName];
227b93cc 838 var strokeWidth = this.dygraph_.attr_("strokeWidth", setName);
80aaae18
DV
839
840 // setup graphics context
841 context.save();
842 var point = this.layout.points[0];
227b93cc 843 var pointSize = this.dygraph_.attr_("pointSize", setName);
80aaae18 844 var prevX = null, prevY = null;
227b93cc 845 var drawPoints = this.dygraph_.attr_("drawPoints", setName);
80aaae18
DV
846 var points = this.layout.points;
847 for (var j = 0; j < points.length; j++) {
848 var point = points[j];
849 if (point.name == setName) {
850 if (!isOK(point.canvasy)) {
5d13ef68 851 if (stepPlot && prevX != null) {
0599d13b
NN
852 // Draw a horizontal line to the start of the missing data
853 ctx.beginPath();
854 ctx.strokeStyle = color;
855 ctx.lineWidth = this.options.strokeWidth;
856 ctx.moveTo(prevX, prevY);
857 ctx.lineTo(point.canvasx, prevY);
858 ctx.stroke();
859 }
80aaae18
DV
860 // this will make us move to the next point, not draw a line to it.
861 prevX = prevY = null;
862 } else {
863 // A point is "isolated" if it is non-null but both the previous
864 // and next points are null.
865 var isIsolated = (!prevX && (j == points.length - 1 ||
866 !isOK(points[j+1].canvasy)));
867
868 if (!prevX) {
869 prevX = point.canvasx;
870 prevY = point.canvasy;
871 } else {
46dde5f9
DV
872 // TODO(danvk): figure out why this conditional is necessary.
873 if (strokeWidth) {
874 ctx.beginPath();
875 ctx.strokeStyle = color;
876 ctx.lineWidth = strokeWidth;
877 ctx.moveTo(prevX, prevY);
878 if (stepPlot) {
879 ctx.lineTo(point.canvasx, prevY);
880 }
881 prevX = point.canvasx;
882 prevY = point.canvasy;
883 ctx.lineTo(prevX, prevY);
884 ctx.stroke();
afdc483f 885 }
80aaae18
DV
886 }
887
888 if (drawPoints || isIsolated) {
889 ctx.beginPath();
890 ctx.fillStyle = color;
7bf6a9fe
DV
891 ctx.arc(point.canvasx, point.canvasy, pointSize,
892 0, 2 * Math.PI, false);
80aaae18
DV
893 ctx.fill();
894 }
895 }
896 }
897 }
898 }
6a1aa64f 899
6a1aa64f
DV
900 context.restore();
901};