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