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