merge in kberg changes
[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, this.dygraph_);
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: 0,
338 y: 0
339 };
340 if (this.attr_('drawYAxis')) {
341 area.x = this.attr_('yAxisLabelWidth') + 2 * this.attr_('axisTickSize');
342 }
343
344 area.w = this.width - area.x - this.attr_('rightGap');
345 area.h = this.height;
346 if (this.attr_('drawXAxis')) {
347 if (this.attr_('xAxisHeight')) {
348 area.h -= this.attr_('xAxisHeight');
349 } else {
350 area.h -= this.attr_('axisLabelFontSize') + 2 * this.attr_('axisTickSize');
351 }
352 }
353
354 // Shrink the drawing area to accomodate additional y-axes.
355 if (this.dygraph_.numAxes() == 2) {
356 // TODO(danvk): per-axis setting.
357 area.w -= (this.attr_('yAxisLabelWidth') + 2 * this.attr_('axisTickSize'));
358 } else if (this.dygraph_.numAxes() > 2) {
359 this.dygraph_.error("Only two y-axes are supported at this time. (Trying " +
360 "to use " + this.dygraph_.numAxes() + ")");
361 }
362
363 // Add space for chart labels: title, xlabel and ylabel.
364 if (this.attr_('title')) {
365 area.h -= this.attr_('titleHeight');
366 area.y += this.attr_('titleHeight');
367 }
368 if (this.attr_('xlabel')) {
369 area.h -= this.attr_('xLabelHeight');
370 }
371 if (this.attr_('ylabel')) {
372 // It would make sense to shift the chart here to make room for the y-axis
373 // label, but the default yAxisLabelWidth is large enough that this results
374 // in overly-padded charts. The y-axis label should fit fine. If it
375 // doesn't, the yAxisLabelWidth option can be increased.
376 }
377
378 return area;
379 };
380
381 DygraphCanvasRenderer.prototype.clear = function() {
382 if (this.isIE) {
383 // VML takes a while to start up, so we just poll every this.IEDelay
384 try {
385 if (this.clearDelay) {
386 this.clearDelay.cancel();
387 this.clearDelay = null;
388 }
389 var context = this.elementContext;
390 }
391 catch (e) {
392 // TODO(danvk): this is broken, since MochiKit.Async is gone.
393 this.clearDelay = MochiKit.Async.wait(this.IEDelay);
394 this.clearDelay.addCallback(bind(this.clear, this));
395 return;
396 }
397 }
398
399 var context = this.elementContext;
400 context.clearRect(0, 0, this.width, this.height);
401
402 for (var i = 0; i < this.xlabels.length; i++) {
403 var el = this.xlabels[i];
404 if (el.parentNode) el.parentNode.removeChild(el);
405 }
406 for (var i = 0; i < this.ylabels.length; i++) {
407 var el = this.ylabels[i];
408 if (el.parentNode) el.parentNode.removeChild(el);
409 }
410 for (var i = 0; i < this.annotations.length; i++) {
411 var el = this.annotations[i];
412 if (el.parentNode) el.parentNode.removeChild(el);
413 }
414 for (var k in this.chartLabels) {
415 if (!this.chartLabels.hasOwnProperty(k)) continue;
416 var el = this.chartLabels[k];
417 if (el.parentNode) el.parentNode.removeChild(el);
418 }
419 this.xlabels = new Array();
420 this.ylabels = new Array();
421 this.annotations = new Array();
422 this.chartLabels = {};
423 };
424
425
426 DygraphCanvasRenderer.isSupported = function(canvasName) {
427 var canvas = null;
428 try {
429 if (typeof(canvasName) == 'undefined' || canvasName == null)
430 canvas = document.createElement("canvas");
431 else
432 canvas = canvasName;
433 var context = canvas.getContext("2d");
434 }
435 catch (e) {
436 var ie = navigator.appVersion.match(/MSIE (\d\.\d)/);
437 var opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
438 if ((!ie) || (ie[1] < 6) || (opera))
439 return false;
440 return true;
441 }
442 return true;
443 };
444
445 /**
446 * @param { [String] } colors Array of color strings. Should have one entry for
447 * each series to be rendered.
448 */
449 DygraphCanvasRenderer.prototype.setColors = function(colors) {
450 this.colorScheme_ = colors;
451 };
452
453 /**
454 * Draw an X/Y grid on top of the existing plot
455 */
456 DygraphCanvasRenderer.prototype.render = function() {
457 // Draw the new X/Y grid. Lines appear crisper when pixels are rounded to
458 // half-integers. This prevents them from drawing in two rows/cols.
459 var ctx = this.elementContext;
460 function halfUp(x){return Math.round(x)+0.5};
461 function halfDown(y){return Math.round(y)-0.5};
462
463 if (this.attr_('underlayCallback')) {
464 // NOTE: we pass the dygraph object to this callback twice to avoid breaking
465 // users who expect a deprecated form of this callback.
466 this.attr_('underlayCallback')(ctx, this.area, this.dygraph_, this.dygraph_);
467 }
468
469 if (this.attr_('drawYGrid')) {
470 var ticks = this.layout.yticks;
471 ctx.save();
472 ctx.strokeStyle = this.attr_('gridLineColor');
473 ctx.lineWidth = this.attr_('gridLineWidth');
474 for (var i = 0; i < ticks.length; i++) {
475 // TODO(danvk): allow secondary axes to draw a grid, too.
476 if (ticks[i][0] != 0) continue;
477 var x = halfUp(this.area.x);
478 var y = halfDown(this.area.y + ticks[i][1] * this.area.h);
479 ctx.beginPath();
480 ctx.moveTo(x, y);
481 ctx.lineTo(x + this.area.w, y);
482 ctx.closePath();
483 ctx.stroke();
484 }
485 }
486
487 if (this.attr_('drawXGrid')) {
488 var ticks = this.layout.xticks;
489 ctx.save();
490 ctx.strokeStyle = this.attr_('gridLineColor');
491 ctx.lineWidth = this.attr_('gridLineWidth');
492 for (var i=0; i<ticks.length; i++) {
493 var x = halfUp(this.area.x + ticks[i][0] * this.area.w);
494 var y = halfDown(this.area.y + this.area.h);
495 ctx.beginPath();
496 ctx.moveTo(x, y);
497 ctx.lineTo(x, this.area.y);
498 ctx.closePath();
499 ctx.stroke();
500 }
501 }
502
503 // Do the ordinary rendering, as before
504 this._renderLineChart();
505 this._renderAxis();
506 this._renderChartLabels();
507 this._renderAnnotations();
508 };
509
510
511 DygraphCanvasRenderer.prototype._renderAxis = function() {
512 if (!this.attr_('drawXAxis') && !this.attr_('drawYAxis')) return;
513
514 // Round pixels to half-integer boundaries for crisper drawing.
515 function halfUp(x){return Math.round(x)+0.5};
516 function halfDown(y){return Math.round(y)-0.5};
517
518 var context = this.elementContext;
519
520 var labelStyle = {
521 position: "absolute",
522 fontSize: this.attr_('axisLabelFontSize') + "px",
523 zIndex: 10,
524 color: this.attr_('axisLabelColor'),
525 width: this.attr_('axisLabelWidth') + "px",
526 overflow: "hidden"
527 };
528 var makeDiv = function(txt, axis) {
529 var div = document.createElement("div");
530 for (var name in labelStyle) {
531 if (labelStyle.hasOwnProperty(name)) {
532 div.style[name] = labelStyle[name];
533 }
534 }
535 var inner_div = document.createElement("div");
536 // TODO(danvk): separate class for secondary y-axis
537 inner_div.className = 'dygraph-axis-label dygraph-axis-label-' + axis;
538 inner_div.appendChild(document.createTextNode(txt));
539 div.appendChild(inner_div);
540 return div;
541 };
542
543 // axis lines
544 context.save();
545 context.strokeStyle = this.attr_('axisLineColor');
546 context.lineWidth = this.attr_('axisLineWidth');
547
548 if (this.attr_('drawYAxis')) {
549 if (this.layout.yticks && this.layout.yticks.length > 0) {
550 for (var i = 0; i < this.layout.yticks.length; i++) {
551 var tick = this.layout.yticks[i];
552 if (typeof(tick) == "function") return;
553 var x = this.area.x;
554 var sgn = 1;
555 if (tick[0] == 1) { // right-side y-axis
556 x = this.area.x + this.area.w;
557 sgn = -1;
558 }
559 var y = this.area.y + tick[1] * this.area.h;
560 context.beginPath();
561 context.moveTo(halfUp(x), halfDown(y));
562 context.lineTo(halfUp(x - sgn * this.attr_('axisTickSize')), halfDown(y));
563 context.closePath();
564 context.stroke();
565
566 var label = makeDiv(tick[2], 'y');
567 var top = (y - this.attr_('axisLabelFontSize') / 2);
568 if (top < 0) top = 0;
569
570 if (top + this.attr_('axisLabelFontSize') + 3 > this.height) {
571 label.style.bottom = "0px";
572 } else {
573 label.style.top = top + "px";
574 }
575 if (tick[0] == 0) {
576 label.style.left = (this.area.x - this.attr_('yAxisLabelWidth') - this.attr_('axisTickSize')) + "px";
577 label.style.textAlign = "right";
578 } else if (tick[0] == 1) {
579 label.style.left = (this.area.x + this.area.w +
580 this.attr_('axisTickSize')) + "px";
581 label.style.textAlign = "left";
582 }
583 label.style.width = this.attr_('yAxisLabelWidth') + "px";
584 this.container.appendChild(label);
585 this.ylabels.push(label);
586 }
587
588 // The lowest tick on the y-axis often overlaps with the leftmost
589 // tick on the x-axis. Shift the bottom tick up a little bit to
590 // compensate if necessary.
591 var bottomTick = this.ylabels[0];
592 var fontSize = this.attr_('axisLabelFontSize');
593 var bottom = parseInt(bottomTick.style.top) + fontSize;
594 if (bottom > this.height - fontSize) {
595 bottomTick.style.top = (parseInt(bottomTick.style.top) -
596 fontSize / 2) + "px";
597 }
598 }
599
600 // draw a vertical line on the left to separate the chart from the labels.
601 context.beginPath();
602 context.moveTo(halfUp(this.area.x), halfDown(this.area.y));
603 context.lineTo(halfUp(this.area.x), halfDown(this.area.y + this.area.h));
604 context.closePath();
605 context.stroke();
606
607 // if there's a secondary y-axis, draw a vertical line for that, too.
608 if (this.dygraph_.numAxes() == 2) {
609 context.beginPath();
610 context.moveTo(halfDown(this.area.x + this.area.w), halfDown(this.area.y));
611 context.lineTo(halfDown(this.area.x + this.area.w), halfDown(this.area.y + this.area.h));
612 context.closePath();
613 context.stroke();
614 }
615 }
616
617 if (this.attr_('drawXAxis')) {
618 if (this.layout.xticks) {
619 for (var i = 0; i < this.layout.xticks.length; i++) {
620 var tick = this.layout.xticks[i];
621 if (typeof(dataset) == "function") return;
622
623 var x = this.area.x + tick[0] * this.area.w;
624 var y = this.area.y + this.area.h;
625 context.beginPath();
626 context.moveTo(halfUp(x), halfDown(y));
627 context.lineTo(halfUp(x), halfDown(y + this.attr_('axisTickSize')));
628 context.closePath();
629 context.stroke();
630
631 var label = makeDiv(tick[1], 'x');
632 label.style.textAlign = "center";
633 label.style.top = (y + this.attr_('axisTickSize')) + 'px';
634
635 var left = (x - this.attr_('axisLabelWidth')/2);
636 if (left + this.attr_('axisLabelWidth') > this.width) {
637 left = this.width - this.attr_('xAxisLabelWidth');
638 label.style.textAlign = "right";
639 }
640 if (left < 0) {
641 left = 0;
642 label.style.textAlign = "left";
643 }
644
645 label.style.left = left + "px";
646 label.style.width = this.attr_('xAxisLabelWidth') + "px";
647 this.container.appendChild(label);
648 this.xlabels.push(label);
649 }
650 }
651
652 context.beginPath();
653 context.moveTo(halfUp(this.area.x), halfDown(this.area.y + this.area.h));
654 context.lineTo(halfUp(this.area.x + this.area.w), halfDown(this.area.y + this.area.h));
655 context.closePath();
656 context.stroke();
657 }
658
659 context.restore();
660 };
661
662
663 DygraphCanvasRenderer.prototype._renderChartLabels = function() {
664 // Generate divs for the chart title, xlabel and ylabel.
665 // Space for these divs has already been taken away from the charting area in
666 // the DygraphCanvasRenderer constructor.
667 if (this.attr_('title')) {
668 var div = document.createElement("div");
669 div.style.position = 'absolute';
670 div.style.top = '0px';
671 div.style.left = this.area.x + 'px';
672 div.style.width = this.area.w + 'px';
673 div.style.height = this.attr_('titleHeight') + 'px';
674 div.style.textAlign = 'center';
675 div.style.fontSize = (this.attr_('titleHeight') - 8) + 'px';
676 div.style.fontWeight = 'bold';
677 var class_div = document.createElement("div");
678 class_div.className = 'dygraph-label dygraph-title';
679 class_div.innerHTML = this.attr_('title');
680 div.appendChild(class_div);
681 this.container.appendChild(div);
682 this.chartLabels.title = div;
683 }
684
685 if (this.attr_('xlabel')) {
686 var div = document.createElement("div");
687 div.style.position = 'absolute';
688 div.style.bottom = 0; // TODO(danvk): this is lazy. Calculate style.top.
689 div.style.left = this.area.x + 'px';
690 div.style.width = this.area.w + 'px';
691 div.style.height = this.attr_('xLabelHeight') + 'px';
692 div.style.textAlign = 'center';
693 div.style.fontSize = (this.attr_('xLabelHeight') - 2) + 'px';
694
695 var class_div = document.createElement("div");
696 class_div.className = 'dygraph-label dygraph-xlabel';
697 class_div.innerHTML = this.attr_('xlabel');
698 div.appendChild(class_div);
699 this.container.appendChild(div);
700 this.chartLabels.xlabel = div;
701 }
702
703 if (this.attr_('ylabel')) {
704 var box = {
705 left: 0,
706 top: this.area.y,
707 width: this.attr_('yLabelWidth'),
708 height: this.area.h
709 };
710 // TODO(danvk): is this outer div actually necessary?
711 var div = document.createElement("div");
712 div.style.position = 'absolute';
713 div.style.left = box.left;
714 div.style.top = box.top + 'px';
715 div.style.width = box.width + 'px';
716 div.style.height = box.height + 'px';
717 div.style.fontSize = (this.attr_('yLabelWidth') - 2) + 'px';
718
719 var inner_div = document.createElement("div");
720 inner_div.style.position = 'absolute';
721 inner_div.style.width = box.height + 'px';
722 inner_div.style.height = box.width + 'px';
723 inner_div.style.top = (box.height / 2 - box.width / 2) + 'px';
724 inner_div.style.left = (box.width / 2 - box.height / 2) + 'px';
725 inner_div.style.textAlign = 'center';
726
727 // CSS rotation is an HTML5 feature which is not standardized. Hence every
728 // browser has its own name for the CSS style.
729 inner_div.style.transform = 'rotate(-90deg)'; // HTML5
730 inner_div.style.WebkitTransform = 'rotate(-90deg)'; // Safari/Chrome
731 inner_div.style.MozTransform = 'rotate(-90deg)'; // Firefox
732 inner_div.style.OTransform = 'rotate(-90deg)'; // Opera
733 inner_div.style.msTransform = 'rotate(-90deg)'; // IE9
734
735 if (typeof(document.documentMode) !== 'undefined' &&
736 document.documentMode < 9) {
737 // We're dealing w/ an old version of IE, so we have to rotate the text
738 // using a BasicImage transform. This uses a different origin of rotation
739 // than HTML5 rotation (top left of div vs. its center).
740 inner_div.style.filter =
741 'progid:DXImageTransform.Microsoft.BasicImage(rotation=3)';
742 inner_div.style.left = '0px';
743 inner_div.style.top = '0px';
744 }
745
746 var class_div = document.createElement("div");
747 class_div.className = 'dygraph-label dygraph-ylabel';
748 class_div.innerHTML = this.attr_('ylabel');
749
750 inner_div.appendChild(class_div);
751 div.appendChild(inner_div);
752 this.container.appendChild(div);
753 this.chartLabels.ylabel = div;
754 }
755 };
756
757
758 DygraphCanvasRenderer.prototype._renderAnnotations = function() {
759 var annotationStyle = {
760 "position": "absolute",
761 "fontSize": this.attr_('axisLabelFontSize') + "px",
762 "zIndex": 10,
763 "overflow": "hidden"
764 };
765
766 var bindEvt = function(eventName, classEventName, p, self) {
767 return function(e) {
768 var a = p.annotation;
769 if (a.hasOwnProperty(eventName)) {
770 a[eventName](a, p, self.dygraph_, e);
771 } else if (self.dygraph_.attr_(classEventName)) {
772 self.dygraph_.attr_(classEventName)(a, p, self.dygraph_,e );
773 }
774 };
775 }
776
777 // Get a list of point with annotations.
778 var points = this.layout.annotated_points;
779 for (var i = 0; i < points.length; i++) {
780 var p = points[i];
781 if (p.canvasx < this.area.x || p.canvasx > this.area.x + this.area.w) {
782 continue;
783 }
784
785 var a = p.annotation;
786 var tick_height = 6;
787 if (a.hasOwnProperty("tickHeight")) {
788 tick_height = a.tickHeight;
789 }
790
791 var div = document.createElement("div");
792 for (var name in annotationStyle) {
793 if (annotationStyle.hasOwnProperty(name)) {
794 div.style[name] = annotationStyle[name];
795 }
796 }
797 if (!a.hasOwnProperty('icon')) {
798 div.className = "dygraphDefaultAnnotation";
799 }
800 if (a.hasOwnProperty('cssClass')) {
801 div.className += " " + a.cssClass;
802 }
803
804 var width = a.hasOwnProperty('width') ? a.width : 16;
805 var height = a.hasOwnProperty('height') ? a.height : 16;
806 if (a.hasOwnProperty('icon')) {
807 var img = document.createElement("img");
808 img.src = a.icon;
809 img.width = width;
810 img.height = height;
811 div.appendChild(img);
812 } else if (p.annotation.hasOwnProperty('shortText')) {
813 div.appendChild(document.createTextNode(p.annotation.shortText));
814 }
815 div.style.left = (p.canvasx - width / 2) + "px";
816 if (a.attachAtBottom) {
817 div.style.top = (this.area.h - height - tick_height) + "px";
818 } else {
819 div.style.top = (p.canvasy - height - tick_height) + "px";
820 }
821 div.style.width = width + "px";
822 div.style.height = height + "px";
823 div.title = p.annotation.text;
824 div.style.color = this.colors[p.name];
825 div.style.borderColor = this.colors[p.name];
826 a.div = div;
827
828 Dygraph.addEvent(div, 'click',
829 bindEvt('clickHandler', 'annotationClickHandler', p, this));
830 Dygraph.addEvent(div, 'mouseover',
831 bindEvt('mouseOverHandler', 'annotationMouseOverHandler', p, this));
832 Dygraph.addEvent(div, 'mouseout',
833 bindEvt('mouseOutHandler', 'annotationMouseOutHandler', p, this));
834 Dygraph.addEvent(div, 'dblclick',
835 bindEvt('dblClickHandler', 'annotationDblClickHandler', p, this));
836
837 this.container.appendChild(div);
838 this.annotations.push(div);
839
840 var ctx = this.elementContext;
841 ctx.strokeStyle = this.colors[p.name];
842 ctx.beginPath();
843 if (!a.attachAtBottom) {
844 ctx.moveTo(p.canvasx, p.canvasy);
845 ctx.lineTo(p.canvasx, p.canvasy - 2 - tick_height);
846 } else {
847 ctx.moveTo(p.canvasx, this.area.h);
848 ctx.lineTo(p.canvasx, this.area.h - 2 - tick_height);
849 }
850 ctx.closePath();
851 ctx.stroke();
852 }
853 };
854
855
856 /**
857 * Overrides the CanvasRenderer method to draw error bars
858 */
859 DygraphCanvasRenderer.prototype._renderLineChart = function() {
860 // TODO(danvk): use this.attr_ for many of these.
861 var context = this.elementContext;
862 var fillAlpha = this.attr_('fillAlpha');
863 var errorBars = this.attr_("errorBars") || this.attr_("customBars");
864 var fillGraph = this.attr_("fillGraph");
865 var stackedGraph = this.attr_("stackedGraph");
866 var stepPlot = this.attr_("stepPlot");
867
868 var setNames = [];
869 for (var name in this.layout.datasets) {
870 if (this.layout.datasets.hasOwnProperty(name)) {
871 setNames.push(name);
872 }
873 }
874 var setCount = setNames.length;
875
876 // TODO(danvk): Move this mapping into Dygraph and get it out of here.
877 this.colors = {}
878 for (var i = 0; i < setCount; i++) {
879 this.colors[setNames[i]] = this.colorScheme_[i % this.colorScheme_.length];
880 }
881
882 // Update Points
883 // TODO(danvk): here
884 for (var i = 0; i < this.layout.points.length; i++) {
885 var point = this.layout.points[i];
886 point.canvasx = this.area.w * point.x + this.area.x;
887 point.canvasy = this.area.h * point.y + this.area.y;
888 }
889
890 // create paths
891 var ctx = context;
892 if (errorBars) {
893 if (fillGraph) {
894 this.dygraph_.warn("Can't use fillGraph option with error bars");
895 }
896
897 for (var i = 0; i < setCount; i++) {
898 var setName = setNames[i];
899 var axis = this.dygraph_.axisPropertiesForSeries(setName);
900 var color = this.colors[setName];
901
902 // setup graphics context
903 ctx.save();
904 var prevX = NaN;
905 var prevY = NaN;
906 var prevYs = [-1, -1];
907 var yscale = axis.yscale;
908 // should be same color as the lines but only 15% opaque.
909 var rgb = new RGBColor(color);
910 var err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
911 fillAlpha + ')';
912 ctx.fillStyle = err_color;
913 ctx.beginPath();
914 for (var j = 0; j < this.layout.points.length; j++) {
915 var point = this.layout.points[j];
916 if (point.name == setName) {
917 if (!Dygraph.isOK(point.y)) {
918 prevX = NaN;
919 continue;
920 }
921
922 // TODO(danvk): here
923 if (stepPlot) {
924 var newYs = [ prevY - point.errorPlus * yscale,
925 prevY + point.errorMinus * yscale ];
926 prevY = point.y;
927 } else {
928 var newYs = [ point.y - point.errorPlus * yscale,
929 point.y + point.errorMinus * yscale ];
930 }
931 newYs[0] = this.area.h * newYs[0] + this.area.y;
932 newYs[1] = this.area.h * newYs[1] + this.area.y;
933 if (!isNaN(prevX)) {
934 if (stepPlot) {
935 ctx.moveTo(prevX, newYs[0]);
936 } else {
937 ctx.moveTo(prevX, prevYs[0]);
938 }
939 ctx.lineTo(point.canvasx, newYs[0]);
940 ctx.lineTo(point.canvasx, newYs[1]);
941 if (stepPlot) {
942 ctx.lineTo(prevX, newYs[1]);
943 } else {
944 ctx.lineTo(prevX, prevYs[1]);
945 }
946 ctx.closePath();
947 }
948 prevYs = newYs;
949 prevX = point.canvasx;
950 }
951 }
952 ctx.fill();
953 }
954 } else if (fillGraph) {
955 var baseline = [] // for stacked graphs: baseline for filling
956
957 // process sets in reverse order (needed for stacked graphs)
958 for (var i = setCount - 1; i >= 0; i--) {
959 var setName = setNames[i];
960 var color = this.colors[setName];
961 var axis = this.dygraph_.axisPropertiesForSeries(setName);
962 var axisY = 1.0 + axis.minyval * axis.yscale;
963 if (axisY < 0.0) axisY = 0.0;
964 else if (axisY > 1.0) axisY = 1.0;
965 axisY = this.area.h * axisY + this.area.y;
966
967 // setup graphics context
968 ctx.save();
969 var prevX = NaN;
970 var prevYs = [-1, -1];
971 var yscale = axis.yscale;
972 // should be same color as the lines but only 15% opaque.
973 var rgb = new RGBColor(color);
974 var err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
975 fillAlpha + ')';
976 ctx.fillStyle = err_color;
977 ctx.beginPath();
978 for (var j = 0; j < this.layout.points.length; j++) {
979 var point = this.layout.points[j];
980 if (point.name == setName) {
981 if (!Dygraph.isOK(point.y)) {
982 prevX = NaN;
983 continue;
984 }
985 var newYs;
986 if (stackedGraph) {
987 lastY = baseline[point.canvasx];
988 if (lastY === undefined) lastY = axisY;
989 baseline[point.canvasx] = point.canvasy;
990 newYs = [ point.canvasy, lastY ];
991 } else {
992 newYs = [ point.canvasy, axisY ];
993 }
994 if (!isNaN(prevX)) {
995 ctx.moveTo(prevX, prevYs[0]);
996 if (stepPlot) {
997 ctx.lineTo(point.canvasx, prevYs[0]);
998 } else {
999 ctx.lineTo(point.canvasx, newYs[0]);
1000 }
1001 ctx.lineTo(point.canvasx, newYs[1]);
1002 ctx.lineTo(prevX, prevYs[1]);
1003 ctx.closePath();
1004 }
1005 prevYs = newYs;
1006 prevX = point.canvasx;
1007 }
1008 }
1009 ctx.fill();
1010 }
1011 }
1012
1013 var isNullOrNaN = function(x) {
1014 return (x === null || isNaN(x));
1015 };
1016
1017 for (var i = 0; i < setCount; i++) {
1018 var setName = setNames[i];
1019 var color = this.colors[setName];
1020 var strokeWidth = this.dygraph_.attr_("strokeWidth", setName);
1021
1022 // setup graphics context
1023 context.save();
1024 var point = this.layout.points[0];
1025 var pointSize = this.dygraph_.attr_("pointSize", setName);
1026 var prevX = null, prevY = null;
1027 var drawPoints = this.dygraph_.attr_("drawPoints", setName);
1028 var points = this.layout.points;
1029 for (var j = 0; j < points.length; j++) {
1030 var point = points[j];
1031 if (point.name == setName) {
1032 if (isNullOrNaN(point.canvasy)) {
1033 if (stepPlot && prevX != null) {
1034 // Draw a horizontal line to the start of the missing data
1035 ctx.beginPath();
1036 ctx.strokeStyle = color;
1037 ctx.lineWidth = this.attr_('strokeWidth');
1038 ctx.moveTo(prevX, prevY);
1039 ctx.lineTo(point.canvasx, prevY);
1040 ctx.stroke();
1041 }
1042 // this will make us move to the next point, not draw a line to it.
1043 prevX = prevY = null;
1044 } else {
1045 // A point is "isolated" if it is non-null but both the previous
1046 // and next points are null.
1047 var isIsolated = (!prevX && (j == points.length - 1 ||
1048 isNullOrNaN(points[j+1].canvasy)));
1049
1050 if (prevX === null) {
1051 prevX = point.canvasx;
1052 prevY = point.canvasy;
1053 } else {
1054 // TODO(danvk): figure out why this conditional is necessary.
1055 if (strokeWidth) {
1056 ctx.beginPath();
1057 ctx.strokeStyle = color;
1058 ctx.lineWidth = strokeWidth;
1059 ctx.moveTo(prevX, prevY);
1060 if (stepPlot) {
1061 ctx.lineTo(point.canvasx, prevY);
1062 }
1063 prevX = point.canvasx;
1064 prevY = point.canvasy;
1065 ctx.lineTo(prevX, prevY);
1066 ctx.stroke();
1067 }
1068 }
1069
1070 if (drawPoints || isIsolated) {
1071 ctx.beginPath();
1072 ctx.fillStyle = color;
1073 ctx.arc(point.canvasx, point.canvasy, pointSize,
1074 0, 2 * Math.PI, false);
1075 ctx.fill();
1076 }
1077 }
1078 }
1079 }
1080 }
1081
1082 context.restore();
1083 };