remove dependence on MochiKit.Signal
[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 MochiKit.Base.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 MochiKit.Base.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": Color.blackColor(),
172 "axisLineWidth": 0.5,
173 "axisTickSize": 3,
174 "axisLabelColor": Color.blackColor(),
175 "axisLabelFont": "Arial",
176 "axisLabelFontSize": 9,
177 "axisLabelWidth": 50,
178 "drawYGrid": true,
179 "drawXGrid": true,
180 "gridLineColor": MochiKit.Color.Color.grayColor()
181 };
182 MochiKit.Base.update(this.options, options);
183
184 this.layout = layout;
185 this.element = element;
186 this.container = this.element.parentNode;
187
188 // Stuff relating to Canvas on IE support
189 this.isIE = (/MSIE/.test(navigator.userAgent) && !window.opera);
190
191 if (this.isIE && !isNil(G_vmlCanvasManager)) {
192 this.IEDelay = 0.5;
193 this.maxTries = 5;
194 this.renderDelay = null;
195 this.clearDelay = null;
196 this.element = G_vmlCanvasManager.initElement(this.element);
197 }
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 (MochiKit.Base.isUndefinedOrNull(canvasName))
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.toRGBString();
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.toRGBString();
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 // TODO(danvk) Call super.render()
315 this._renderLineChart();
316 this._renderAxis();
317 };
318
319
320 DygraphCanvasRenderer.prototype._renderAxis = function() {
321 if (!this.options.drawXAxis && !this.options.drawYAxis)
322 return;
323
324 var context = this.element.getContext("2d");
325
326 var labelStyle = {"style":
327 {"position": "absolute",
328 "fontSize": this.options.axisLabelFontSize + "px",
329 "zIndex": 10,
330 "color": this.options.axisLabelColor.toRGBString(),
331 "width": this.options.axisLabelWidth + "px",
332 "overflow": "hidden"
333 }
334 };
335
336 // axis lines
337 context.save();
338 context.strokeStyle = this.options.axisLineColor.toRGBString();
339 context.lineWidth = this.options.axisLineWidth;
340
341
342 if (this.options.drawYAxis) {
343 if (this.layout.yticks) {
344 for (var i = 0; i < this.layout.yticks.length; i++) {
345 var tick = this.layout.yticks[i];
346 if (typeof(tick) == "function") return;
347 var x = this.area.x;
348 var y = this.area.y + tick[0] * this.area.h;
349 context.beginPath();
350 context.moveTo(x, y);
351 context.lineTo(x - this.options.axisTickSize, y);
352 context.closePath();
353 context.stroke();
354
355 var label = DIV(labelStyle, tick[1]);
356 var top = (y - this.options.axisLabelFontSize / 2);
357 if (top < 0) top = 0;
358
359 if (top + this.options.axisLabelFontSize + 3 > this.height) {
360 label.style.bottom = "0px";
361 } else {
362 label.style.top = top + "px";
363 }
364 label.style.left = "0px";
365 label.style.textAlign = "right";
366 label.style.width = this.options.yAxisLabelWidth + "px";
367 this.container.appendChild(label);
368 this.ylabels.push(label);
369 }
370
371 // The lowest tick on the y-axis often overlaps with the leftmost
372 // tick on the x-axis. Shift the bottom tick up a little bit to
373 // compensate if necessary.
374 var bottomTick = this.ylabels[0];
375 var fontSize = this.options.axisLabelFontSize;
376 var bottom = parseInt(bottomTick.style.top) + fontSize;
377 if (bottom > this.height - fontSize) {
378 bottomTick.style.top = (parseInt(bottomTick.style.top) -
379 fontSize / 2) + "px";
380 }
381 }
382
383 context.beginPath();
384 context.moveTo(this.area.x, this.area.y);
385 context.lineTo(this.area.x, this.area.y + this.area.h);
386 context.closePath();
387 context.stroke();
388 }
389
390 if (this.options.drawXAxis) {
391 if (this.layout.xticks) {
392 for (var i = 0; i < this.layout.xticks.length; i++) {
393 var tick = this.layout.xticks[i];
394 if (typeof(dataset) == "function") return;
395
396 var x = this.area.x + tick[0] * this.area.w;
397 var y = this.area.y + this.area.h;
398 context.beginPath();
399 context.moveTo(x, y);
400 context.lineTo(x, y + this.options.axisTickSize);
401 context.closePath();
402 context.stroke();
403
404 var label = DIV(labelStyle, tick[1]);
405 label.style.textAlign = "center";
406 label.style.bottom = "0px";
407
408 var left = (x - this.options.axisLabelWidth/2);
409 if (left + this.options.axisLabelWidth > this.width) {
410 left = this.width - this.options.xAxisLabelWidth;
411 label.style.textAlign = "right";
412 }
413 if (left < 0) {
414 left = 0;
415 label.style.textAlign = "left";
416 }
417
418 label.style.left = left + "px";
419 label.style.width = this.options.xAxisLabelWidth + "px";
420 this.container.appendChild(label);
421 this.xlabels.push(label);
422 }
423 }
424
425 context.beginPath();
426 context.moveTo(this.area.x, this.area.y + this.area.h);
427 context.lineTo(this.area.x + this.area.w, this.area.y + this.area.h);
428 context.closePath();
429 context.stroke();
430 }
431
432 context.restore();
433 };
434
435
436 /**
437 * Overrides the CanvasRenderer method to draw error bars
438 */
439 DygraphCanvasRenderer.prototype._renderLineChart = function() {
440 var context = this.element.getContext("2d");
441 var colorCount = this.options.colorScheme.length;
442 var colorScheme = this.options.colorScheme;
443 var setNames = MochiKit.Base.keys(this.layout.datasets);
444 var errorBars = this.layout.options.errorBars;
445 var setCount = setNames.length;
446 var bind = MochiKit.Base.bind;
447 var partial = MochiKit.Base.partial;
448
449 //Update Points
450 for (var i = 0; i < this.layout.points.length; i++) {
451 var point = this.layout.points[i];
452 point.canvasx = this.area.w * point.x + this.area.x;
453 point.canvasy = this.area.h * point.y + this.area.y;
454 }
455
456 // create paths
457 var isOK = function(x) { return x && !isNaN(x); };
458 var makePath = function(ctx) {
459 for (var i = 0; i < setCount; i++) {
460 var setName = setNames[i];
461 var color = colorScheme[i%colorCount];
462 var strokeX = this.options.strokeColorTransform;
463
464 // setup graphics context
465 context.save();
466 context.strokeStyle = color.toRGBString();
467 context.lineWidth = this.options.strokeWidth;
468 var point = this.layout.points[0];
469 var pointSize = this.dygraph_.attr_("pointSize");
470 var prevX = null, prevY = null;
471 var drawPoints = this.dygraph_.attr_("drawPoints");
472 var points = this.layout.points;
473 for (var j = 0; j < points.length; j++) {
474 var point = points[j];
475 if (point.name == setName) {
476 if (!isOK(point.canvasy)) {
477 // this will make us move to the next point, not draw a line to it.
478 prevX = prevY = null;
479 } else {
480 // A point is "isolated" if it is non-null but both the previous
481 // and next points are null.
482 var isIsolated = (!prevX && (j == points.length - 1 ||
483 !isOK(points[j+1].canvasy)));
484
485 if (!prevX) {
486 prevX = point.canvasx;
487 prevY = point.canvasy;
488 } else {
489 ctx.beginPath();
490 ctx.moveTo(prevX, prevY);
491 prevX = point.canvasx;
492 prevY = point.canvasy;
493 ctx.lineTo(prevX, prevY);
494 ctx.stroke();
495 }
496
497 if (drawPoints || isIsolated) {
498 ctx.beginPath();
499 ctx.fillStyle = color.toRGBString();
500 ctx.arc(point.canvasx, point.canvasy, pointSize, 0, 360, false);
501 ctx.fill();
502 }
503 }
504 }
505 }
506 }
507 };
508
509 var makeErrorBars = function(ctx) {
510 for (var i = 0; i < setCount; i++) {
511 var setName = setNames[i];
512 var color = colorScheme[i % colorCount];
513 var strokeX = this.options.strokeColorTransform;
514
515 // setup graphics context
516 context.save();
517 context.strokeStyle = color.toRGBString();
518 context.lineWidth = this.options.strokeWidth;
519 var prevX = -1;
520 var prevYs = [-1, -1];
521 var count = 0;
522 var yscale = this.layout.yscale;
523 // should be same color as the lines
524 var err_color = color.colorWithAlpha(0.15);
525 ctx.fillStyle = err_color.toRGBString();
526 ctx.beginPath();
527 for (var j = 0; j < this.layout.points.length; j++) {
528 var point = this.layout.points[j];
529 count++;
530 if (point.name == setName) {
531 if (!point.y || isNaN(point.y)) {
532 prevX = -1;
533 return;
534 }
535 var newYs = [ point.y - point.errorPlus * yscale,
536 point.y + point.errorMinus * yscale ];
537 newYs[0] = this.area.h * newYs[0] + this.area.y;
538 newYs[1] = this.area.h * newYs[1] + this.area.y;
539 if (prevX >= 0) {
540 ctx.moveTo(prevX, prevYs[0]);
541 ctx.lineTo(point.canvasx, newYs[0]);
542 ctx.lineTo(point.canvasx, newYs[1]);
543 ctx.lineTo(prevX, prevYs[1]);
544 ctx.closePath();
545 }
546 prevYs[0] = newYs[0];
547 prevYs[1] = newYs[1];
548 prevX = point.canvasx;
549 }
550 }
551 ctx.fill();
552 }
553 };
554
555 if (errorBars)
556 bind(makeErrorBars, this)(context);
557 bind(makePath, this)(context);
558 context.restore();
559 };