Fix Issue 60: Add tests for one data point and zero data points
[dygraphs.git] / dygraph-canvas.js
CommitLineData
88e95c46
DV
1/**
2 * @license
3 * Copyright 2006 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
5 */
6a1aa64f
DV
6
7/**
74a5af31
DV
8 * @fileoverview Based on PlotKit.CanvasRenderer, but modified to meet the
9 * needs of dygraphs.
10 *
3df0ccf0 11 * In particular, support for:
0abfbd7e 12 * - grid overlays
3df0ccf0
DV
13 * - error bars
14 * - dygraphs attribute system
6a1aa64f
DV
15 */
16
6a1aa64f 17/**
423f5ed3
DV
18 * The DygraphCanvasRenderer class does the actual rendering of the chart onto
19 * a canvas. It's based on PlotKit.CanvasRenderer.
6a1aa64f 20 * @param {Object} element The canvas to attach to
2cf95fff
RK
21 * @param {Object} elementContext The 2d context of the canvas (injected so it
22 * can be mocked for testing.)
285a6bda 23 * @param {Layout} layout The DygraphLayout object for this graph.
74a5af31 24 * @constructor
6a1aa64f 25 */
c0f54d4f
DV
26
27"use strict";
28
29var DygraphCanvasRenderer = function(dygraph, element, elementContext, layout) {
9317362d 30 this.dygraph_ = dygraph;
fbe31dc8 31
fbe31dc8 32 this.layout = layout;
b0c3b730 33 this.element = element;
2cf95fff 34 this.elementContext = elementContext;
fbe31dc8
DV
35 this.container = this.element.parentNode;
36
fbe31dc8
DV
37 this.height = this.element.height;
38 this.width = this.element.width;
39
40 // --- check whether everything is ok before we return
41 if (!this.isIE && !(DygraphCanvasRenderer.isSupported(this.element)))
42 throw "Canvas is not supported.";
43
44 // internal state
45 this.xlabels = new Array();
46 this.ylabels = new Array();
ce49c2fa 47 this.annotations = new Array();
ad1798c2 48 this.chartLabels = {};
fbe31dc8 49
70be5ed1 50 this.area = layout.getPlotArea();
423f5ed3
DV
51 this.container.style.position = "relative";
52 this.container.style.width = this.width + "px";
53
54 // Set up a clipping area for the canvas (and the interaction canvas).
55 // This ensures that we don't overdraw.
920208fb
PF
56 if (this.dygraph_.isUsingExcanvas_) {
57 this._createIEClipArea();
58 } else {
59 var ctx = this.dygraph_.canvas_ctx_;
60 ctx.beginPath();
61 ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h);
62 ctx.clip();
63
64 ctx = this.dygraph_.hidden_ctx_;
65 ctx.beginPath();
66 ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h);
67 ctx.clip();
68 }
423f5ed3
DV
69};
70
71DygraphCanvasRenderer.prototype.attr_ = function(x) {
72 return this.dygraph_.attr_(x);
73};
74
fbe31dc8
DV
75DygraphCanvasRenderer.prototype.clear = function() {
76 if (this.isIE) {
77 // VML takes a while to start up, so we just poll every this.IEDelay
78 try {
79 if (this.clearDelay) {
80 this.clearDelay.cancel();
81 this.clearDelay = null;
82 }
2cf95fff 83 var context = this.elementContext;
fbe31dc8
DV
84 }
85 catch (e) {
76171648 86 // TODO(danvk): this is broken, since MochiKit.Async is gone.
fbe31dc8
DV
87 this.clearDelay = MochiKit.Async.wait(this.IEDelay);
88 this.clearDelay.addCallback(bind(this.clear, this));
89 return;
90 }
91 }
92
2cf95fff 93 var context = this.elementContext;
fbe31dc8
DV
94 context.clearRect(0, 0, this.width, this.height);
95
2160ed4a 96 for (var i = 0; i < this.xlabels.length; i++) {
b0c3b730 97 var el = this.xlabels[i];
b304aaec 98 if (el.parentNode) el.parentNode.removeChild(el);
2160ed4a
DV
99 }
100 for (var i = 0; i < this.ylabels.length; i++) {
b0c3b730 101 var el = this.ylabels[i];
b304aaec 102 if (el.parentNode) el.parentNode.removeChild(el);
2160ed4a 103 }
ce49c2fa
DV
104 for (var i = 0; i < this.annotations.length; i++) {
105 var el = this.annotations[i];
b304aaec 106 if (el.parentNode) el.parentNode.removeChild(el);
ce49c2fa 107 }
ad1798c2
DV
108 for (var k in this.chartLabels) {
109 if (!this.chartLabels.hasOwnProperty(k)) continue;
110 var el = this.chartLabels[k];
111 if (el.parentNode) el.parentNode.removeChild(el);
112 }
fbe31dc8
DV
113 this.xlabels = new Array();
114 this.ylabels = new Array();
ce49c2fa 115 this.annotations = new Array();
ad1798c2 116 this.chartLabels = {};
fbe31dc8
DV
117};
118
119
120DygraphCanvasRenderer.isSupported = function(canvasName) {
121 var canvas = null;
122 try {
21d3323f 123 if (typeof(canvasName) == 'undefined' || canvasName == null)
b0c3b730 124 canvas = document.createElement("canvas");
fbe31dc8 125 else
b0c3b730 126 canvas = canvasName;
fbe31dc8
DV
127 var context = canvas.getContext("2d");
128 }
129 catch (e) {
130 var ie = navigator.appVersion.match(/MSIE (\d\.\d)/);
131 var opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
132 if ((!ie) || (ie[1] < 6) || (opera))
133 return false;
134 return true;
135 }
136 return true;
6a1aa64f 137};
6a1aa64f
DV
138
139/**
600d841a
DV
140 * @param { [String] } colors Array of color strings. Should have one entry for
141 * each series to be rendered.
142 */
143DygraphCanvasRenderer.prototype.setColors = function(colors) {
144 this.colorScheme_ = colors;
145};
146
147/**
6a1aa64f
DV
148 * Draw an X/Y grid on top of the existing plot
149 */
285a6bda 150DygraphCanvasRenderer.prototype.render = function() {
528ce7e5
DV
151 // Draw the new X/Y grid. Lines appear crisper when pixels are rounded to
152 // half-integers. This prevents them from drawing in two rows/cols.
2cf95fff 153 var ctx = this.elementContext;
528ce7e5
DV
154 function halfUp(x){return Math.round(x)+0.5};
155 function halfDown(y){return Math.round(y)-0.5};
e7746234 156
423f5ed3 157 if (this.attr_('underlayCallback')) {
1e41bd2d
DV
158 // NOTE: we pass the dygraph object to this callback twice to avoid breaking
159 // users who expect a deprecated form of this callback.
423f5ed3 160 this.attr_('underlayCallback')(ctx, this.area, this.dygraph_, this.dygraph_);
e7746234
EC
161 }
162
423f5ed3 163 if (this.attr_('drawYGrid')) {
6a1aa64f 164 var ticks = this.layout.yticks;
bbba718a 165 // TODO(konigsberg): I don't think these calls to save() have a corresponding restore().
6a1aa64f 166 ctx.save();
423f5ed3 167 ctx.strokeStyle = this.attr_('gridLineColor');
990d6a35 168 ctx.lineWidth = this.attr_('gridLineWidth');
6a1aa64f 169 for (var i = 0; i < ticks.length; i++) {
880a574f
DV
170 // TODO(danvk): allow secondary axes to draw a grid, too.
171 if (ticks[i][0] != 0) continue;
528ce7e5
DV
172 var x = halfUp(this.area.x);
173 var y = halfDown(this.area.y + ticks[i][1] * this.area.h);
6a1aa64f
DV
174 ctx.beginPath();
175 ctx.moveTo(x, y);
176 ctx.lineTo(x + this.area.w, y);
177 ctx.closePath();
178 ctx.stroke();
179 }
180 }
181
423f5ed3 182 if (this.attr_('drawXGrid')) {
6a1aa64f
DV
183 var ticks = this.layout.xticks;
184 ctx.save();
423f5ed3 185 ctx.strokeStyle = this.attr_('gridLineColor');
990d6a35 186 ctx.lineWidth = this.attr_('gridLineWidth');
6a1aa64f 187 for (var i=0; i<ticks.length; i++) {
528ce7e5
DV
188 var x = halfUp(this.area.x + ticks[i][0] * this.area.w);
189 var y = halfDown(this.area.y + this.area.h);
6a1aa64f 190 ctx.beginPath();
880a574f 191 ctx.moveTo(x, y);
6a1aa64f
DV
192 ctx.lineTo(x, this.area.y);
193 ctx.closePath();
194 ctx.stroke();
195 }
196 }
2ce09b19
DV
197
198 // Do the ordinary rendering, as before
2ce09b19 199 this._renderLineChart();
fbe31dc8 200 this._renderAxis();
ccd9d7c2 201 this._renderChartLabels();
ce49c2fa 202 this._renderAnnotations();
fbe31dc8
DV
203};
204
920208fb
PF
205DygraphCanvasRenderer.prototype._createIEClipArea = function() {
206 var className = 'dygraph-clip-div';
207 var graphDiv = this.dygraph_.graphDiv;
208
209 // Remove old clip divs.
210 for (var i = graphDiv.childNodes.length-1; i >= 0; i--) {
211 if (graphDiv.childNodes[i].className == className) {
212 graphDiv.removeChild(graphDiv.childNodes[i]);
213 }
214 }
215
216 // Determine background color to give clip divs.
217 var backgroundColor = document.bgColor;
218 var element = this.dygraph_.graphDiv;
219 while (element != document) {
220 var bgcolor = element.currentStyle.backgroundColor;
221 if (bgcolor && bgcolor != 'transparent') {
222 backgroundColor = bgcolor;
223 break;
224 }
225 element = element.parentNode;
226 }
227
228 function createClipDiv(area) {
229 if (area.w == 0 || area.h == 0) {
230 return;
231 }
232 var elem = document.createElement('div');
233 elem.className = className;
234 elem.style.backgroundColor = backgroundColor;
235 elem.style.position = 'absolute';
236 elem.style.left = area.x + 'px';
237 elem.style.top = area.y + 'px';
238 elem.style.width = area.w + 'px';
239 elem.style.height = area.h + 'px';
240 graphDiv.appendChild(elem);
241 }
242
243 var plotArea = this.area;
244 // Left side
245 createClipDiv({x:0, y:0, w:plotArea.x, h:this.height});
246 // Top
247 createClipDiv({x:plotArea.x, y:0, w:this.width-plotArea.x, h:plotArea.y});
248 // Right side
249 createClipDiv({x:plotArea.x+plotArea.w, y:0, w:this.width-plotArea.x-plotArea.w, h:this.height});
250 // Bottom
251 createClipDiv({x:plotArea.x, y:plotArea.y+plotArea.h, w:this.width-plotArea.x, h:this.height-plotArea.h-plotArea.y});
252}
fbe31dc8
DV
253
254DygraphCanvasRenderer.prototype._renderAxis = function() {
423f5ed3 255 if (!this.attr_('drawXAxis') && !this.attr_('drawYAxis')) return;
fbe31dc8 256
528ce7e5
DV
257 // Round pixels to half-integer boundaries for crisper drawing.
258 function halfUp(x){return Math.round(x)+0.5};
259 function halfDown(y){return Math.round(y)-0.5};
260
2cf95fff 261 var context = this.elementContext;
fbe31dc8 262
34fedff8 263 var labelStyle = {
423f5ed3
DV
264 position: "absolute",
265 fontSize: this.attr_('axisLabelFontSize') + "px",
266 zIndex: 10,
267 color: this.attr_('axisLabelColor'),
268 width: this.attr_('axisLabelWidth') + "px",
74a5af31 269 // height: this.attr_('axisLabelFontSize') + 2 + "px",
ccd9d7c2 270 lineHeight: "normal", // Something other than "normal" line-height screws up label positioning.
423f5ed3 271 overflow: "hidden"
34fedff8 272 };
48e614ac 273 var makeDiv = function(txt, axis, prec_axis) {
34fedff8
DV
274 var div = document.createElement("div");
275 for (var name in labelStyle) {
85b99f0b
DV
276 if (labelStyle.hasOwnProperty(name)) {
277 div.style[name] = labelStyle[name];
278 }
fbe31dc8 279 }
ba451526 280 var inner_div = document.createElement("div");
48e614ac
DV
281 inner_div.className = 'dygraph-axis-label' +
282 ' dygraph-axis-label-' + axis +
283 (prec_axis ? ' dygraph-axis-label-' + prec_axis : '');
ba451526
DV
284 inner_div.appendChild(document.createTextNode(txt));
285 div.appendChild(inner_div);
34fedff8 286 return div;
fbe31dc8
DV
287 };
288
289 // axis lines
290 context.save();
423f5ed3
DV
291 context.strokeStyle = this.attr_('axisLineColor');
292 context.lineWidth = this.attr_('axisLineWidth');
fbe31dc8 293
423f5ed3 294 if (this.attr_('drawYAxis')) {
8b7a0cc3 295 if (this.layout.yticks && this.layout.yticks.length > 0) {
48e614ac 296 var num_axes = this.dygraph_.numAxes();
2160ed4a
DV
297 for (var i = 0; i < this.layout.yticks.length; i++) {
298 var tick = this.layout.yticks[i];
fbe31dc8
DV
299 if (typeof(tick) == "function") return;
300 var x = this.area.x;
880a574f 301 var sgn = 1;
48e614ac 302 var prec_axis = 'y1';
880a574f
DV
303 if (tick[0] == 1) { // right-side y-axis
304 x = this.area.x + this.area.w;
305 sgn = -1;
48e614ac 306 prec_axis = 'y2';
9012dd21
DV
307 }
308 var y = this.area.y + tick[1] * this.area.h;
920208fb
PF
309
310 /* Tick marks are currently clipped, so don't bother drawing them.
fbe31dc8 311 context.beginPath();
528ce7e5 312 context.moveTo(halfUp(x), halfDown(y));
0e23cfc6 313 context.lineTo(halfUp(x - sgn * this.attr_('axisTickSize')), halfDown(y));
fbe31dc8
DV
314 context.closePath();
315 context.stroke();
920208fb 316 */
fbe31dc8 317
48e614ac 318 var label = makeDiv(tick[2], 'y', num_axes == 2 ? prec_axis : null);
423f5ed3 319 var top = (y - this.attr_('axisLabelFontSize') / 2);
fbe31dc8
DV
320 if (top < 0) top = 0;
321
423f5ed3 322 if (top + this.attr_('axisLabelFontSize') + 3 > this.height) {
fbe31dc8
DV
323 label.style.bottom = "0px";
324 } else {
325 label.style.top = top + "px";
326 }
9012dd21 327 if (tick[0] == 0) {
423f5ed3 328 label.style.left = (this.area.x - this.attr_('yAxisLabelWidth') - this.attr_('axisTickSize')) + "px";
9012dd21
DV
329 label.style.textAlign = "right";
330 } else if (tick[0] == 1) {
331 label.style.left = (this.area.x + this.area.w +
423f5ed3 332 this.attr_('axisTickSize')) + "px";
9012dd21
DV
333 label.style.textAlign = "left";
334 }
423f5ed3 335 label.style.width = this.attr_('yAxisLabelWidth') + "px";
b0c3b730 336 this.container.appendChild(label);
fbe31dc8 337 this.ylabels.push(label);
2160ed4a 338 }
fbe31dc8
DV
339
340 // The lowest tick on the y-axis often overlaps with the leftmost
341 // tick on the x-axis. Shift the bottom tick up a little bit to
342 // compensate if necessary.
343 var bottomTick = this.ylabels[0];
423f5ed3 344 var fontSize = this.attr_('axisLabelFontSize');
fbe31dc8
DV
345 var bottom = parseInt(bottomTick.style.top) + fontSize;
346 if (bottom > this.height - fontSize) {
347 bottomTick.style.top = (parseInt(bottomTick.style.top) -
348 fontSize / 2) + "px";
349 }
350 }
351
528ce7e5 352 // draw a vertical line on the left to separate the chart from the labels.
fbe31dc8 353 context.beginPath();
528ce7e5
DV
354 context.moveTo(halfUp(this.area.x), halfDown(this.area.y));
355 context.lineTo(halfUp(this.area.x), halfDown(this.area.y + this.area.h));
fbe31dc8
DV
356 context.closePath();
357 context.stroke();
c1dbeb10 358
528ce7e5 359 // if there's a secondary y-axis, draw a vertical line for that, too.
c1dbeb10
DV
360 if (this.dygraph_.numAxes() == 2) {
361 context.beginPath();
528ce7e5
DV
362 context.moveTo(halfDown(this.area.x + this.area.w), halfDown(this.area.y));
363 context.lineTo(halfDown(this.area.x + this.area.w), halfDown(this.area.y + this.area.h));
c1dbeb10
DV
364 context.closePath();
365 context.stroke();
366 }
fbe31dc8
DV
367 }
368
423f5ed3 369 if (this.attr_('drawXAxis')) {
fbe31dc8 370 if (this.layout.xticks) {
2160ed4a
DV
371 for (var i = 0; i < this.layout.xticks.length; i++) {
372 var tick = this.layout.xticks[i];
fbe31dc8
DV
373 if (typeof(dataset) == "function") return;
374
375 var x = this.area.x + tick[0] * this.area.w;
376 var y = this.area.y + this.area.h;
920208fb
PF
377
378 /* Tick marks are currently clipped, so don't bother drawing them.
fbe31dc8 379 context.beginPath();
528ce7e5 380 context.moveTo(halfUp(x), halfDown(y));
423f5ed3 381 context.lineTo(halfUp(x), halfDown(y + this.attr_('axisTickSize')));
fbe31dc8
DV
382 context.closePath();
383 context.stroke();
920208fb 384 */
fbe31dc8 385
ba451526 386 var label = makeDiv(tick[1], 'x');
fbe31dc8 387 label.style.textAlign = "center";
423f5ed3 388 label.style.top = (y + this.attr_('axisTickSize')) + 'px';
fbe31dc8 389
423f5ed3
DV
390 var left = (x - this.attr_('axisLabelWidth')/2);
391 if (left + this.attr_('axisLabelWidth') > this.width) {
392 left = this.width - this.attr_('xAxisLabelWidth');
fbe31dc8
DV
393 label.style.textAlign = "right";
394 }
395 if (left < 0) {
396 left = 0;
397 label.style.textAlign = "left";
398 }
399
400 label.style.left = left + "px";
423f5ed3 401 label.style.width = this.attr_('xAxisLabelWidth') + "px";
b0c3b730 402 this.container.appendChild(label);
fbe31dc8 403 this.xlabels.push(label);
2160ed4a 404 }
fbe31dc8
DV
405 }
406
407 context.beginPath();
528ce7e5
DV
408 context.moveTo(halfUp(this.area.x), halfDown(this.area.y + this.area.h));
409 context.lineTo(halfUp(this.area.x + this.area.w), halfDown(this.area.y + this.area.h));
fbe31dc8
DV
410 context.closePath();
411 context.stroke();
412 }
413
414 context.restore();
6a1aa64f
DV
415};
416
fbe31dc8 417
ad1798c2
DV
418DygraphCanvasRenderer.prototype._renderChartLabels = function() {
419 // Generate divs for the chart title, xlabel and ylabel.
420 // Space for these divs has already been taken away from the charting area in
421 // the DygraphCanvasRenderer constructor.
422 if (this.attr_('title')) {
423 var div = document.createElement("div");
424 div.style.position = 'absolute';
425 div.style.top = '0px';
426 div.style.left = this.area.x + 'px';
427 div.style.width = this.area.w + 'px';
428 div.style.height = this.attr_('titleHeight') + 'px';
429 div.style.textAlign = 'center';
b4202b3d 430 div.style.fontSize = (this.attr_('titleHeight') - 8) + 'px';
ad1798c2 431 div.style.fontWeight = 'bold';
ca49434a
DV
432 var class_div = document.createElement("div");
433 class_div.className = 'dygraph-label dygraph-title';
434 class_div.innerHTML = this.attr_('title');
435 div.appendChild(class_div);
ad1798c2
DV
436 this.container.appendChild(div);
437 this.chartLabels.title = div;
438 }
439
440 if (this.attr_('xlabel')) {
441 var div = document.createElement("div");
442 div.style.position = 'absolute';
443 div.style.bottom = 0; // TODO(danvk): this is lazy. Calculate style.top.
444 div.style.left = this.area.x + 'px';
445 div.style.width = this.area.w + 'px';
446 div.style.height = this.attr_('xLabelHeight') + 'px';
447 div.style.textAlign = 'center';
86cce9e8 448 div.style.fontSize = (this.attr_('xLabelHeight') - 2) + 'px';
ca49434a
DV
449
450 var class_div = document.createElement("div");
451 class_div.className = 'dygraph-label dygraph-xlabel';
452 class_div.innerHTML = this.attr_('xlabel');
453 div.appendChild(class_div);
ad1798c2
DV
454 this.container.appendChild(div);
455 this.chartLabels.xlabel = div;
456 }
457
458 if (this.attr_('ylabel')) {
459 var box = {
460 left: 0,
461 top: this.area.y,
462 width: this.attr_('yLabelWidth'),
463 height: this.area.h
464 };
ca49434a 465 // TODO(danvk): is this outer div actually necessary?
ad1798c2
DV
466 var div = document.createElement("div");
467 div.style.position = 'absolute';
468 div.style.left = box.left;
469 div.style.top = box.top + 'px';
470 div.style.width = box.width + 'px';
471 div.style.height = box.height + 'px';
86cce9e8 472 div.style.fontSize = (this.attr_('yLabelWidth') - 2) + 'px';
ad1798c2
DV
473
474 var inner_div = document.createElement("div");
475 inner_div.style.position = 'absolute';
ad1798c2
DV
476 inner_div.style.width = box.height + 'px';
477 inner_div.style.height = box.width + 'px';
478 inner_div.style.top = (box.height / 2 - box.width / 2) + 'px';
479 inner_div.style.left = (box.width / 2 - box.height / 2) + 'px';
480 inner_div.style.textAlign = 'center';
b56b6993
DV
481
482 // CSS rotation is an HTML5 feature which is not standardized. Hence every
483 // browser has its own name for the CSS style.
ad1798c2
DV
484 inner_div.style.transform = 'rotate(-90deg)'; // HTML5
485 inner_div.style.WebkitTransform = 'rotate(-90deg)'; // Safari/Chrome
486 inner_div.style.MozTransform = 'rotate(-90deg)'; // Firefox
487 inner_div.style.OTransform = 'rotate(-90deg)'; // Opera
52c47e80 488 inner_div.style.msTransform = 'rotate(-90deg)'; // IE9
b56b6993
DV
489
490 if (typeof(document.documentMode) !== 'undefined' &&
491 document.documentMode < 9) {
492 // We're dealing w/ an old version of IE, so we have to rotate the text
493 // using a BasicImage transform. This uses a different origin of rotation
494 // than HTML5 rotation (top left of div vs. its center).
495 inner_div.style.filter =
496 'progid:DXImageTransform.Microsoft.BasicImage(rotation=3)';
497 inner_div.style.left = '0px';
498 inner_div.style.top = '0px';
499 }
ad1798c2 500
ca49434a
DV
501 var class_div = document.createElement("div");
502 class_div.className = 'dygraph-label dygraph-ylabel';
503 class_div.innerHTML = this.attr_('ylabel');
504
505 inner_div.appendChild(class_div);
ad1798c2
DV
506 div.appendChild(inner_div);
507 this.container.appendChild(div);
508 this.chartLabels.ylabel = div;
509 }
510};
511
512
ce49c2fa
DV
513DygraphCanvasRenderer.prototype._renderAnnotations = function() {
514 var annotationStyle = {
515 "position": "absolute",
423f5ed3 516 "fontSize": this.attr_('axisLabelFontSize') + "px",
ce49c2fa 517 "zIndex": 10,
3bf2fa91 518 "overflow": "hidden"
ce49c2fa
DV
519 };
520
ab5e5c75
DV
521 var bindEvt = function(eventName, classEventName, p, self) {
522 return function(e) {
523 var a = p.annotation;
524 if (a.hasOwnProperty(eventName)) {
525 a[eventName](a, p, self.dygraph_, e);
526 } else if (self.dygraph_.attr_(classEventName)) {
527 self.dygraph_.attr_(classEventName)(a, p, self.dygraph_,e );
528 }
529 };
530 }
531
ce49c2fa
DV
532 // Get a list of point with annotations.
533 var points = this.layout.annotated_points;
534 for (var i = 0; i < points.length; i++) {
535 var p = points[i];
e6d53148
DV
536 if (p.canvasx < this.area.x || p.canvasx > this.area.x + this.area.w) {
537 continue;
538 }
539
ce5e8d36
DV
540 var a = p.annotation;
541 var tick_height = 6;
542 if (a.hasOwnProperty("tickHeight")) {
543 tick_height = a.tickHeight;
9a40897e
DV
544 }
545
ce49c2fa
DV
546 var div = document.createElement("div");
547 for (var name in annotationStyle) {
548 if (annotationStyle.hasOwnProperty(name)) {
549 div.style[name] = annotationStyle[name];
550 }
551 }
ce5e8d36
DV
552 if (!a.hasOwnProperty('icon')) {
553 div.className = "dygraphDefaultAnnotation";
554 }
555 if (a.hasOwnProperty('cssClass')) {
556 div.className += " " + a.cssClass;
557 }
558
a5ad69cc
DV
559 var width = a.hasOwnProperty('width') ? a.width : 16;
560 var height = a.hasOwnProperty('height') ? a.height : 16;
ce5e8d36
DV
561 if (a.hasOwnProperty('icon')) {
562 var img = document.createElement("img");
563 img.src = a.icon;
33030f33
DV
564 img.width = width;
565 img.height = height;
ce5e8d36
DV
566 div.appendChild(img);
567 } else if (p.annotation.hasOwnProperty('shortText')) {
568 div.appendChild(document.createTextNode(p.annotation.shortText));
5c528fa2 569 }
ce5e8d36 570 div.style.left = (p.canvasx - width / 2) + "px";
d14b9eed
DV
571 if (a.attachAtBottom) {
572 div.style.top = (this.area.h - height - tick_height) + "px";
573 } else {
574 div.style.top = (p.canvasy - height - tick_height) + "px";
575 }
ce5e8d36
DV
576 div.style.width = width + "px";
577 div.style.height = height + "px";
ce49c2fa
DV
578 div.title = p.annotation.text;
579 div.style.color = this.colors[p.name];
580 div.style.borderColor = this.colors[p.name];
e6d53148 581 a.div = div;
ab5e5c75 582
9a40897e
DV
583 Dygraph.addEvent(div, 'click',
584 bindEvt('clickHandler', 'annotationClickHandler', p, this));
585 Dygraph.addEvent(div, 'mouseover',
586 bindEvt('mouseOverHandler', 'annotationMouseOverHandler', p, this));
587 Dygraph.addEvent(div, 'mouseout',
588 bindEvt('mouseOutHandler', 'annotationMouseOutHandler', p, this));
589 Dygraph.addEvent(div, 'dblclick',
590 bindEvt('dblClickHandler', 'annotationDblClickHandler', p, this));
ab5e5c75 591
ce49c2fa
DV
592 this.container.appendChild(div);
593 this.annotations.push(div);
9a40897e 594
2cf95fff 595 var ctx = this.elementContext;
9a40897e
DV
596 ctx.strokeStyle = this.colors[p.name];
597 ctx.beginPath();
d14b9eed
DV
598 if (!a.attachAtBottom) {
599 ctx.moveTo(p.canvasx, p.canvasy);
600 ctx.lineTo(p.canvasx, p.canvasy - 2 - tick_height);
601 } else {
602 ctx.moveTo(p.canvasx, this.area.h);
603 ctx.lineTo(p.canvasx, this.area.h - 2 - tick_height);
604 }
9a40897e
DV
605 ctx.closePath();
606 ctx.stroke();
ce49c2fa
DV
607 }
608};
609
610
6a1aa64f
DV
611/**
612 * Overrides the CanvasRenderer method to draw error bars
613 */
285a6bda 614DygraphCanvasRenderer.prototype._renderLineChart = function() {
f9414b11
DV
615 var isNullOrNaN = function(x) {
616 return (x === null || isNaN(x));
617 };
ccd9d7c2 618
44c6bc29 619 // TODO(danvk): use this.attr_ for many of these.
2cf95fff 620 var context = this.elementContext;
423f5ed3 621 var fillAlpha = this.attr_('fillAlpha');
e4182459 622 var errorBars = this.attr_("errorBars") || this.attr_("customBars");
44c6bc29 623 var fillGraph = this.attr_("fillGraph");
b2c9222a
DV
624 var stackedGraph = this.attr_("stackedGraph");
625 var stepPlot = this.attr_("stepPlot");
c3e1495b
AR
626 var points = this.layout.points;
627 var pointsLength = points.length;
21d3323f
DV
628
629 var setNames = [];
ca43052c 630 for (var name in this.layout.datasets) {
85b99f0b
DV
631 if (this.layout.datasets.hasOwnProperty(name)) {
632 setNames.push(name);
633 }
ca43052c 634 }
21d3323f 635 var setCount = setNames.length;
6a1aa64f 636
0e23cfc6 637 // TODO(danvk): Move this mapping into Dygraph and get it out of here.
f032c51d
AV
638 this.colors = {}
639 for (var i = 0; i < setCount; i++) {
600d841a 640 this.colors[setNames[i]] = this.colorScheme_[i % this.colorScheme_.length];
f032c51d
AV
641 }
642
ff00d3e2
DV
643 // Update Points
644 // TODO(danvk): here
c3e1495b
AR
645 for (var i = pointsLength; i--;) {
646 var point = points[i];
6a1aa64f
DV
647 point.canvasx = this.area.w * point.x + this.area.x;
648 point.canvasy = this.area.h * point.y + this.area.y;
649 }
6a1aa64f
DV
650
651 // create paths
80aaae18
DV
652 var ctx = context;
653 if (errorBars) {
6a834bbb
DV
654 if (fillGraph) {
655 this.dygraph_.warn("Can't use fillGraph option with error bars");
656 }
657
6a1aa64f
DV
658 for (var i = 0; i < setCount; i++) {
659 var setName = setNames[i];
b2c9222a 660 var axis = this.dygraph_.axisPropertiesForSeries(setName);
f032c51d 661 var color = this.colors[setName];
6a1aa64f
DV
662
663 // setup graphics context
80aaae18 664 ctx.save();
56623f3b 665 var prevX = NaN;
afdc483f 666 var prevY = NaN;
6a1aa64f 667 var prevYs = [-1, -1];
ea4942ed 668 var yscale = axis.yscale;
f474c2a3
DV
669 // should be same color as the lines but only 15% opaque.
670 var rgb = new RGBColor(color);
43af96e7
NK
671 var err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
672 fillAlpha + ')';
f474c2a3 673 ctx.fillStyle = err_color;
05c9d0c4 674 ctx.beginPath();
c3e1495b
AR
675 for (var j = 0; j < pointsLength; j++) {
676 var point = points[j];
6a1aa64f 677 if (point.name == setName) {
e9fe4a2f 678 if (!Dygraph.isOK(point.y)) {
56623f3b 679 prevX = NaN;
ae85914a 680 continue;
5011e7a1 681 }
ce49c2fa 682
3637724f 683 // TODO(danvk): here
afdc483f 684 if (stepPlot) {
7f028980 685 var newYs = [ point.y_bottom, point.y_top ];
afdc483f
NN
686 prevY = point.y;
687 } else {
7f028980 688 var newYs = [ point.y_bottom, point.y_top ];
afdc483f 689 }
6a1aa64f
DV
690 newYs[0] = this.area.h * newYs[0] + this.area.y;
691 newYs[1] = this.area.h * newYs[1] + this.area.y;
56623f3b 692 if (!isNaN(prevX)) {
afdc483f 693 if (stepPlot) {
47600757 694 ctx.moveTo(prevX, newYs[0]);
afdc483f 695 } else {
47600757 696 ctx.moveTo(prevX, prevYs[0]);
afdc483f 697 }
5954ef32
DV
698 ctx.lineTo(point.canvasx, newYs[0]);
699 ctx.lineTo(point.canvasx, newYs[1]);
afdc483f 700 if (stepPlot) {
47600757 701 ctx.lineTo(prevX, newYs[1]);
afdc483f 702 } else {
47600757 703 ctx.lineTo(prevX, prevYs[1]);
afdc483f 704 }
5954ef32
DV
705 ctx.closePath();
706 }
354e15ab 707 prevYs = newYs;
5954ef32
DV
708 prevX = point.canvasx;
709 }
710 }
711 ctx.fill();
712 }
713 } else if (fillGraph) {
354e15ab
DE
714 var baseline = [] // for stacked graphs: baseline for filling
715
716 // process sets in reverse order (needed for stacked graphs)
717 for (var i = setCount - 1; i >= 0; i--) {
5954ef32 718 var setName = setNames[i];
f032c51d 719 var color = this.colors[setName];
b2c9222a 720 var axis = this.dygraph_.axisPropertiesForSeries(setName);
ea4942ed
DV
721 var axisY = 1.0 + axis.minyval * axis.yscale;
722 if (axisY < 0.0) axisY = 0.0;
723 else if (axisY > 1.0) axisY = 1.0;
724 axisY = this.area.h * axisY + this.area.y;
5954ef32
DV
725
726 // setup graphics context
727 ctx.save();
56623f3b 728 var prevX = NaN;
5954ef32 729 var prevYs = [-1, -1];
ea4942ed 730 var yscale = axis.yscale;
5954ef32
DV
731 // should be same color as the lines but only 15% opaque.
732 var rgb = new RGBColor(color);
43af96e7
NK
733 var err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
734 fillAlpha + ')';
5954ef32
DV
735 ctx.fillStyle = err_color;
736 ctx.beginPath();
c3e1495b
AR
737 for (var j = 0; j < pointsLength; j++) {
738 var point = points[j];
5954ef32 739 if (point.name == setName) {
e9fe4a2f 740 if (!Dygraph.isOK(point.y)) {
56623f3b 741 prevX = NaN;
5954ef32
DV
742 continue;
743 }
354e15ab
DE
744 var newYs;
745 if (stackedGraph) {
47927039 746 var lastY = baseline[point.canvasx];
354e15ab
DE
747 if (lastY === undefined) lastY = axisY;
748 baseline[point.canvasx] = point.canvasy;
749 newYs = [ point.canvasy, lastY ];
750 } else {
751 newYs = [ point.canvasy, axisY ];
752 }
56623f3b 753 if (!isNaN(prevX)) {
05c9d0c4 754 ctx.moveTo(prevX, prevYs[0]);
afdc483f 755 if (stepPlot) {
47600757 756 ctx.lineTo(point.canvasx, prevYs[0]);
afdc483f 757 } else {
47600757 758 ctx.lineTo(point.canvasx, newYs[0]);
afdc483f 759 }
05c9d0c4
DV
760 ctx.lineTo(point.canvasx, newYs[1]);
761 ctx.lineTo(prevX, prevYs[1]);
762 ctx.closePath();
6a1aa64f 763 }
354e15ab 764 prevYs = newYs;
6a1aa64f
DV
765 prevX = point.canvasx;
766 }
05c9d0c4 767 }
6a1aa64f
DV
768 ctx.fill();
769 }
80aaae18
DV
770 }
771
f9414b11 772 // Drawing the lines.
c3e1495b
AR
773 var firstIndexInSet = 0;
774 var afterLastIndexInSet = 0;
775 var setLength = 0;
776 for (var i = 0; i < setCount; i += 1) {
777 setLength = this.layout.setPointsLengths[i];
778 afterLastIndexInSet += setLength;
80aaae18 779 var setName = setNames[i];
f032c51d 780 var color = this.colors[setName];
227b93cc 781 var strokeWidth = this.dygraph_.attr_("strokeWidth", setName);
80aaae18
DV
782
783 // setup graphics context
784 context.save();
227b93cc 785 var pointSize = this.dygraph_.attr_("pointSize", setName);
80aaae18 786 var prevX = null, prevY = null;
227b93cc 787 var drawPoints = this.dygraph_.attr_("drawPoints", setName);
c3e1495b 788 for (var j = firstIndexInSet; j < afterLastIndexInSet; j++) {
80aaae18 789 var point = points[j];
c3e1495b
AR
790 if (isNullOrNaN(point.canvasy)) {
791 if (stepPlot && prevX != null) {
792 // Draw a horizontal line to the start of the missing data
793 ctx.beginPath();
794 ctx.strokeStyle = color;
795 ctx.lineWidth = this.attr_('strokeWidth');
796 ctx.moveTo(prevX, prevY);
797 ctx.lineTo(point.canvasx, prevY);
798 ctx.stroke();
799 }
800 // this will make us move to the next point, not draw a line to it.
801 prevX = prevY = null;
802 } else {
803 // A point is "isolated" if it is non-null but both the previous
804 // and next points are null.
805 var isIsolated = (!prevX && (j == points.length - 1 ||
806 isNullOrNaN(points[j+1].canvasy)));
5f453f17 807 if (prevX === null) {
c3e1495b
AR
808 prevX = point.canvasx;
809 prevY = point.canvasy;
810 } else {
f9414b11
DV
811 // Skip over points that will be drawn in the same pixel.
812 if (Math.round(prevX) == Math.round(point.canvasx) &&
813 Math.round(prevY) == Math.round(point.canvasy)) {
814 continue;
815 }
c3e1495b
AR
816 // TODO(antrob): skip over points that lie on a line that is already
817 // going to be drawn. There is no need to have more than 2
818 // consecutive points that are collinear.
819 if (strokeWidth) {
0599d13b
NN
820 ctx.beginPath();
821 ctx.strokeStyle = color;
c3e1495b 822 ctx.lineWidth = strokeWidth;
0599d13b 823 ctx.moveTo(prevX, prevY);
c3e1495b
AR
824 if (stepPlot) {
825 ctx.lineTo(point.canvasx, prevY);
826 }
80aaae18
DV
827 prevX = point.canvasx;
828 prevY = point.canvasy;
c3e1495b
AR
829 ctx.lineTo(prevX, prevY);
830 ctx.stroke();
80aaae18
DV
831 }
832 }
5f453f17
DV
833
834 if (drawPoints || isIsolated) {
835 ctx.beginPath();
836 ctx.fillStyle = color;
837 ctx.arc(point.canvasx, point.canvasy, pointSize,
838 0, 2 * Math.PI, false);
839 ctx.fill();
c3e1495b 840 }
80aaae18
DV
841 }
842 }
c3e1495b 843 firstIndexInSet = afterLastIndexInSet;
80aaae18 844 }
6a1aa64f 845
6a1aa64f
DV
846 context.restore();
847};