synchronize demo
[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
12 /**
13 * Creates a new DygraphLayout object.
14 * @param {Object} options Options for PlotKit.Layout
15 * @return {Object} The DygraphLayout object
16 */
17 DygraphLayout = function(dygraph, options) {
18 this.dygraph_ = dygraph;
19 this.options = {}; // TODO(danvk): remove, use attr_ instead.
20 Dygraph.update(this.options, options ? options : {});
21 this.datasets = new Array();
22 };
23
24 DygraphLayout.prototype.attr_ = function(name) {
25 return this.dygraph_.attr_(name);
26 };
27
28 DygraphLayout.prototype.addDataset = function(setname, set_xy) {
29 this.datasets[setname] = set_xy;
30 };
31
32 DygraphLayout.prototype.evaluate = function() {
33 this._evaluateLimits();
34 this._evaluateLineCharts();
35 this._evaluateLineTicks();
36 };
37
38 DygraphLayout.prototype._evaluateLimits = function() {
39 this.minxval = this.maxxval = null;
40 if (this.options.dateWindow) {
41 this.minxval = this.options.dateWindow[0];
42 this.maxxval = this.options.dateWindow[1];
43 } else {
44 for (var name in this.datasets) {
45 if (!this.datasets.hasOwnProperty(name)) continue;
46 var series = this.datasets[name];
47 var x1 = series[0][0];
48 if (!this.minxval || x1 < this.minxval) this.minxval = x1;
49
50 var x2 = series[series.length - 1][0];
51 if (!this.maxxval || x2 > this.maxxval) this.maxxval = x2;
52 }
53 }
54 this.xrange = this.maxxval - this.minxval;
55 this.xscale = (this.xrange != 0 ? 1/this.xrange : 1.0);
56
57 this.minyval = this.options.yAxis[0];
58 this.maxyval = this.options.yAxis[1];
59 this.yrange = this.maxyval - this.minyval;
60 this.yscale = (this.yrange != 0 ? 1/this.yrange : 1.0);
61 };
62
63 DygraphLayout.prototype._evaluateLineCharts = function() {
64 // add all the rects
65 this.points = new Array();
66 for (var setName in this.datasets) {
67 if (!this.datasets.hasOwnProperty(setName)) continue;
68
69 var dataset = this.datasets[setName];
70 for (var j = 0; j < dataset.length; j++) {
71 var item = dataset[j];
72 var point = {
73 // TODO(danvk): here
74 x: ((parseFloat(item[0]) - this.minxval) * this.xscale),
75 y: 1.0 - ((parseFloat(item[1]) - this.minyval) * this.yscale),
76 xval: parseFloat(item[0]),
77 yval: parseFloat(item[1]),
78 name: setName
79 };
80
81 // limit the x, y values so they do not overdraw
82 if (point.y <= 0.0) {
83 point.y = 0.0;
84 }
85 if (point.y >= 1.0) {
86 point.y = 1.0;
87 }
88 if ((point.x >= 0.0) && (point.x <= 1.0)) {
89 this.points.push(point);
90 }
91 }
92 }
93 };
94
95 DygraphLayout.prototype._evaluateLineTicks = function() {
96 this.xticks = new Array();
97 for (var i = 0; i < this.options.xTicks.length; i++) {
98 var tick = this.options.xTicks[i];
99 var label = tick.label;
100 var pos = this.xscale * (tick.v - this.minxval);
101 if ((pos >= 0.0) && (pos <= 1.0)) {
102 this.xticks.push([pos, label]);
103 }
104 }
105
106 this.yticks = new Array();
107 for (var i = 0; i < this.options.yTicks.length; i++) {
108 var tick = this.options.yTicks[i];
109 var label = tick.label;
110 var pos = 1.0 - (this.yscale * (tick.v - this.minyval));
111 if ((pos >= 0.0) && (pos <= 1.0)) {
112 this.yticks.push([pos, label]);
113 }
114 }
115 };
116
117
118 /**
119 * Behaves the same way as PlotKit.Layout, but also copies the errors
120 * @private
121 */
122 DygraphLayout.prototype.evaluateWithError = function() {
123 this.evaluate();
124 if (!this.options.errorBars) return;
125
126 // Copy over the error terms
127 var i = 0; // index in this.points
128 for (var setName in this.datasets) {
129 if (!this.datasets.hasOwnProperty(setName)) continue;
130 var j = 0;
131 var dataset = this.datasets[setName];
132 for (var j = 0; j < dataset.length; j++, i++) {
133 var item = dataset[j];
134 var xv = parseFloat(item[0]);
135 var yv = parseFloat(item[1]);
136
137 if (xv == this.points[i].xval &&
138 yv == this.points[i].yval) {
139 this.points[i].errorMinus = parseFloat(item[2]);
140 this.points[i].errorPlus = parseFloat(item[3]);
141 }
142 }
143 }
144 };
145
146 /**
147 * Convenience function to remove all the data sets from a graph
148 */
149 DygraphLayout.prototype.removeAllDatasets = function() {
150 delete this.datasets;
151 this.datasets = new Array();
152 };
153
154 /**
155 * Change the values of various layout options
156 * @param {Object} new_options an associative array of new properties
157 */
158 DygraphLayout.prototype.updateOptions = function(new_options) {
159 Dygraph.update(this.options, new_options ? new_options : {});
160 };
161
162 // Subclass PlotKit.CanvasRenderer to add:
163 // 1. X/Y grid overlay
164 // 2. Ability to draw error bars (if required)
165
166 /**
167 * Sets some PlotKit.CanvasRenderer options
168 * @param {Object} element The canvas to attach to
169 * @param {Layout} layout The DygraphLayout object for this graph.
170 * @param {Object} options Options to pass on to CanvasRenderer
171 */
172 DygraphCanvasRenderer = function(dygraph, element, layout, options) {
173 // TODO(danvk): remove options, just use dygraph.attr_.
174 this.dygraph_ = dygraph;
175
176 // default options
177 this.options = {
178 "strokeWidth": 0.5,
179 "drawXAxis": true,
180 "drawYAxis": true,
181 "axisLineColor": "black",
182 "axisLineWidth": 0.5,
183 "axisTickSize": 3,
184 "axisLabelColor": "black",
185 "axisLabelFont": "Arial",
186 "axisLabelFontSize": 9,
187 "axisLabelWidth": 50,
188 "drawYGrid": true,
189 "drawXGrid": true,
190 "gridLineColor": "rgb(128,128,128)",
191 "fillAlpha": 0.15,
192 };
193 Dygraph.update(this.options, options);
194
195 this.layout = layout;
196 this.element = element;
197 this.container = this.element.parentNode;
198
199 this.height = this.element.height;
200 this.width = this.element.width;
201
202 // --- check whether everything is ok before we return
203 if (!this.isIE && !(DygraphCanvasRenderer.isSupported(this.element)))
204 throw "Canvas is not supported.";
205
206 // internal state
207 this.xlabels = new Array();
208 this.ylabels = new Array();
209
210 this.area = {
211 x: this.options.yAxisLabelWidth + 2 * this.options.axisTickSize,
212 y: 0
213 };
214 this.area.w = this.width - this.area.x - this.options.rightGap;
215 this.area.h = this.height - this.options.axisLabelFontSize -
216 2 * this.options.axisTickSize;
217
218 this.container.style.position = "relative";
219 this.container.style.width = this.width + "px";
220 };
221
222 DygraphCanvasRenderer.prototype.clear = function() {
223 if (this.isIE) {
224 // VML takes a while to start up, so we just poll every this.IEDelay
225 try {
226 if (this.clearDelay) {
227 this.clearDelay.cancel();
228 this.clearDelay = null;
229 }
230 var context = this.element.getContext("2d");
231 }
232 catch (e) {
233 // TODO(danvk): this is broken, since MochiKit.Async is gone.
234 this.clearDelay = MochiKit.Async.wait(this.IEDelay);
235 this.clearDelay.addCallback(bind(this.clear, this));
236 return;
237 }
238 }
239
240 var context = this.element.getContext("2d");
241 context.clearRect(0, 0, this.width, this.height);
242
243 for (var i = 0; i < this.xlabels.length; i++) {
244 var el = this.xlabels[i];
245 el.parentNode.removeChild(el);
246 }
247 for (var i = 0; i < this.ylabels.length; i++) {
248 var el = this.ylabels[i];
249 el.parentNode.removeChild(el);
250 }
251 this.xlabels = new Array();
252 this.ylabels = new Array();
253 };
254
255
256 DygraphCanvasRenderer.isSupported = function(canvasName) {
257 var canvas = null;
258 try {
259 if (typeof(canvasName) == 'undefined' || canvasName == null)
260 canvas = document.createElement("canvas");
261 else
262 canvas = canvasName;
263 var context = canvas.getContext("2d");
264 }
265 catch (e) {
266 var ie = navigator.appVersion.match(/MSIE (\d\.\d)/);
267 var opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
268 if ((!ie) || (ie[1] < 6) || (opera))
269 return false;
270 return true;
271 }
272 return true;
273 };
274
275 /**
276 * Draw an X/Y grid on top of the existing plot
277 */
278 DygraphCanvasRenderer.prototype.render = function() {
279 // Draw the new X/Y grid
280 var ctx = this.element.getContext("2d");
281 if (this.options.drawYGrid) {
282 var ticks = this.layout.yticks;
283 ctx.save();
284 ctx.strokeStyle = this.options.gridLineColor;
285 ctx.lineWidth = this.options.axisLineWidth;
286 for (var i = 0; i < ticks.length; i++) {
287 var x = this.area.x;
288 var y = this.area.y + ticks[i][0] * this.area.h;
289 ctx.beginPath();
290 ctx.moveTo(x, y);
291 ctx.lineTo(x + this.area.w, y);
292 ctx.closePath();
293 ctx.stroke();
294 }
295 }
296
297 if (this.options.drawXGrid) {
298 var ticks = this.layout.xticks;
299 ctx.save();
300 ctx.strokeStyle = this.options.gridLineColor;
301 ctx.lineWidth = this.options.axisLineWidth;
302 for (var i=0; i<ticks.length; i++) {
303 var x = this.area.x + ticks[i][0] * this.area.w;
304 var y = this.area.y + this.area.h;
305 ctx.beginPath();
306 ctx.moveTo(x, y);
307 ctx.lineTo(x, this.area.y);
308 ctx.closePath();
309 ctx.stroke();
310 }
311 }
312
313 // Do the ordinary rendering, as before
314 this._renderLineChart();
315 this._renderAxis();
316 };
317
318
319 DygraphCanvasRenderer.prototype._renderAxis = function() {
320 if (!this.options.drawXAxis && !this.options.drawYAxis)
321 return;
322
323 var context = this.element.getContext("2d");
324
325 var labelStyle = {
326 "position": "absolute",
327 "fontSize": this.options.axisLabelFontSize + "px",
328 "zIndex": 10,
329 "color": this.options.axisLabelColor,
330 "width": this.options.axisLabelWidth + "px",
331 "overflow": "hidden"
332 };
333 var makeDiv = function(txt) {
334 var div = document.createElement("div");
335 for (var name in labelStyle) {
336 if (labelStyle.hasOwnProperty(name)) {
337 div.style[name] = labelStyle[name];
338 }
339 }
340 div.appendChild(document.createTextNode(txt));
341 return div;
342 };
343
344 // axis lines
345 context.save();
346 context.strokeStyle = this.options.axisLineColor;
347 context.lineWidth = this.options.axisLineWidth;
348
349 if (this.options.drawYAxis) {
350 if (this.layout.yticks && this.layout.yticks.length > 0) {
351 for (var i = 0; i < this.layout.yticks.length; i++) {
352 var tick = this.layout.yticks[i];
353 if (typeof(tick) == "function") return;
354 var x = this.area.x;
355 var y = this.area.y + tick[0] * this.area.h;
356 context.beginPath();
357 context.moveTo(x, y);
358 context.lineTo(x - this.options.axisTickSize, y);
359 context.closePath();
360 context.stroke();
361
362 var label = makeDiv(tick[1]);
363 var top = (y - this.options.axisLabelFontSize / 2);
364 if (top < 0) top = 0;
365
366 if (top + this.options.axisLabelFontSize + 3 > this.height) {
367 label.style.bottom = "0px";
368 } else {
369 label.style.top = top + "px";
370 }
371 label.style.left = "0px";
372 label.style.textAlign = "right";
373 label.style.width = this.options.yAxisLabelWidth + "px";
374 this.container.appendChild(label);
375 this.ylabels.push(label);
376 }
377
378 // The lowest tick on the y-axis often overlaps with the leftmost
379 // tick on the x-axis. Shift the bottom tick up a little bit to
380 // compensate if necessary.
381 var bottomTick = this.ylabels[0];
382 var fontSize = this.options.axisLabelFontSize;
383 var bottom = parseInt(bottomTick.style.top) + fontSize;
384 if (bottom > this.height - fontSize) {
385 bottomTick.style.top = (parseInt(bottomTick.style.top) -
386 fontSize / 2) + "px";
387 }
388 }
389
390 context.beginPath();
391 context.moveTo(this.area.x, this.area.y);
392 context.lineTo(this.area.x, this.area.y + this.area.h);
393 context.closePath();
394 context.stroke();
395 }
396
397 if (this.options.drawXAxis) {
398 if (this.layout.xticks) {
399 for (var i = 0; i < this.layout.xticks.length; i++) {
400 var tick = this.layout.xticks[i];
401 if (typeof(dataset) == "function") return;
402
403 var x = this.area.x + tick[0] * this.area.w;
404 var y = this.area.y + this.area.h;
405 context.beginPath();
406 context.moveTo(x, y);
407 context.lineTo(x, y + this.options.axisTickSize);
408 context.closePath();
409 context.stroke();
410
411 var label = makeDiv(tick[1]);
412 label.style.textAlign = "center";
413 label.style.bottom = "0px";
414
415 var left = (x - this.options.axisLabelWidth/2);
416 if (left + this.options.axisLabelWidth > this.width) {
417 left = this.width - this.options.xAxisLabelWidth;
418 label.style.textAlign = "right";
419 }
420 if (left < 0) {
421 left = 0;
422 label.style.textAlign = "left";
423 }
424
425 label.style.left = left + "px";
426 label.style.width = this.options.xAxisLabelWidth + "px";
427 this.container.appendChild(label);
428 this.xlabels.push(label);
429 }
430 }
431
432 context.beginPath();
433 context.moveTo(this.area.x, this.area.y + this.area.h);
434 context.lineTo(this.area.x + this.area.w, this.area.y + this.area.h);
435 context.closePath();
436 context.stroke();
437 }
438
439 context.restore();
440 };
441
442
443 /**
444 * Overrides the CanvasRenderer method to draw error bars
445 */
446 DygraphCanvasRenderer.prototype._renderLineChart = function() {
447 var context = this.element.getContext("2d");
448 var colorCount = this.options.colorScheme.length;
449 var colorScheme = this.options.colorScheme;
450 var fillAlpha = this.options.fillAlpha;
451 var errorBars = this.layout.options.errorBars;
452 var fillGraph = this.layout.options.fillGraph;
453
454 var setNames = [];
455 for (var name in this.layout.datasets) {
456 if (this.layout.datasets.hasOwnProperty(name)) {
457 setNames.push(name);
458 }
459 }
460 var setCount = setNames.length;
461
462 // Update Points
463 // TODO(danvk): here
464 for (var i = 0; i < this.layout.points.length; i++) {
465 var point = this.layout.points[i];
466 point.canvasx = this.area.w * point.x + this.area.x;
467 point.canvasy = this.area.h * point.y + this.area.y;
468 }
469
470 // create paths
471 var isOK = function(x) { return x && !isNaN(x); };
472
473 var ctx = context;
474 if (errorBars) {
475 if (fillGraph) {
476 this.dygraph_.warn("Can't use fillGraph option with error bars");
477 }
478
479 for (var i = 0; i < setCount; i++) {
480 var setName = setNames[i];
481 var color = colorScheme[i % colorCount];
482
483 // setup graphics context
484 ctx.save();
485 ctx.strokeStyle = color;
486 ctx.lineWidth = this.options.strokeWidth;
487 var prevX = -1;
488 var prevYs = [-1, -1];
489 var count = 0;
490 var yscale = this.layout.yscale;
491 // should be same color as the lines but only 15% opaque.
492 var rgb = new RGBColor(color);
493 var err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
494 fillAlpha + ')';
495 ctx.fillStyle = err_color;
496 ctx.beginPath();
497 for (var j = 0; j < this.layout.points.length; j++) {
498 var point = this.layout.points[j];
499 count++;
500 if (point.name == setName) {
501 if (!isOK(point.y)) {
502 prevX = -1;
503 continue;
504 }
505 // TODO(danvk): here
506 var newYs = [ point.y - point.errorPlus * yscale,
507 point.y + point.errorMinus * yscale ];
508 newYs[0] = this.area.h * newYs[0] + this.area.y;
509 newYs[1] = this.area.h * newYs[1] + this.area.y;
510 if (prevX >= 0) {
511 ctx.moveTo(prevX, prevYs[0]);
512 ctx.lineTo(point.canvasx, newYs[0]);
513 ctx.lineTo(point.canvasx, newYs[1]);
514 ctx.lineTo(prevX, prevYs[1]);
515 ctx.closePath();
516 }
517 prevYs[0] = newYs[0];
518 prevYs[1] = newYs[1];
519 prevX = point.canvasx;
520 }
521 }
522 ctx.fill();
523 }
524 } else if (fillGraph) {
525 // TODO(danvk): merge this code with the logic above; they're very similar.
526 for (var i = 0; i < setCount; i++) {
527 var setName = setNames[i];
528 var setNameLast;
529 if (i>0) setNameLast = setNames[i-1];
530 var color = colorScheme[i % colorCount];
531
532 // setup graphics context
533 ctx.save();
534 ctx.strokeStyle = color;
535 ctx.lineWidth = this.options.strokeWidth;
536 var prevX = -1;
537 var prevYs = [-1, -1];
538 var count = 0;
539 var yscale = this.layout.yscale;
540 // should be same color as the lines but only 15% opaque.
541 var rgb = new RGBColor(color);
542 var err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
543 fillAlpha + ')';
544 ctx.fillStyle = err_color;
545 ctx.beginPath();
546 for (var j = 0; j < this.layout.points.length; j++) {
547 var point = this.layout.points[j];
548 count++;
549 if (point.name == setName) {
550 if (!isOK(point.y)) {
551 prevX = -1;
552 continue;
553 }
554 var pX = 1.0 + this.layout.minyval * this.layout.yscale;
555 if (pX < 0.0) pX = 0.0;
556 else if (pX > 1.0) pX = 1.0;
557 var newYs = [ point.y, pX ];
558 newYs[0] = this.area.h * newYs[0] + this.area.y;
559 newYs[1] = this.area.h * newYs[1] + this.area.y;
560 if (prevX >= 0) {
561 ctx.moveTo(prevX, prevYs[0]);
562 ctx.lineTo(point.canvasx, newYs[0]);
563 ctx.lineTo(point.canvasx, newYs[1]);
564 ctx.lineTo(prevX, prevYs[1]);
565 ctx.closePath();
566 }
567 prevYs[0] = newYs[0];
568 prevYs[1] = newYs[1];
569 prevX = point.canvasx;
570 }
571 }
572 ctx.fill();
573 }
574 }
575
576 for (var i = 0; i < setCount; i++) {
577 var setName = setNames[i];
578 var color = colorScheme[i%colorCount];
579
580 // setup graphics context
581 context.save();
582 var point = this.layout.points[0];
583 var pointSize = this.dygraph_.attr_("pointSize");
584 var prevX = null, prevY = null;
585 var drawPoints = this.dygraph_.attr_("drawPoints");
586 var points = this.layout.points;
587 for (var j = 0; j < points.length; j++) {
588 var point = points[j];
589 if (point.name == setName) {
590 if (!isOK(point.canvasy)) {
591 // this will make us move to the next point, not draw a line to it.
592 prevX = prevY = null;
593 } else {
594 // A point is "isolated" if it is non-null but both the previous
595 // and next points are null.
596 var isIsolated = (!prevX && (j == points.length - 1 ||
597 !isOK(points[j+1].canvasy)));
598
599 if (!prevX) {
600 prevX = point.canvasx;
601 prevY = point.canvasy;
602 } else {
603 ctx.beginPath();
604 ctx.strokeStyle = color;
605 ctx.lineWidth = this.options.strokeWidth;
606 ctx.moveTo(prevX, prevY);
607 prevX = point.canvasx;
608 prevY = point.canvasy;
609 ctx.lineTo(prevX, prevY);
610 ctx.stroke();
611 }
612
613 if (drawPoints || isIsolated) {
614 ctx.beginPath();
615 ctx.fillStyle = color;
616 ctx.arc(point.canvasx, point.canvasy, pointSize,
617 0, 2 * Math.PI, false);
618 ctx.fill();
619 }
620 }
621 }
622 }
623 }
624
625 context.restore();
626 };