un-HTMLify autotests README
[dygraphs.git] / dygraph-canvas.js
CommitLineData
6a1aa64f
DV
1// Copyright 2006 Dan Vanderkam (danvdk@gmail.com)
2// All Rights Reserved.
3
4/**
74a5af31
DV
5 * @fileoverview Based on PlotKit.CanvasRenderer, but modified to meet the
6 * needs of dygraphs.
7 *
3df0ccf0 8 * In particular, support for:
0abfbd7e 9 * - grid overlays
3df0ccf0
DV
10 * - error bars
11 * - dygraphs attribute system
6a1aa64f
DV
12 */
13
6a1aa64f 14/**
74a5af31
DV
15 * This class determines the charting area (in pixel coordinates), maps the
16 * percentage coordinates in the DygraphLayout to pixels and draws them.
17 * It's also responsible for creating chart DOM elements, i.e. annotations,
18 * tick mark labels, the title and the x/y-axis labels.
19 * This class is based on PlotKit.CanvasRenderer.
20 *
3df0ccf0 21 * Creates a new DygraphLayout object.
285a6bda 22 * @return {Object} The DygraphLayout object
6a1aa64f 23 */
b2c9222a 24DygraphLayout = function(dygraph) {
efe0829a 25 this.dygraph_ = dygraph;
efe0829a 26 this.datasets = new Array();
937029df 27 this.annotations = new Array();
b2c9222a
DV
28 this.yAxes_ = null;
29
30 // TODO(danvk): it's odd that xTicks_ and yTicks_ are inputs, but xticks and
31 // yticks are outputs. Clean this up.
32 this.xTicks_ = null;
33 this.yTicks_ = null;
6a1aa64f 34};
efe0829a
DV
35
36DygraphLayout.prototype.attr_ = function(name) {
37 return this.dygraph_.attr_(name);
38};
39
40DygraphLayout.prototype.addDataset = function(setname, set_xy) {
41 this.datasets[setname] = set_xy;
42};
43
5c528fa2
DV
44DygraphLayout.prototype.setAnnotations = function(ann) {
45 // The Dygraph object's annotations aren't parsed. We parse them here and
70a50f94 46 // save a copy. If there is no parser, then the user must be using raw format.
973e2b79 47 this.annotations = [];
70a50f94 48 var parse = this.attr_('xValueParser') || function(x) { return x; };
5c528fa2
DV
49 for (var i = 0; i < ann.length; i++) {
50 var a = {};
a685723c 51 if (!ann[i].xval && !ann[i].x) {
5c528fa2
DV
52 this.dygraph_.error("Annotations must have an 'x' property");
53 return;
54 }
ce5e8d36 55 if (ann[i].icon &&
33030f33
DV
56 !(ann[i].hasOwnProperty('width') &&
57 ann[i].hasOwnProperty('height'))) {
58 this.dygraph_.error("Must set width and height when setting " +
ce5e8d36
DV
59 "annotation.icon property");
60 return;
61 }
5c528fa2 62 Dygraph.update(a, ann[i]);
cb00f745 63 if (!a.xval) a.xval = parse(a.x, this.dygraph_);
5c528fa2 64 this.annotations.push(a);
ce49c2fa 65 }
ce49c2fa
DV
66};
67
b2c9222a
DV
68DygraphLayout.prototype.setXTicks = function(xTicks) {
69 this.xTicks_ = xTicks;
70};
71
72// TODO(danvk): add this to the Dygraph object's API or move it into Layout.
73DygraphLayout.prototype.setYAxes = function (yAxes) {
74 this.yAxes_ = yAxes;
75};
76
77DygraphLayout.prototype.setDateWindow = function(dateWindow) {
78 this.dateWindow_ = dateWindow;
79};
80
efe0829a
DV
81DygraphLayout.prototype.evaluate = function() {
82 this._evaluateLimits();
83 this._evaluateLineCharts();
84 this._evaluateLineTicks();
ce49c2fa 85 this._evaluateAnnotations();
efe0829a
DV
86};
87
88DygraphLayout.prototype._evaluateLimits = function() {
89 this.minxval = this.maxxval = null;
b2c9222a
DV
90 if (this.dateWindow_) {
91 this.minxval = this.dateWindow_[0];
92 this.maxxval = this.dateWindow_[1];
f6401bf6
DV
93 } else {
94 for (var name in this.datasets) {
95 if (!this.datasets.hasOwnProperty(name)) continue;
96 var series = this.datasets[name];
48841144
NN
97 if (series.length > 1) {
98 var x1 = series[0][0];
99 if (!this.minxval || x1 < this.minxval) this.minxval = x1;
100
101 var x2 = series[series.length - 1][0];
102 if (!this.maxxval || x2 > this.maxxval) this.maxxval = x2;
103 }
f6401bf6 104 }
efe0829a
DV
105 }
106 this.xrange = this.maxxval - this.minxval;
107 this.xscale = (this.xrange != 0 ? 1/this.xrange : 1.0);
108
b2c9222a
DV
109 for (var i = 0; i < this.yAxes_.length; i++) {
110 var axis = this.yAxes_[i];
26ca7938
DV
111 axis.minyval = axis.computedValueRange[0];
112 axis.maxyval = axis.computedValueRange[1];
ea4942ed
DV
113 axis.yrange = axis.maxyval - axis.minyval;
114 axis.yscale = (axis.yrange != 0 ? 1.0 / axis.yrange : 1.0);
ff022deb 115
c742293b
RK
116 if (axis.g.attr_("logscale")) {
117 axis.ylogrange = Dygraph.log10(axis.maxyval) - Dygraph.log10(axis.minyval);
118 axis.ylogscale = (axis.ylogrange != 0 ? 1.0 / axis.ylogrange : 1.0);
119 if (!isFinite(axis.ylogrange) || isNaN(axis.ylogrange)) {
120 axis.g.error('axis ' + i + ' of graph at ' + axis.g +
121 ' can\'t be displayed in log scale for range [' +
122 axis.minyval + ' - ' + axis.maxyval + ']');
123 }
d03e78ed 124 }
ea4942ed 125 }
efe0829a
DV
126};
127
128DygraphLayout.prototype._evaluateLineCharts = function() {
129 // add all the rects
130 this.points = new Array();
131 for (var setName in this.datasets) {
85b99f0b
DV
132 if (!this.datasets.hasOwnProperty(setName)) continue;
133
134 var dataset = this.datasets[setName];
b2c9222a 135 var axis = this.dygraph_.axisPropertiesForSeries(setName);
ea4942ed 136
85b99f0b
DV
137 for (var j = 0; j < dataset.length; j++) {
138 var item = dataset[j];
d03e78ed 139
3637724f 140 var yval;
7d0e7a0d 141 if (axis.logscale) {
0037b2a4 142 yval = 1.0 - ((Dygraph.log10(parseFloat(item[1])) - Dygraph.log10(axis.minyval)) * axis.ylogscale); // really should just be yscale.
ff022deb 143 } else {
3637724f 144 yval = 1.0 - ((parseFloat(item[1]) - axis.minyval) * axis.yscale);
ff022deb 145 }
85b99f0b 146 var point = {
ff00d3e2 147 // TODO(danvk): here
85b99f0b 148 x: ((parseFloat(item[0]) - this.minxval) * this.xscale),
3637724f 149 y: yval,
85b99f0b
DV
150 xval: parseFloat(item[0]),
151 yval: parseFloat(item[1]),
152 name: setName
153 };
154
1a26f3fb 155 this.points.push(point);
85b99f0b 156 }
efe0829a
DV
157 }
158};
159
160DygraphLayout.prototype._evaluateLineTicks = function() {
161 this.xticks = new Array();
b2c9222a
DV
162 for (var i = 0; i < this.xTicks_.length; i++) {
163 var tick = this.xTicks_[i];
efe0829a
DV
164 var label = tick.label;
165 var pos = this.xscale * (tick.v - this.minxval);
166 if ((pos >= 0.0) && (pos <= 1.0)) {
167 this.xticks.push([pos, label]);
168 }
169 }
170
171 this.yticks = new Array();
b2c9222a
DV
172 for (var i = 0; i < this.yAxes_.length; i++ ) {
173 var axis = this.yAxes_[i];
67076b22
DV
174 for (var j = 0; j < axis.ticks.length; j++) {
175 var tick = axis.ticks[j];
176 var label = tick.label;
ff022deb 177 var pos = this.dygraph_.toPercentYCoord(tick.v, i);
67076b22 178 if ((pos >= 0.0) && (pos <= 1.0)) {
9012dd21 179 this.yticks.push([i, pos, label]);
67076b22 180 }
efe0829a
DV
181 }
182 }
183};
184
6a1aa64f
DV
185
186/**
187 * Behaves the same way as PlotKit.Layout, but also copies the errors
188 * @private
189 */
285a6bda 190DygraphLayout.prototype.evaluateWithError = function() {
6a1aa64f 191 this.evaluate();
b2c9222a 192 if (!(this.attr_('errorBars') || this.attr_('customBars'))) return;
6a1aa64f
DV
193
194 // Copy over the error terms
195 var i = 0; // index in this.points
196 for (var setName in this.datasets) {
85b99f0b
DV
197 if (!this.datasets.hasOwnProperty(setName)) continue;
198 var j = 0;
199 var dataset = this.datasets[setName];
200 for (var j = 0; j < dataset.length; j++, i++) {
201 var item = dataset[j];
202 var xv = parseFloat(item[0]);
203 var yv = parseFloat(item[1]);
204
205 if (xv == this.points[i].xval &&
206 yv == this.points[i].yval) {
207 this.points[i].errorMinus = parseFloat(item[2]);
208 this.points[i].errorPlus = parseFloat(item[3]);
209 }
210 }
6a1aa64f
DV
211 }
212};
213
ce49c2fa
DV
214DygraphLayout.prototype._evaluateAnnotations = function() {
215 // Add the annotations to the point to which they belong.
216 // Make a map from (setName, xval) to annotation for quick lookups.
217 var annotations = {};
218 for (var i = 0; i < this.annotations.length; i++) {
219 var a = this.annotations[i];
220 annotations[a.xval + "," + a.series] = a;
221 }
222
223 this.annotated_points = [];
224 for (var i = 0; i < this.points.length; i++) {
225 var p = this.points[i];
226 var k = p.xval + "," + p.name;
227 if (k in annotations) {
228 p.annotation = annotations[k];
229 this.annotated_points.push(p);
230 }
231 }
232};
233
6a1aa64f
DV
234/**
235 * Convenience function to remove all the data sets from a graph
236 */
285a6bda 237DygraphLayout.prototype.removeAllDatasets = function() {
6a1aa64f
DV
238 delete this.datasets;
239 this.datasets = new Array();
240};
241
242/**
667d510b 243 * Return a copy of the point at the indicated index, with its yval unstacked.
244 * @param int index of point in layout_.points
245 */
8c03ba63 246DygraphLayout.prototype.unstackPointAtIndex = function(idx) {
667d510b 247 var point = this.points[idx];
248
249 // Clone the point since we modify it
250 var unstackedPoint = {};
251 for (var i in point) {
252 unstackedPoint[i] = point[i];
253 }
254
255 if (!this.attr_("stackedGraph")) {
256 return unstackedPoint;
257 }
258
259 // The unstacked yval is equal to the current yval minus the yval of the
260 // next point at the same xval.
261 for (var i = idx+1; i < this.points.length; i++) {
262 if (this.points[i].xval == point.xval) {
263 unstackedPoint.yval -= this.points[i].yval;
264 break;
265 }
266 }
267
268 return unstackedPoint;
269}
270
6a1aa64f 271/**
423f5ed3
DV
272 * The DygraphCanvasRenderer class does the actual rendering of the chart onto
273 * a canvas. It's based on PlotKit.CanvasRenderer.
1b89e01f 274>>>>>>> master
6a1aa64f 275 * @param {Object} element The canvas to attach to
2cf95fff
RK
276 * @param {Object} elementContext The 2d context of the canvas (injected so it
277 * can be mocked for testing.)
285a6bda 278 * @param {Layout} layout The DygraphLayout object for this graph.
74a5af31 279 * @constructor
6a1aa64f 280 */
423f5ed3 281DygraphCanvasRenderer = function(dygraph, element, elementContext, layout) {
9317362d 282 this.dygraph_ = dygraph;
fbe31dc8 283
fbe31dc8 284 this.layout = layout;
b0c3b730 285 this.element = element;
2cf95fff 286 this.elementContext = elementContext;
fbe31dc8
DV
287 this.container = this.element.parentNode;
288
fbe31dc8
DV
289 this.height = this.element.height;
290 this.width = this.element.width;
291
292 // --- check whether everything is ok before we return
293 if (!this.isIE && !(DygraphCanvasRenderer.isSupported(this.element)))
294 throw "Canvas is not supported.";
295
296 // internal state
297 this.xlabels = new Array();
298 this.ylabels = new Array();
ce49c2fa 299 this.annotations = new Array();
ad1798c2 300 this.chartLabels = {};
fbe31dc8 301
423f5ed3
DV
302 this.area = this.computeArea_();
303 this.container.style.position = "relative";
304 this.container.style.width = this.width + "px";
305
306 // Set up a clipping area for the canvas (and the interaction canvas).
307 // This ensures that we don't overdraw.
308 var ctx = this.dygraph_.canvas_ctx_;
309 ctx.beginPath();
310 ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h);
311 ctx.clip();
312
313 ctx = this.dygraph_.hidden_ctx_;
314 ctx.beginPath();
315 ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h);
316 ctx.clip();
317};
318
319DygraphCanvasRenderer.prototype.attr_ = function(x) {
320 return this.dygraph_.attr_(x);
321};
322
323// Compute the box which the chart should be drawn in. This is the canvas's
324// box, less space needed for axis and chart labels.
0e23cfc6 325// TODO(danvk): this belongs in DygraphLayout.
423f5ed3
DV
326DygraphCanvasRenderer.prototype.computeArea_ = function() {
327 var area = {
9012dd21 328 // TODO(danvk): per-axis setting.
520c8080 329 x: 0,
fbe31dc8
DV
330 y: 0
331 };
520c8080
DV
332 if (this.attr_('drawYAxis')) {
333 area.x = this.attr_('yAxisLabelWidth') + 2 * this.attr_('axisTickSize');
334 }
335
423f5ed3 336 area.w = this.width - area.x - this.attr_('rightGap');
520c8080
DV
337 area.h = this.height;
338 if (this.attr_('drawXAxis')) {
063e83ba
DV
339 if (this.attr_('xAxisHeight')) {
340 area.h -= this.attr_('xAxisHeight');
341 } else {
342 area.h -= this.attr_('axisLabelFontSize') + 2 * this.attr_('axisTickSize');
343 }
520c8080 344 }
fbe31dc8 345
26ca7938
DV
346 // Shrink the drawing area to accomodate additional y-axes.
347 if (this.dygraph_.numAxes() == 2) {
348 // TODO(danvk): per-axis setting.
423f5ed3 349 area.w -= (this.attr_('yAxisLabelWidth') + 2 * this.attr_('axisTickSize'));
26ca7938
DV
350 } else if (this.dygraph_.numAxes() > 2) {
351 this.dygraph_.error("Only two y-axes are supported at this time. (Trying " +
34de8b76 352 "to use " + this.dygraph_.numAxes() + ")");
26ca7938
DV
353 }
354
ad1798c2
DV
355 // Add space for chart labels: title, xlabel and ylabel.
356 if (this.attr_('title')) {
423f5ed3
DV
357 area.h -= this.attr_('titleHeight');
358 area.y += this.attr_('titleHeight');
ad1798c2
DV
359 }
360 if (this.attr_('xlabel')) {
423f5ed3 361 area.h -= this.attr_('xLabelHeight');
ad1798c2
DV
362 }
363 if (this.attr_('ylabel')) {
ca49434a
DV
364 // It would make sense to shift the chart here to make room for the y-axis
365 // label, but the default yAxisLabelWidth is large enough that this results
366 // in overly-padded charts. The y-axis label should fit fine. If it
367 // doesn't, the yAxisLabelWidth option can be increased.
ad1798c2
DV
368 }
369
423f5ed3 370 return area;
44c6bc29
DV
371};
372
fbe31dc8
DV
373DygraphCanvasRenderer.prototype.clear = function() {
374 if (this.isIE) {
375 // VML takes a while to start up, so we just poll every this.IEDelay
376 try {
377 if (this.clearDelay) {
378 this.clearDelay.cancel();
379 this.clearDelay = null;
380 }
2cf95fff 381 var context = this.elementContext;
fbe31dc8
DV
382 }
383 catch (e) {
76171648 384 // TODO(danvk): this is broken, since MochiKit.Async is gone.
fbe31dc8
DV
385 this.clearDelay = MochiKit.Async.wait(this.IEDelay);
386 this.clearDelay.addCallback(bind(this.clear, this));
387 return;
388 }
389 }
390
2cf95fff 391 var context = this.elementContext;
fbe31dc8
DV
392 context.clearRect(0, 0, this.width, this.height);
393
2160ed4a 394 for (var i = 0; i < this.xlabels.length; i++) {
b0c3b730 395 var el = this.xlabels[i];
b304aaec 396 if (el.parentNode) el.parentNode.removeChild(el);
2160ed4a
DV
397 }
398 for (var i = 0; i < this.ylabels.length; i++) {
b0c3b730 399 var el = this.ylabels[i];
b304aaec 400 if (el.parentNode) el.parentNode.removeChild(el);
2160ed4a 401 }
ce49c2fa
DV
402 for (var i = 0; i < this.annotations.length; i++) {
403 var el = this.annotations[i];
b304aaec 404 if (el.parentNode) el.parentNode.removeChild(el);
ce49c2fa 405 }
ad1798c2
DV
406 for (var k in this.chartLabels) {
407 if (!this.chartLabels.hasOwnProperty(k)) continue;
408 var el = this.chartLabels[k];
409 if (el.parentNode) el.parentNode.removeChild(el);
410 }
fbe31dc8
DV
411 this.xlabels = new Array();
412 this.ylabels = new Array();
ce49c2fa 413 this.annotations = new Array();
ad1798c2 414 this.chartLabels = {};
fbe31dc8
DV
415};
416
417
418DygraphCanvasRenderer.isSupported = function(canvasName) {
419 var canvas = null;
420 try {
21d3323f 421 if (typeof(canvasName) == 'undefined' || canvasName == null)
b0c3b730 422 canvas = document.createElement("canvas");
fbe31dc8 423 else
b0c3b730 424 canvas = canvasName;
fbe31dc8
DV
425 var context = canvas.getContext("2d");
426 }
427 catch (e) {
428 var ie = navigator.appVersion.match(/MSIE (\d\.\d)/);
429 var opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
430 if ((!ie) || (ie[1] < 6) || (opera))
431 return false;
432 return true;
433 }
434 return true;
6a1aa64f 435};
6a1aa64f
DV
436
437/**
600d841a
DV
438 * @param { [String] } colors Array of color strings. Should have one entry for
439 * each series to be rendered.
440 */
441DygraphCanvasRenderer.prototype.setColors = function(colors) {
442 this.colorScheme_ = colors;
443};
444
445/**
6a1aa64f
DV
446 * Draw an X/Y grid on top of the existing plot
447 */
285a6bda 448DygraphCanvasRenderer.prototype.render = function() {
528ce7e5
DV
449 // Draw the new X/Y grid. Lines appear crisper when pixels are rounded to
450 // half-integers. This prevents them from drawing in two rows/cols.
2cf95fff 451 var ctx = this.elementContext;
528ce7e5
DV
452 function halfUp(x){return Math.round(x)+0.5};
453 function halfDown(y){return Math.round(y)-0.5};
e7746234 454
423f5ed3 455 if (this.attr_('underlayCallback')) {
1e41bd2d
DV
456 // NOTE: we pass the dygraph object to this callback twice to avoid breaking
457 // users who expect a deprecated form of this callback.
423f5ed3 458 this.attr_('underlayCallback')(ctx, this.area, this.dygraph_, this.dygraph_);
e7746234
EC
459 }
460
423f5ed3 461 if (this.attr_('drawYGrid')) {
6a1aa64f
DV
462 var ticks = this.layout.yticks;
463 ctx.save();
423f5ed3 464 ctx.strokeStyle = this.attr_('gridLineColor');
990d6a35 465 ctx.lineWidth = this.attr_('gridLineWidth');
6a1aa64f 466 for (var i = 0; i < ticks.length; i++) {
880a574f
DV
467 // TODO(danvk): allow secondary axes to draw a grid, too.
468 if (ticks[i][0] != 0) continue;
528ce7e5
DV
469 var x = halfUp(this.area.x);
470 var y = halfDown(this.area.y + ticks[i][1] * this.area.h);
6a1aa64f
DV
471 ctx.beginPath();
472 ctx.moveTo(x, y);
473 ctx.lineTo(x + this.area.w, y);
474 ctx.closePath();
475 ctx.stroke();
476 }
477 }
478
423f5ed3 479 if (this.attr_('drawXGrid')) {
6a1aa64f
DV
480 var ticks = this.layout.xticks;
481 ctx.save();
423f5ed3 482 ctx.strokeStyle = this.attr_('gridLineColor');
990d6a35 483 ctx.lineWidth = this.attr_('gridLineWidth');
6a1aa64f 484 for (var i=0; i<ticks.length; i++) {
528ce7e5
DV
485 var x = halfUp(this.area.x + ticks[i][0] * this.area.w);
486 var y = halfDown(this.area.y + this.area.h);
6a1aa64f 487 ctx.beginPath();
880a574f 488 ctx.moveTo(x, y);
6a1aa64f
DV
489 ctx.lineTo(x, this.area.y);
490 ctx.closePath();
491 ctx.stroke();
492 }
493 }
2ce09b19
DV
494
495 // Do the ordinary rendering, as before
2ce09b19 496 this._renderLineChart();
fbe31dc8 497 this._renderAxis();
ad1798c2 498 this._renderChartLabels();
ce49c2fa 499 this._renderAnnotations();
fbe31dc8
DV
500};
501
502
503DygraphCanvasRenderer.prototype._renderAxis = function() {
423f5ed3 504 if (!this.attr_('drawXAxis') && !this.attr_('drawYAxis')) return;
fbe31dc8 505
528ce7e5
DV
506 // Round pixels to half-integer boundaries for crisper drawing.
507 function halfUp(x){return Math.round(x)+0.5};
508 function halfDown(y){return Math.round(y)-0.5};
509
2cf95fff 510 var context = this.elementContext;
fbe31dc8 511
34fedff8 512 var labelStyle = {
423f5ed3
DV
513 position: "absolute",
514 fontSize: this.attr_('axisLabelFontSize') + "px",
515 zIndex: 10,
516 color: this.attr_('axisLabelColor'),
517 width: this.attr_('axisLabelWidth') + "px",
74a5af31 518 // height: this.attr_('axisLabelFontSize') + 2 + "px",
423f5ed3 519 overflow: "hidden"
34fedff8 520 };
ba451526 521 var makeDiv = function(txt, axis) {
34fedff8
DV
522 var div = document.createElement("div");
523 for (var name in labelStyle) {
85b99f0b
DV
524 if (labelStyle.hasOwnProperty(name)) {
525 div.style[name] = labelStyle[name];
526 }
fbe31dc8 527 }
ba451526
DV
528 var inner_div = document.createElement("div");
529 // TODO(danvk): separate class for secondary y-axis
530 inner_div.className = 'dygraph-axis-label dygraph-axis-label-' + axis;
531 inner_div.appendChild(document.createTextNode(txt));
532 div.appendChild(inner_div);
34fedff8 533 return div;
fbe31dc8
DV
534 };
535
536 // axis lines
537 context.save();
423f5ed3
DV
538 context.strokeStyle = this.attr_('axisLineColor');
539 context.lineWidth = this.attr_('axisLineWidth');
fbe31dc8 540
423f5ed3 541 if (this.attr_('drawYAxis')) {
8b7a0cc3 542 if (this.layout.yticks && this.layout.yticks.length > 0) {
2160ed4a
DV
543 for (var i = 0; i < this.layout.yticks.length; i++) {
544 var tick = this.layout.yticks[i];
fbe31dc8
DV
545 if (typeof(tick) == "function") return;
546 var x = this.area.x;
880a574f
DV
547 var sgn = 1;
548 if (tick[0] == 1) { // right-side y-axis
549 x = this.area.x + this.area.w;
550 sgn = -1;
9012dd21
DV
551 }
552 var y = this.area.y + tick[1] * this.area.h;
fbe31dc8 553 context.beginPath();
528ce7e5 554 context.moveTo(halfUp(x), halfDown(y));
0e23cfc6 555 context.lineTo(halfUp(x - sgn * this.attr_('axisTickSize')), halfDown(y));
fbe31dc8
DV
556 context.closePath();
557 context.stroke();
558
ba451526 559 var label = makeDiv(tick[2], 'y');
423f5ed3 560 var top = (y - this.attr_('axisLabelFontSize') / 2);
fbe31dc8
DV
561 if (top < 0) top = 0;
562
423f5ed3 563 if (top + this.attr_('axisLabelFontSize') + 3 > this.height) {
fbe31dc8
DV
564 label.style.bottom = "0px";
565 } else {
566 label.style.top = top + "px";
567 }
9012dd21 568 if (tick[0] == 0) {
423f5ed3 569 label.style.left = (this.area.x - this.attr_('yAxisLabelWidth') - this.attr_('axisTickSize')) + "px";
9012dd21
DV
570 label.style.textAlign = "right";
571 } else if (tick[0] == 1) {
572 label.style.left = (this.area.x + this.area.w +
423f5ed3 573 this.attr_('axisTickSize')) + "px";
9012dd21
DV
574 label.style.textAlign = "left";
575 }
423f5ed3 576 label.style.width = this.attr_('yAxisLabelWidth') + "px";
b0c3b730 577 this.container.appendChild(label);
fbe31dc8 578 this.ylabels.push(label);
2160ed4a 579 }
fbe31dc8
DV
580
581 // The lowest tick on the y-axis often overlaps with the leftmost
582 // tick on the x-axis. Shift the bottom tick up a little bit to
583 // compensate if necessary.
584 var bottomTick = this.ylabels[0];
423f5ed3 585 var fontSize = this.attr_('axisLabelFontSize');
fbe31dc8
DV
586 var bottom = parseInt(bottomTick.style.top) + fontSize;
587 if (bottom > this.height - fontSize) {
588 bottomTick.style.top = (parseInt(bottomTick.style.top) -
589 fontSize / 2) + "px";
590 }
591 }
592
528ce7e5 593 // draw a vertical line on the left to separate the chart from the labels.
fbe31dc8 594 context.beginPath();
528ce7e5
DV
595 context.moveTo(halfUp(this.area.x), halfDown(this.area.y));
596 context.lineTo(halfUp(this.area.x), halfDown(this.area.y + this.area.h));
fbe31dc8
DV
597 context.closePath();
598 context.stroke();
c1dbeb10 599
528ce7e5 600 // if there's a secondary y-axis, draw a vertical line for that, too.
c1dbeb10
DV
601 if (this.dygraph_.numAxes() == 2) {
602 context.beginPath();
528ce7e5
DV
603 context.moveTo(halfDown(this.area.x + this.area.w), halfDown(this.area.y));
604 context.lineTo(halfDown(this.area.x + this.area.w), halfDown(this.area.y + this.area.h));
c1dbeb10
DV
605 context.closePath();
606 context.stroke();
607 }
fbe31dc8
DV
608 }
609
423f5ed3 610 if (this.attr_('drawXAxis')) {
fbe31dc8 611 if (this.layout.xticks) {
2160ed4a
DV
612 for (var i = 0; i < this.layout.xticks.length; i++) {
613 var tick = this.layout.xticks[i];
fbe31dc8
DV
614 if (typeof(dataset) == "function") return;
615
616 var x = this.area.x + tick[0] * this.area.w;
617 var y = this.area.y + this.area.h;
618 context.beginPath();
528ce7e5 619 context.moveTo(halfUp(x), halfDown(y));
423f5ed3 620 context.lineTo(halfUp(x), halfDown(y + this.attr_('axisTickSize')));
fbe31dc8
DV
621 context.closePath();
622 context.stroke();
623
ba451526 624 var label = makeDiv(tick[1], 'x');
fbe31dc8 625 label.style.textAlign = "center";
423f5ed3 626 label.style.top = (y + this.attr_('axisTickSize')) + 'px';
fbe31dc8 627
423f5ed3
DV
628 var left = (x - this.attr_('axisLabelWidth')/2);
629 if (left + this.attr_('axisLabelWidth') > this.width) {
630 left = this.width - this.attr_('xAxisLabelWidth');
fbe31dc8
DV
631 label.style.textAlign = "right";
632 }
633 if (left < 0) {
634 left = 0;
635 label.style.textAlign = "left";
636 }
637
638 label.style.left = left + "px";
423f5ed3 639 label.style.width = this.attr_('xAxisLabelWidth') + "px";
b0c3b730 640 this.container.appendChild(label);
fbe31dc8 641 this.xlabels.push(label);
2160ed4a 642 }
fbe31dc8
DV
643 }
644
645 context.beginPath();
528ce7e5
DV
646 context.moveTo(halfUp(this.area.x), halfDown(this.area.y + this.area.h));
647 context.lineTo(halfUp(this.area.x + this.area.w), halfDown(this.area.y + this.area.h));
fbe31dc8
DV
648 context.closePath();
649 context.stroke();
650 }
651
652 context.restore();
6a1aa64f
DV
653};
654
fbe31dc8 655
ad1798c2
DV
656DygraphCanvasRenderer.prototype._renderChartLabels = function() {
657 // Generate divs for the chart title, xlabel and ylabel.
658 // Space for these divs has already been taken away from the charting area in
659 // the DygraphCanvasRenderer constructor.
660 if (this.attr_('title')) {
661 var div = document.createElement("div");
662 div.style.position = 'absolute';
663 div.style.top = '0px';
664 div.style.left = this.area.x + 'px';
665 div.style.width = this.area.w + 'px';
666 div.style.height = this.attr_('titleHeight') + 'px';
667 div.style.textAlign = 'center';
b4202b3d 668 div.style.fontSize = (this.attr_('titleHeight') - 8) + 'px';
ad1798c2 669 div.style.fontWeight = 'bold';
ca49434a
DV
670 var class_div = document.createElement("div");
671 class_div.className = 'dygraph-label dygraph-title';
672 class_div.innerHTML = this.attr_('title');
673 div.appendChild(class_div);
ad1798c2
DV
674 this.container.appendChild(div);
675 this.chartLabels.title = div;
676 }
677
678 if (this.attr_('xlabel')) {
679 var div = document.createElement("div");
680 div.style.position = 'absolute';
681 div.style.bottom = 0; // TODO(danvk): this is lazy. Calculate style.top.
682 div.style.left = this.area.x + 'px';
683 div.style.width = this.area.w + 'px';
684 div.style.height = this.attr_('xLabelHeight') + 'px';
685 div.style.textAlign = 'center';
86cce9e8 686 div.style.fontSize = (this.attr_('xLabelHeight') - 2) + 'px';
ca49434a
DV
687
688 var class_div = document.createElement("div");
689 class_div.className = 'dygraph-label dygraph-xlabel';
690 class_div.innerHTML = this.attr_('xlabel');
691 div.appendChild(class_div);
ad1798c2
DV
692 this.container.appendChild(div);
693 this.chartLabels.xlabel = div;
694 }
695
696 if (this.attr_('ylabel')) {
697 var box = {
698 left: 0,
699 top: this.area.y,
700 width: this.attr_('yLabelWidth'),
701 height: this.area.h
702 };
ca49434a 703 // TODO(danvk): is this outer div actually necessary?
ad1798c2
DV
704 var div = document.createElement("div");
705 div.style.position = 'absolute';
706 div.style.left = box.left;
707 div.style.top = box.top + 'px';
708 div.style.width = box.width + 'px';
709 div.style.height = box.height + 'px';
86cce9e8 710 div.style.fontSize = (this.attr_('yLabelWidth') - 2) + 'px';
ad1798c2
DV
711
712 var inner_div = document.createElement("div");
713 inner_div.style.position = 'absolute';
ad1798c2
DV
714 inner_div.style.width = box.height + 'px';
715 inner_div.style.height = box.width + 'px';
716 inner_div.style.top = (box.height / 2 - box.width / 2) + 'px';
717 inner_div.style.left = (box.width / 2 - box.height / 2) + 'px';
718 inner_div.style.textAlign = 'center';
b56b6993
DV
719
720 // CSS rotation is an HTML5 feature which is not standardized. Hence every
721 // browser has its own name for the CSS style.
ad1798c2
DV
722 inner_div.style.transform = 'rotate(-90deg)'; // HTML5
723 inner_div.style.WebkitTransform = 'rotate(-90deg)'; // Safari/Chrome
724 inner_div.style.MozTransform = 'rotate(-90deg)'; // Firefox
725 inner_div.style.OTransform = 'rotate(-90deg)'; // Opera
52c47e80 726 inner_div.style.msTransform = 'rotate(-90deg)'; // IE9
b56b6993
DV
727
728 if (typeof(document.documentMode) !== 'undefined' &&
729 document.documentMode < 9) {
730 // We're dealing w/ an old version of IE, so we have to rotate the text
731 // using a BasicImage transform. This uses a different origin of rotation
732 // than HTML5 rotation (top left of div vs. its center).
733 inner_div.style.filter =
734 'progid:DXImageTransform.Microsoft.BasicImage(rotation=3)';
735 inner_div.style.left = '0px';
736 inner_div.style.top = '0px';
737 }
ad1798c2 738
ca49434a
DV
739 var class_div = document.createElement("div");
740 class_div.className = 'dygraph-label dygraph-ylabel';
741 class_div.innerHTML = this.attr_('ylabel');
742
743 inner_div.appendChild(class_div);
ad1798c2
DV
744 div.appendChild(inner_div);
745 this.container.appendChild(div);
746 this.chartLabels.ylabel = div;
747 }
748};
749
750
ce49c2fa
DV
751DygraphCanvasRenderer.prototype._renderAnnotations = function() {
752 var annotationStyle = {
753 "position": "absolute",
423f5ed3 754 "fontSize": this.attr_('axisLabelFontSize') + "px",
ce49c2fa 755 "zIndex": 10,
3bf2fa91 756 "overflow": "hidden"
ce49c2fa
DV
757 };
758
ab5e5c75
DV
759 var bindEvt = function(eventName, classEventName, p, self) {
760 return function(e) {
761 var a = p.annotation;
762 if (a.hasOwnProperty(eventName)) {
763 a[eventName](a, p, self.dygraph_, e);
764 } else if (self.dygraph_.attr_(classEventName)) {
765 self.dygraph_.attr_(classEventName)(a, p, self.dygraph_,e );
766 }
767 };
768 }
769
ce49c2fa
DV
770 // Get a list of point with annotations.
771 var points = this.layout.annotated_points;
772 for (var i = 0; i < points.length; i++) {
773 var p = points[i];
e6d53148
DV
774 if (p.canvasx < this.area.x || p.canvasx > this.area.x + this.area.w) {
775 continue;
776 }
777
ce5e8d36
DV
778 var a = p.annotation;
779 var tick_height = 6;
780 if (a.hasOwnProperty("tickHeight")) {
781 tick_height = a.tickHeight;
9a40897e
DV
782 }
783
ce49c2fa
DV
784 var div = document.createElement("div");
785 for (var name in annotationStyle) {
786 if (annotationStyle.hasOwnProperty(name)) {
787 div.style[name] = annotationStyle[name];
788 }
789 }
ce5e8d36
DV
790 if (!a.hasOwnProperty('icon')) {
791 div.className = "dygraphDefaultAnnotation";
792 }
793 if (a.hasOwnProperty('cssClass')) {
794 div.className += " " + a.cssClass;
795 }
796
a5ad69cc
DV
797 var width = a.hasOwnProperty('width') ? a.width : 16;
798 var height = a.hasOwnProperty('height') ? a.height : 16;
ce5e8d36
DV
799 if (a.hasOwnProperty('icon')) {
800 var img = document.createElement("img");
801 img.src = a.icon;
33030f33
DV
802 img.width = width;
803 img.height = height;
ce5e8d36
DV
804 div.appendChild(img);
805 } else if (p.annotation.hasOwnProperty('shortText')) {
806 div.appendChild(document.createTextNode(p.annotation.shortText));
5c528fa2 807 }
ce5e8d36 808 div.style.left = (p.canvasx - width / 2) + "px";
d14b9eed
DV
809 if (a.attachAtBottom) {
810 div.style.top = (this.area.h - height - tick_height) + "px";
811 } else {
812 div.style.top = (p.canvasy - height - tick_height) + "px";
813 }
ce5e8d36
DV
814 div.style.width = width + "px";
815 div.style.height = height + "px";
ce49c2fa
DV
816 div.title = p.annotation.text;
817 div.style.color = this.colors[p.name];
818 div.style.borderColor = this.colors[p.name];
e6d53148 819 a.div = div;
ab5e5c75 820
9a40897e
DV
821 Dygraph.addEvent(div, 'click',
822 bindEvt('clickHandler', 'annotationClickHandler', p, this));
823 Dygraph.addEvent(div, 'mouseover',
824 bindEvt('mouseOverHandler', 'annotationMouseOverHandler', p, this));
825 Dygraph.addEvent(div, 'mouseout',
826 bindEvt('mouseOutHandler', 'annotationMouseOutHandler', p, this));
827 Dygraph.addEvent(div, 'dblclick',
828 bindEvt('dblClickHandler', 'annotationDblClickHandler', p, this));
ab5e5c75 829
ce49c2fa
DV
830 this.container.appendChild(div);
831 this.annotations.push(div);
9a40897e 832
2cf95fff 833 var ctx = this.elementContext;
9a40897e
DV
834 ctx.strokeStyle = this.colors[p.name];
835 ctx.beginPath();
d14b9eed
DV
836 if (!a.attachAtBottom) {
837 ctx.moveTo(p.canvasx, p.canvasy);
838 ctx.lineTo(p.canvasx, p.canvasy - 2 - tick_height);
839 } else {
840 ctx.moveTo(p.canvasx, this.area.h);
841 ctx.lineTo(p.canvasx, this.area.h - 2 - tick_height);
842 }
9a40897e
DV
843 ctx.closePath();
844 ctx.stroke();
ce49c2fa
DV
845 }
846};
847
848
6a1aa64f
DV
849/**
850 * Overrides the CanvasRenderer method to draw error bars
851 */
285a6bda 852DygraphCanvasRenderer.prototype._renderLineChart = function() {
44c6bc29 853 // TODO(danvk): use this.attr_ for many of these.
2cf95fff 854 var context = this.elementContext;
423f5ed3 855 var fillAlpha = this.attr_('fillAlpha');
e4182459 856 var errorBars = this.attr_("errorBars") || this.attr_("customBars");
44c6bc29 857 var fillGraph = this.attr_("fillGraph");
b2c9222a
DV
858 var stackedGraph = this.attr_("stackedGraph");
859 var stepPlot = this.attr_("stepPlot");
21d3323f
DV
860
861 var setNames = [];
ca43052c 862 for (var name in this.layout.datasets) {
85b99f0b
DV
863 if (this.layout.datasets.hasOwnProperty(name)) {
864 setNames.push(name);
865 }
ca43052c 866 }
21d3323f 867 var setCount = setNames.length;
6a1aa64f 868
0e23cfc6 869 // TODO(danvk): Move this mapping into Dygraph and get it out of here.
f032c51d
AV
870 this.colors = {}
871 for (var i = 0; i < setCount; i++) {
600d841a 872 this.colors[setNames[i]] = this.colorScheme_[i % this.colorScheme_.length];
f032c51d
AV
873 }
874
ff00d3e2
DV
875 // Update Points
876 // TODO(danvk): here
2160ed4a
DV
877 for (var i = 0; i < this.layout.points.length; i++) {
878 var point = this.layout.points[i];
6a1aa64f
DV
879 point.canvasx = this.area.w * point.x + this.area.x;
880 point.canvasy = this.area.h * point.y + this.area.y;
881 }
6a1aa64f
DV
882
883 // create paths
80aaae18
DV
884 var ctx = context;
885 if (errorBars) {
6a834bbb
DV
886 if (fillGraph) {
887 this.dygraph_.warn("Can't use fillGraph option with error bars");
888 }
889
6a1aa64f
DV
890 for (var i = 0; i < setCount; i++) {
891 var setName = setNames[i];
b2c9222a 892 var axis = this.dygraph_.axisPropertiesForSeries(setName);
f032c51d 893 var color = this.colors[setName];
6a1aa64f
DV
894
895 // setup graphics context
80aaae18 896 ctx.save();
56623f3b 897 var prevX = NaN;
afdc483f 898 var prevY = NaN;
6a1aa64f 899 var prevYs = [-1, -1];
ea4942ed 900 var yscale = axis.yscale;
f474c2a3
DV
901 // should be same color as the lines but only 15% opaque.
902 var rgb = new RGBColor(color);
43af96e7
NK
903 var err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
904 fillAlpha + ')';
f474c2a3 905 ctx.fillStyle = err_color;
05c9d0c4
DV
906 ctx.beginPath();
907 for (var j = 0; j < this.layout.points.length; j++) {
908 var point = this.layout.points[j];
6a1aa64f 909 if (point.name == setName) {
e9fe4a2f 910 if (!Dygraph.isOK(point.y)) {
56623f3b 911 prevX = NaN;
ae85914a 912 continue;
5011e7a1 913 }
ce49c2fa 914
3637724f 915 // TODO(danvk): here
afdc483f
NN
916 if (stepPlot) {
917 var newYs = [ prevY - point.errorPlus * yscale,
47600757 918 prevY + point.errorMinus * yscale ];
afdc483f
NN
919 prevY = point.y;
920 } else {
921 var newYs = [ point.y - point.errorPlus * yscale,
47600757 922 point.y + point.errorMinus * yscale ];
afdc483f 923 }
6a1aa64f
DV
924 newYs[0] = this.area.h * newYs[0] + this.area.y;
925 newYs[1] = this.area.h * newYs[1] + this.area.y;
56623f3b 926 if (!isNaN(prevX)) {
afdc483f 927 if (stepPlot) {
47600757 928 ctx.moveTo(prevX, newYs[0]);
afdc483f 929 } else {
47600757 930 ctx.moveTo(prevX, prevYs[0]);
afdc483f 931 }
5954ef32
DV
932 ctx.lineTo(point.canvasx, newYs[0]);
933 ctx.lineTo(point.canvasx, newYs[1]);
afdc483f 934 if (stepPlot) {
47600757 935 ctx.lineTo(prevX, newYs[1]);
afdc483f 936 } else {
47600757 937 ctx.lineTo(prevX, prevYs[1]);
afdc483f 938 }
5954ef32
DV
939 ctx.closePath();
940 }
354e15ab 941 prevYs = newYs;
5954ef32
DV
942 prevX = point.canvasx;
943 }
944 }
945 ctx.fill();
946 }
947 } else if (fillGraph) {
354e15ab
DE
948 var baseline = [] // for stacked graphs: baseline for filling
949
950 // process sets in reverse order (needed for stacked graphs)
951 for (var i = setCount - 1; i >= 0; i--) {
5954ef32 952 var setName = setNames[i];
f032c51d 953 var color = this.colors[setName];
b2c9222a 954 var axis = this.dygraph_.axisPropertiesForSeries(setName);
ea4942ed
DV
955 var axisY = 1.0 + axis.minyval * axis.yscale;
956 if (axisY < 0.0) axisY = 0.0;
957 else if (axisY > 1.0) axisY = 1.0;
958 axisY = this.area.h * axisY + this.area.y;
5954ef32
DV
959
960 // setup graphics context
961 ctx.save();
56623f3b 962 var prevX = NaN;
5954ef32 963 var prevYs = [-1, -1];
ea4942ed 964 var yscale = axis.yscale;
5954ef32
DV
965 // should be same color as the lines but only 15% opaque.
966 var rgb = new RGBColor(color);
43af96e7
NK
967 var err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
968 fillAlpha + ')';
5954ef32
DV
969 ctx.fillStyle = err_color;
970 ctx.beginPath();
971 for (var j = 0; j < this.layout.points.length; j++) {
972 var point = this.layout.points[j];
5954ef32 973 if (point.name == setName) {
e9fe4a2f 974 if (!Dygraph.isOK(point.y)) {
56623f3b 975 prevX = NaN;
5954ef32
DV
976 continue;
977 }
354e15ab
DE
978 var newYs;
979 if (stackedGraph) {
980 lastY = baseline[point.canvasx];
981 if (lastY === undefined) lastY = axisY;
982 baseline[point.canvasx] = point.canvasy;
983 newYs = [ point.canvasy, lastY ];
984 } else {
985 newYs = [ point.canvasy, axisY ];
986 }
56623f3b 987 if (!isNaN(prevX)) {
05c9d0c4 988 ctx.moveTo(prevX, prevYs[0]);
afdc483f 989 if (stepPlot) {
47600757 990 ctx.lineTo(point.canvasx, prevYs[0]);
afdc483f 991 } else {
47600757 992 ctx.lineTo(point.canvasx, newYs[0]);
afdc483f 993 }
05c9d0c4
DV
994 ctx.lineTo(point.canvasx, newYs[1]);
995 ctx.lineTo(prevX, prevYs[1]);
996 ctx.closePath();
6a1aa64f 997 }
354e15ab 998 prevYs = newYs;
6a1aa64f
DV
999 prevX = point.canvasx;
1000 }
05c9d0c4 1001 }
6a1aa64f
DV
1002 ctx.fill();
1003 }
80aaae18
DV
1004 }
1005
063e83ba
DV
1006 var isNullOrNaN = function(x) {
1007 return (x === null || isNaN(x));
1008 };
1009
80aaae18
DV
1010 for (var i = 0; i < setCount; i++) {
1011 var setName = setNames[i];
f032c51d 1012 var color = this.colors[setName];
227b93cc 1013 var strokeWidth = this.dygraph_.attr_("strokeWidth", setName);
80aaae18
DV
1014
1015 // setup graphics context
1016 context.save();
1017 var point = this.layout.points[0];
227b93cc 1018 var pointSize = this.dygraph_.attr_("pointSize", setName);
80aaae18 1019 var prevX = null, prevY = null;
227b93cc 1020 var drawPoints = this.dygraph_.attr_("drawPoints", setName);
80aaae18
DV
1021 var points = this.layout.points;
1022 for (var j = 0; j < points.length; j++) {
1023 var point = points[j];
1024 if (point.name == setName) {
063e83ba 1025 if (isNullOrNaN(point.canvasy)) {
5d13ef68 1026 if (stepPlot && prevX != null) {
0599d13b
NN
1027 // Draw a horizontal line to the start of the missing data
1028 ctx.beginPath();
1029 ctx.strokeStyle = color;
423f5ed3 1030 ctx.lineWidth = this.attr_('strokeWidth');
0599d13b
NN
1031 ctx.moveTo(prevX, prevY);
1032 ctx.lineTo(point.canvasx, prevY);
1033 ctx.stroke();
1034 }
80aaae18
DV
1035 // this will make us move to the next point, not draw a line to it.
1036 prevX = prevY = null;
1037 } else {
1038 // A point is "isolated" if it is non-null but both the previous
1039 // and next points are null.
1040 var isIsolated = (!prevX && (j == points.length - 1 ||
063e83ba 1041 isNullOrNaN(points[j+1].canvasy)));
80aaae18 1042
95398db1 1043 if (prevX === null) {
80aaae18
DV
1044 prevX = point.canvasx;
1045 prevY = point.canvasy;
1046 } else {
46dde5f9
DV
1047 // TODO(danvk): figure out why this conditional is necessary.
1048 if (strokeWidth) {
1049 ctx.beginPath();
1050 ctx.strokeStyle = color;
1051 ctx.lineWidth = strokeWidth;
1052 ctx.moveTo(prevX, prevY);
1053 if (stepPlot) {
1054 ctx.lineTo(point.canvasx, prevY);
1055 }
1056 prevX = point.canvasx;
1057 prevY = point.canvasy;
1058 ctx.lineTo(prevX, prevY);
1059 ctx.stroke();
afdc483f 1060 }
80aaae18
DV
1061 }
1062
1063 if (drawPoints || isIsolated) {
1064 ctx.beginPath();
1065 ctx.fillStyle = color;
7bf6a9fe
DV
1066 ctx.arc(point.canvasx, point.canvasy, pointSize,
1067 0, 2 * Math.PI, false);
80aaae18
DV
1068 ctx.fill();
1069 }
1070 }
1071 }
1072 }
1073 }
6a1aa64f 1074
6a1aa64f
DV
1075 context.restore();
1076};