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