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