no more renderer options!
[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 * @return {Object} The DygraphLayout object
33 */
34 DygraphLayout = function(dygraph) {
35 this.dygraph_ = dygraph;
36 this.datasets = new Array();
37 this.annotations = new Array();
38 this.yAxes_ = null;
39
40 // TODO(danvk): it's odd that xTicks_ and yTicks_ are inputs, but xticks and
41 // yticks are outputs. Clean this up.
42 this.xTicks_ = null;
43 this.yTicks_ = null;
44 };
45
46 DygraphLayout.prototype.attr_ = function(name) {
47 return this.dygraph_.attr_(name);
48 };
49
50 DygraphLayout.prototype.addDataset = function(setname, set_xy) {
51 this.datasets[setname] = set_xy;
52 };
53
54 DygraphLayout.prototype.setAnnotations = function(ann) {
55 // The Dygraph object's annotations aren't parsed. We parse them here and
56 // save a copy. If there is no parser, then the user must be using raw format.
57 this.annotations = [];
58 var parse = this.attr_('xValueParser') || function(x) { return x; };
59 for (var i = 0; i < ann.length; i++) {
60 var a = {};
61 if (!ann[i].xval && !ann[i].x) {
62 this.dygraph_.error("Annotations must have an 'x' property");
63 return;
64 }
65 if (ann[i].icon &&
66 !(ann[i].hasOwnProperty('width') &&
67 ann[i].hasOwnProperty('height'))) {
68 this.dygraph_.error("Must set width and height when setting " +
69 "annotation.icon property");
70 return;
71 }
72 Dygraph.update(a, ann[i]);
73 if (!a.xval) a.xval = parse(a.x);
74 this.annotations.push(a);
75 }
76 };
77
78 DygraphLayout.prototype.setXTicks = function(xTicks) {
79 this.xTicks_ = xTicks;
80 };
81
82 // TODO(danvk): add this to the Dygraph object's API or move it into Layout.
83 DygraphLayout.prototype.setYAxes = function (yAxes) {
84 this.yAxes_ = yAxes;
85 };
86
87 DygraphLayout.prototype.setDateWindow = function(dateWindow) {
88 this.dateWindow_ = dateWindow;
89 };
90
91 DygraphLayout.prototype.evaluate = function() {
92 this._evaluateLimits();
93 this._evaluateLineCharts();
94 this._evaluateLineTicks();
95 this._evaluateAnnotations();
96 };
97
98 DygraphLayout.prototype._evaluateLimits = function() {
99 this.minxval = this.maxxval = null;
100 if (this.dateWindow_) {
101 this.minxval = this.dateWindow_[0];
102 this.maxxval = this.dateWindow_[1];
103 } else {
104 for (var name in this.datasets) {
105 if (!this.datasets.hasOwnProperty(name)) continue;
106 var series = this.datasets[name];
107 if (series.length > 1) {
108 var x1 = series[0][0];
109 if (!this.minxval || x1 < this.minxval) this.minxval = x1;
110
111 var x2 = series[series.length - 1][0];
112 if (!this.maxxval || x2 > this.maxxval) this.maxxval = x2;
113 }
114 }
115 }
116 this.xrange = this.maxxval - this.minxval;
117 this.xscale = (this.xrange != 0 ? 1/this.xrange : 1.0);
118
119 for (var i = 0; i < this.yAxes_.length; i++) {
120 var axis = this.yAxes_[i];
121 axis.minyval = axis.computedValueRange[0];
122 axis.maxyval = axis.computedValueRange[1];
123 axis.yrange = axis.maxyval - axis.minyval;
124 axis.yscale = (axis.yrange != 0 ? 1.0 / axis.yrange : 1.0);
125
126 if (axis.g.attr_("logscale")) {
127 axis.ylogrange = Dygraph.log10(axis.maxyval) - Dygraph.log10(axis.minyval);
128 axis.ylogscale = (axis.ylogrange != 0 ? 1.0 / axis.ylogrange : 1.0);
129 if (!isFinite(axis.ylogrange) || isNaN(axis.ylogrange)) {
130 axis.g.error('axis ' + i + ' of graph at ' + axis.g +
131 ' can\'t be displayed in log scale for range [' +
132 axis.minyval + ' - ' + axis.maxyval + ']');
133 }
134 }
135 }
136 };
137
138 DygraphLayout.prototype._evaluateLineCharts = function() {
139 // add all the rects
140 this.points = new Array();
141 for (var setName in this.datasets) {
142 if (!this.datasets.hasOwnProperty(setName)) continue;
143
144 var dataset = this.datasets[setName];
145 var axis = this.dygraph_.axisPropertiesForSeries(setName);
146
147 for (var j = 0; j < dataset.length; j++) {
148 var item = dataset[j];
149
150 var yval;
151 if (axis.logscale) {
152 yval = 1.0 - ((Dygraph.log10(parseFloat(item[1])) - Dygraph.log10(axis.minyval)) * axis.ylogscale); // really should just be yscale.
153 } else {
154 yval = 1.0 - ((parseFloat(item[1]) - axis.minyval) * axis.yscale);
155 }
156 var point = {
157 // TODO(danvk): here
158 x: ((parseFloat(item[0]) - this.minxval) * this.xscale),
159 y: yval,
160 xval: parseFloat(item[0]),
161 yval: parseFloat(item[1]),
162 name: setName
163 };
164
165 this.points.push(point);
166 }
167 }
168 };
169
170 DygraphLayout.prototype._evaluateLineTicks = function() {
171 this.xticks = new Array();
172 for (var i = 0; i < this.xTicks_.length; i++) {
173 var tick = this.xTicks_[i];
174 var label = tick.label;
175 var pos = this.xscale * (tick.v - this.minxval);
176 if ((pos >= 0.0) && (pos <= 1.0)) {
177 this.xticks.push([pos, label]);
178 }
179 }
180
181 this.yticks = new Array();
182 for (var i = 0; i < this.yAxes_.length; i++ ) {
183 var axis = this.yAxes_[i];
184 for (var j = 0; j < axis.ticks.length; j++) {
185 var tick = axis.ticks[j];
186 var label = tick.label;
187 var pos = this.dygraph_.toPercentYCoord(tick.v, i);
188 if ((pos >= 0.0) && (pos <= 1.0)) {
189 this.yticks.push([i, pos, label]);
190 }
191 }
192 }
193 };
194
195
196 /**
197 * Behaves the same way as PlotKit.Layout, but also copies the errors
198 * @private
199 */
200 DygraphLayout.prototype.evaluateWithError = function() {
201 this.evaluate();
202 if (!(this.attr_('errorBars') || this.attr_('customBars'))) return;
203
204 // Copy over the error terms
205 var i = 0; // index in this.points
206 for (var setName in this.datasets) {
207 if (!this.datasets.hasOwnProperty(setName)) continue;
208 var j = 0;
209 var dataset = this.datasets[setName];
210 for (var j = 0; j < dataset.length; j++, i++) {
211 var item = dataset[j];
212 var xv = parseFloat(item[0]);
213 var yv = parseFloat(item[1]);
214
215 if (xv == this.points[i].xval &&
216 yv == this.points[i].yval) {
217 this.points[i].errorMinus = parseFloat(item[2]);
218 this.points[i].errorPlus = parseFloat(item[3]);
219 }
220 }
221 }
222 };
223
224 DygraphLayout.prototype._evaluateAnnotations = function() {
225 // Add the annotations to the point to which they belong.
226 // Make a map from (setName, xval) to annotation for quick lookups.
227 var annotations = {};
228 for (var i = 0; i < this.annotations.length; i++) {
229 var a = this.annotations[i];
230 annotations[a.xval + "," + a.series] = a;
231 }
232
233 this.annotated_points = [];
234 for (var i = 0; i < this.points.length; i++) {
235 var p = this.points[i];
236 var k = p.xval + "," + p.name;
237 if (k in annotations) {
238 p.annotation = annotations[k];
239 this.annotated_points.push(p);
240 }
241 }
242 };
243
244 /**
245 * Convenience function to remove all the data sets from a graph
246 */
247 DygraphLayout.prototype.removeAllDatasets = function() {
248 delete this.datasets;
249 this.datasets = new Array();
250 };
251
252 /**
253 * Return a copy of the point at the indicated index, with its yval unstacked.
254 * @param int index of point in layout_.points
255 */
256 DygraphLayout.prototype.unstackPointAtIndex = function(idx) {
257 var point = this.points[idx];
258
259 // Clone the point since we modify it
260 var unstackedPoint = {};
261 for (var i in point) {
262 unstackedPoint[i] = point[i];
263 }
264
265 if (!this.attr_("stackedGraph")) {
266 return unstackedPoint;
267 }
268
269 // The unstacked yval is equal to the current yval minus the yval of the
270 // next point at the same xval.
271 for (var i = idx+1; i < this.points.length; i++) {
272 if (this.points[i].xval == point.xval) {
273 unstackedPoint.yval -= this.points[i].yval;
274 break;
275 }
276 }
277
278 return unstackedPoint;
279 }
280
281 /**
282 * The DygraphCanvasRenderer class does the actual rendering of the chart onto
283 * a canvas. It's based on PlotKit.CanvasRenderer.
284 * @param {Object} element The canvas to attach to
285 * @param {Object} elementContext The 2d context of the canvas (injected so it
286 * can be mocked for testing.)
287 * @param {Layout} layout The DygraphLayout object for this graph.
288 */
289 DygraphCanvasRenderer = function(dygraph, element, elementContext, layout) {
290 this.dygraph_ = dygraph;
291
292 this.layout = layout;
293 this.element = element;
294 this.elementContext = elementContext;
295 this.container = this.element.parentNode;
296
297 this.height = this.element.height;
298 this.width = this.element.width;
299
300 // --- check whether everything is ok before we return
301 if (!this.isIE && !(DygraphCanvasRenderer.isSupported(this.element)))
302 throw "Canvas is not supported.";
303
304 // internal state
305 this.xlabels = new Array();
306 this.ylabels = new Array();
307 this.annotations = new Array();
308 this.chartLabels = {};
309
310 this.area = this.computeArea_();
311 this.container.style.position = "relative";
312 this.container.style.width = this.width + "px";
313
314 // Set up a clipping area for the canvas (and the interaction canvas).
315 // This ensures that we don't overdraw.
316 var ctx = this.dygraph_.canvas_ctx_;
317 ctx.beginPath();
318 ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h);
319 ctx.clip();
320
321 ctx = this.dygraph_.hidden_ctx_;
322 ctx.beginPath();
323 ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h);
324 ctx.clip();
325 };
326
327 DygraphCanvasRenderer.prototype.attr_ = function(x) {
328 return this.dygraph_.attr_(x);
329 };
330
331 // Compute the box which the chart should be drawn in. This is the canvas's
332 // box, less space needed for axis and chart labels.
333 // TODO(danvk): this belongs in DygraphLayout.
334 DygraphCanvasRenderer.prototype.computeArea_ = function() {
335 var area = {
336 // TODO(danvk): per-axis setting.
337 x: this.attr_('yAxisLabelWidth') + 2 * this.attr_('axisTickSize'),
338 y: 0
339 };
340 area.w = this.width - area.x - this.attr_('rightGap');
341 area.h = this.height - this.attr_('axisLabelFontSize') -
342 2 * this.attr_('axisTickSize');
343
344 // Shrink the drawing area to accomodate additional y-axes.
345 if (this.dygraph_.numAxes() == 2) {
346 // TODO(danvk): per-axis setting.
347 area.w -= (this.attr_('yAxisLabelWidth') + 2 * this.attr_('axisTickSize'));
348 } else if (this.dygraph_.numAxes() > 2) {
349 this.dygraph_.error("Only two y-axes are supported at this time. (Trying " +
350 "to use " + this.dygraph_.numAxes() + ")");
351 }
352
353 // Add space for chart labels: title, xlabel and ylabel.
354 if (this.attr_('title')) {
355 area.h -= this.attr_('titleHeight');
356 area.y += this.attr_('titleHeight');
357 }
358 if (this.attr_('xlabel')) {
359 area.h -= this.attr_('xLabelHeight');
360 }
361 if (this.attr_('ylabel')) {
362 // It would make sense to shift the chart here to make room for the y-axis
363 // label, but the default yAxisLabelWidth is large enough that this results
364 // in overly-padded charts. The y-axis label should fit fine. If it
365 // doesn't, the yAxisLabelWidth option can be increased.
366 }
367
368 return area;
369 };
370
371 DygraphCanvasRenderer.prototype.clear = function() {
372 if (this.isIE) {
373 // VML takes a while to start up, so we just poll every this.IEDelay
374 try {
375 if (this.clearDelay) {
376 this.clearDelay.cancel();
377 this.clearDelay = null;
378 }
379 var context = this.elementContext;
380 }
381 catch (e) {
382 // TODO(danvk): this is broken, since MochiKit.Async is gone.
383 this.clearDelay = MochiKit.Async.wait(this.IEDelay);
384 this.clearDelay.addCallback(bind(this.clear, this));
385 return;
386 }
387 }
388
389 var context = this.elementContext;
390 context.clearRect(0, 0, this.width, this.height);
391
392 for (var i = 0; i < this.xlabels.length; i++) {
393 var el = this.xlabels[i];
394 if (el.parentNode) el.parentNode.removeChild(el);
395 }
396 for (var i = 0; i < this.ylabels.length; i++) {
397 var el = this.ylabels[i];
398 if (el.parentNode) el.parentNode.removeChild(el);
399 }
400 for (var i = 0; i < this.annotations.length; i++) {
401 var el = this.annotations[i];
402 if (el.parentNode) el.parentNode.removeChild(el);
403 }
404 for (var k in this.chartLabels) {
405 if (!this.chartLabels.hasOwnProperty(k)) continue;
406 var el = this.chartLabels[k];
407 if (el.parentNode) el.parentNode.removeChild(el);
408 }
409 this.xlabels = new Array();
410 this.ylabels = new Array();
411 this.annotations = new Array();
412 this.chartLabels = {};
413 };
414
415
416 DygraphCanvasRenderer.isSupported = function(canvasName) {
417 var canvas = null;
418 try {
419 if (typeof(canvasName) == 'undefined' || canvasName == null)
420 canvas = document.createElement("canvas");
421 else
422 canvas = canvasName;
423 var context = canvas.getContext("2d");
424 }
425 catch (e) {
426 var ie = navigator.appVersion.match(/MSIE (\d\.\d)/);
427 var opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
428 if ((!ie) || (ie[1] < 6) || (opera))
429 return false;
430 return true;
431 }
432 return true;
433 };
434
435 /**
436 * @param { [String] } colors Array of color strings. Should have one entry for
437 * each series to be rendered.
438 */
439 DygraphCanvasRenderer.prototype.setColors = function(colors) {
440 this.colorScheme_ = colors;
441 };
442
443 /**
444 * Draw an X/Y grid on top of the existing plot
445 */
446 DygraphCanvasRenderer.prototype.render = function() {
447 // Draw the new X/Y grid. Lines appear crisper when pixels are rounded to
448 // half-integers. This prevents them from drawing in two rows/cols.
449 var ctx = this.elementContext;
450 function halfUp(x){return Math.round(x)+0.5};
451 function halfDown(y){return Math.round(y)-0.5};
452
453 if (this.attr_('underlayCallback')) {
454 // NOTE: we pass the dygraph object to this callback twice to avoid breaking
455 // users who expect a deprecated form of this callback.
456 this.attr_('underlayCallback')(ctx, this.area, this.dygraph_, this.dygraph_);
457 }
458
459 if (this.attr_('drawYGrid')) {
460 var ticks = this.layout.yticks;
461 ctx.save();
462 ctx.strokeStyle = this.attr_('gridLineColor');
463 ctx.lineWidth = this.attr_('axisLineWidth');
464 for (var i = 0; i < ticks.length; i++) {
465 // TODO(danvk): allow secondary axes to draw a grid, too.
466 if (ticks[i][0] != 0) continue;
467 var x = halfUp(this.area.x);
468 var y = halfDown(this.area.y + ticks[i][1] * this.area.h);
469 ctx.beginPath();
470 ctx.moveTo(x, y);
471 ctx.lineTo(x + this.area.w, y);
472 ctx.closePath();
473 ctx.stroke();
474 }
475 }
476
477 if (this.attr_('drawXGrid')) {
478 var ticks = this.layout.xticks;
479 ctx.save();
480 ctx.strokeStyle = this.attr_('gridLineColor');
481 ctx.lineWidth = this.attr_('axisLineWidth');
482 for (var i=0; i<ticks.length; i++) {
483 var x = halfUp(this.area.x + ticks[i][0] * this.area.w);
484 var y = halfDown(this.area.y + this.area.h);
485 ctx.beginPath();
486 ctx.moveTo(x, y);
487 ctx.lineTo(x, this.area.y);
488 ctx.closePath();
489 ctx.stroke();
490 }
491 }
492
493 // Do the ordinary rendering, as before
494 this._renderLineChart();
495 this._renderAxis();
496 this._renderChartLabels();
497 this._renderAnnotations();
498 };
499
500
501 DygraphCanvasRenderer.prototype._renderAxis = function() {
502 if (!this.attr_('drawXAxis') && !this.attr_('drawYAxis')) 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.elementContext;
509
510 var labelStyle = {
511 position: "absolute",
512 fontSize: this.attr_('axisLabelFontSize') + "px",
513 zIndex: 10,
514 color: this.attr_('axisLabelColor'),
515 width: this.attr_('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.attr_('axisLineColor');
532 context.lineWidth = this.attr_('axisLineWidth');
533
534 if (this.attr_('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.attr_('axisTickSize')), halfDown(y));
549 context.closePath();
550 context.stroke();
551
552 var label = makeDiv(tick[2]);
553 var top = (y - this.attr_('axisLabelFontSize') / 2);
554 if (top < 0) top = 0;
555
556 if (top + this.attr_('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.attr_('yAxisLabelWidth') - this.attr_('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.attr_('axisTickSize')) + "px";
567 label.style.textAlign = "left";
568 }
569 label.style.width = this.attr_('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.attr_('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.attr_('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.attr_('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.attr_('axisTickSize')) + 'px';
620
621 var left = (x - this.attr_('axisLabelWidth')/2);
622 if (left + this.attr_('axisLabelWidth') > this.width) {
623 left = this.width - this.attr_('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.attr_('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.attr_('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.elementContext;
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.elementContext;
848 var fillAlpha = this.attr_('fillAlpha');
849 var errorBars = this.attr_("errorBars");
850 var fillGraph = this.attr_("fillGraph");
851 var stackedGraph = this.attr_("stackedGraph");
852 var stepPlot = this.attr_("stepPlot");
853
854 var setNames = [];
855 for (var name in this.layout.datasets) {
856 if (this.layout.datasets.hasOwnProperty(name)) {
857 setNames.push(name);
858 }
859 }
860 var setCount = setNames.length;
861
862 // TODO(danvk): Move this mapping into Dygraph and get it out of here.
863 this.colors = {}
864 for (var i = 0; i < setCount; i++) {
865 this.colors[setNames[i]] = this.colorScheme_[i % this.colorScheme_.length];
866 }
867
868 // Update Points
869 // TODO(danvk): here
870 for (var i = 0; i < this.layout.points.length; i++) {
871 var point = this.layout.points[i];
872 point.canvasx = this.area.w * point.x + this.area.x;
873 point.canvasy = this.area.h * point.y + this.area.y;
874 }
875
876 // create paths
877 var ctx = context;
878 if (errorBars) {
879 if (fillGraph) {
880 this.dygraph_.warn("Can't use fillGraph option with error bars");
881 }
882
883 for (var i = 0; i < setCount; i++) {
884 var setName = setNames[i];
885 var axis = this.dygraph_.axisPropertiesForSeries(setName);
886 var color = this.colors[setName];
887
888 // setup graphics context
889 ctx.save();
890 var prevX = NaN;
891 var prevY = NaN;
892 var prevYs = [-1, -1];
893 var yscale = axis.yscale;
894 // should be same color as the lines but only 15% opaque.
895 var rgb = new RGBColor(color);
896 var err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
897 fillAlpha + ')';
898 ctx.fillStyle = err_color;
899 ctx.beginPath();
900 for (var j = 0; j < this.layout.points.length; j++) {
901 var point = this.layout.points[j];
902 if (point.name == setName) {
903 if (!Dygraph.isOK(point.y)) {
904 prevX = NaN;
905 continue;
906 }
907
908 // TODO(danvk): here
909 if (stepPlot) {
910 var newYs = [ prevY - point.errorPlus * yscale,
911 prevY + point.errorMinus * yscale ];
912 prevY = point.y;
913 } else {
914 var newYs = [ point.y - point.errorPlus * yscale,
915 point.y + point.errorMinus * yscale ];
916 }
917 newYs[0] = this.area.h * newYs[0] + this.area.y;
918 newYs[1] = this.area.h * newYs[1] + this.area.y;
919 if (!isNaN(prevX)) {
920 if (stepPlot) {
921 ctx.moveTo(prevX, newYs[0]);
922 } else {
923 ctx.moveTo(prevX, prevYs[0]);
924 }
925 ctx.lineTo(point.canvasx, newYs[0]);
926 ctx.lineTo(point.canvasx, newYs[1]);
927 if (stepPlot) {
928 ctx.lineTo(prevX, newYs[1]);
929 } else {
930 ctx.lineTo(prevX, prevYs[1]);
931 }
932 ctx.closePath();
933 }
934 prevYs = newYs;
935 prevX = point.canvasx;
936 }
937 }
938 ctx.fill();
939 }
940 } else if (fillGraph) {
941 var baseline = [] // for stacked graphs: baseline for filling
942
943 // process sets in reverse order (needed for stacked graphs)
944 for (var i = setCount - 1; i >= 0; i--) {
945 var setName = setNames[i];
946 var color = this.colors[setName];
947 var axis = this.dygraph_.axisPropertiesForSeries(setName);
948 var axisY = 1.0 + axis.minyval * axis.yscale;
949 if (axisY < 0.0) axisY = 0.0;
950 else if (axisY > 1.0) axisY = 1.0;
951 axisY = this.area.h * axisY + this.area.y;
952
953 // setup graphics context
954 ctx.save();
955 var prevX = NaN;
956 var prevYs = [-1, -1];
957 var yscale = axis.yscale;
958 // should be same color as the lines but only 15% opaque.
959 var rgb = new RGBColor(color);
960 var err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
961 fillAlpha + ')';
962 ctx.fillStyle = err_color;
963 ctx.beginPath();
964 for (var j = 0; j < this.layout.points.length; j++) {
965 var point = this.layout.points[j];
966 if (point.name == setName) {
967 if (!Dygraph.isOK(point.y)) {
968 prevX = NaN;
969 continue;
970 }
971 var newYs;
972 if (stackedGraph) {
973 lastY = baseline[point.canvasx];
974 if (lastY === undefined) lastY = axisY;
975 baseline[point.canvasx] = point.canvasy;
976 newYs = [ point.canvasy, lastY ];
977 } else {
978 newYs = [ point.canvasy, axisY ];
979 }
980 if (!isNaN(prevX)) {
981 ctx.moveTo(prevX, prevYs[0]);
982 if (stepPlot) {
983 ctx.lineTo(point.canvasx, prevYs[0]);
984 } else {
985 ctx.lineTo(point.canvasx, newYs[0]);
986 }
987 ctx.lineTo(point.canvasx, newYs[1]);
988 ctx.lineTo(prevX, prevYs[1]);
989 ctx.closePath();
990 }
991 prevYs = newYs;
992 prevX = point.canvasx;
993 }
994 }
995 ctx.fill();
996 }
997 }
998
999 for (var i = 0; i < setCount; i++) {
1000 var setName = setNames[i];
1001 var color = this.colors[setName];
1002 var strokeWidth = this.dygraph_.attr_("strokeWidth", setName);
1003
1004 // setup graphics context
1005 context.save();
1006 var point = this.layout.points[0];
1007 var pointSize = this.dygraph_.attr_("pointSize", setName);
1008 var prevX = null, prevY = null;
1009 var drawPoints = this.dygraph_.attr_("drawPoints", setName);
1010 var points = this.layout.points;
1011 for (var j = 0; j < points.length; j++) {
1012 var point = points[j];
1013 if (point.name == setName) {
1014 if (!Dygraph.isOK(point.canvasy)) {
1015 if (stepPlot && prevX != null) {
1016 // Draw a horizontal line to the start of the missing data
1017 ctx.beginPath();
1018 ctx.strokeStyle = color;
1019 ctx.lineWidth = this.attr_('strokeWidth');
1020 ctx.moveTo(prevX, prevY);
1021 ctx.lineTo(point.canvasx, prevY);
1022 ctx.stroke();
1023 }
1024 // this will make us move to the next point, not draw a line to it.
1025 prevX = prevY = null;
1026 } else {
1027 // A point is "isolated" if it is non-null but both the previous
1028 // and next points are null.
1029 var isIsolated = (!prevX && (j == points.length - 1 ||
1030 !Dygraph.isOK(points[j+1].canvasy)));
1031
1032 if (!prevX) {
1033 prevX = point.canvasx;
1034 prevY = point.canvasy;
1035 } else {
1036 // TODO(danvk): figure out why this conditional is necessary.
1037 if (strokeWidth) {
1038 ctx.beginPath();
1039 ctx.strokeStyle = color;
1040 ctx.lineWidth = strokeWidth;
1041 ctx.moveTo(prevX, prevY);
1042 if (stepPlot) {
1043 ctx.lineTo(point.canvasx, prevY);
1044 }
1045 prevX = point.canvasx;
1046 prevY = point.canvasy;
1047 ctx.lineTo(prevX, prevY);
1048 ctx.stroke();
1049 }
1050 }
1051
1052 if (drawPoints || isIsolated) {
1053 ctx.beginPath();
1054 ctx.fillStyle = color;
1055 ctx.arc(point.canvasx, point.canvasy, pointSize,
1056 0, 2 * Math.PI, false);
1057 ctx.fill();
1058 }
1059 }
1060 }
1061 }
1062 }
1063
1064 context.restore();
1065 };