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