leave it in a working state for the night
[dygraphs.git] / dygraph-canvas.js
CommitLineData
6a1aa64f
DV
1// Copyright 2006 Dan Vanderkam (danvdk@gmail.com)
2// All Rights Reserved.
3
4/**
3df0ccf0
DV
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
6a1aa64f
DV
10 */
11
6a1aa64f 12/**
3df0ccf0 13 * Creates a new DygraphLayout object.
6a1aa64f 14 * @param {Object} options Options for PlotKit.Layout
285a6bda 15 * @return {Object} The DygraphLayout object
6a1aa64f 16 */
efe0829a
DV
17DygraphLayout = 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();
6a1aa64f 22};
efe0829a
DV
23
24DygraphLayout.prototype.attr_ = function(name) {
25 return this.dygraph_.attr_(name);
26};
27
28DygraphLayout.prototype.addDataset = function(setname, set_xy) {
29 this.datasets[setname] = set_xy;
30};
31
32DygraphLayout.prototype.evaluate = function() {
33 this._evaluateLimits();
34 this._evaluateLineCharts();
35 this._evaluateLineTicks();
36};
37
38DygraphLayout.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
57DygraphLayout.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
86DygraphLayout.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
6a1aa64f
DV
108
109/**
110 * Behaves the same way as PlotKit.Layout, but also copies the errors
111 * @private
112 */
285a6bda 113DygraphLayout.prototype.evaluateWithError = function() {
6a1aa64f
DV
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];
6a1aa64f
DV
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 */
285a6bda 139DygraphLayout.prototype.removeAllDatasets = function() {
6a1aa64f
DV
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 */
285a6bda 148DygraphLayout.prototype.updateOptions = function(new_options) {
6a1aa64f
DV
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
285a6bda 159 * @param {Layout} layout The DygraphLayout object for this graph.
6a1aa64f
DV
160 * @param {Object} options Options to pass on to CanvasRenderer
161 */
9317362d
DV
162DygraphCanvasRenderer = function(dygraph, element, layout, options) {
163 // TODO(danvk): remove options, just use dygraph.attr_.
9317362d 164 this.dygraph_ = dygraph;
fbe31dc8
DV
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 };
6a1aa64f
DV
182 MochiKit.Base.update(this.options, options);
183
fbe31dc8
DV
184 this.layout = layout;
185 this.element = MochiKit.DOM.getElement(element);
186 this.container = this.element.parentNode;
187
188 // Stuff relating to Canvas on IE support
3df0ccf0 189 this.isIE = (/MSIE/.test(navigator.userAgent) && !window.opera);
fbe31dc8
DV
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 MochiKit.DOM.updateNodeAttributes(this.container,
219 {"style":{ "position": "relative", "width": this.width + "px"}});
220};
221
222DygraphCanvasRenderer.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 this.clearDelay = MochiKit.Async.wait(this.IEDelay);
234 this.clearDelay.addCallback(bind(this.clear, this));
235 return;
236 }
237 }
238
239 var context = this.element.getContext("2d");
240 context.clearRect(0, 0, this.width, this.height);
241
2160ed4a
DV
242 for (var i = 0; i < this.xlabels.length; i++) {
243 MochiKit.DOM.removeElement(this.xlabels[i]);
244 }
245 for (var i = 0; i < this.ylabels.length; i++) {
246 MochiKit.DOM.removeElement(this.ylabels[i]);
247 }
fbe31dc8
DV
248 this.xlabels = new Array();
249 this.ylabels = new Array();
250};
251
252
253DygraphCanvasRenderer.isSupported = function(canvasName) {
254 var canvas = null;
255 try {
256 if (MochiKit.Base.isUndefinedOrNull(canvasName))
257 canvas = MochiKit.DOM.CANVAS({});
258 else
259 canvas = MochiKit.DOM.getElement(canvasName);
260 var context = canvas.getContext("2d");
261 }
262 catch (e) {
263 var ie = navigator.appVersion.match(/MSIE (\d\.\d)/);
264 var opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
265 if ((!ie) || (ie[1] < 6) || (opera))
266 return false;
267 return true;
268 }
269 return true;
6a1aa64f 270};
6a1aa64f
DV
271
272/**
273 * Draw an X/Y grid on top of the existing plot
274 */
285a6bda 275DygraphCanvasRenderer.prototype.render = function() {
6a1aa64f
DV
276 // Draw the new X/Y grid
277 var ctx = this.element.getContext("2d");
278 if (this.options.drawYGrid) {
279 var ticks = this.layout.yticks;
280 ctx.save();
281 ctx.strokeStyle = this.options.gridLineColor.toRGBString();
282 ctx.lineWidth = this.options.axisLineWidth;
283 for (var i = 0; i < ticks.length; i++) {
284 var x = this.area.x;
285 var y = this.area.y + ticks[i][0] * this.area.h;
286 ctx.beginPath();
287 ctx.moveTo(x, y);
288 ctx.lineTo(x + this.area.w, y);
289 ctx.closePath();
290 ctx.stroke();
291 }
292 }
293
294 if (this.options.drawXGrid) {
295 var ticks = this.layout.xticks;
296 ctx.save();
297 ctx.strokeStyle = this.options.gridLineColor.toRGBString();
298 ctx.lineWidth = this.options.axisLineWidth;
299 for (var i=0; i<ticks.length; i++) {
300 var x = this.area.x + ticks[i][0] * this.area.w;
301 var y = this.area.y + this.area.h;
302 ctx.beginPath();
303 ctx.moveTo(x, y);
304 ctx.lineTo(x, this.area.y);
305 ctx.closePath();
306 ctx.stroke();
307 }
308 }
2ce09b19
DV
309
310 // Do the ordinary rendering, as before
311 // TODO(danvk) Call super.render()
312 this._renderLineChart();
fbe31dc8
DV
313 this._renderAxis();
314};
315
316
317DygraphCanvasRenderer.prototype._renderAxis = function() {
318 if (!this.options.drawXAxis && !this.options.drawYAxis)
319 return;
320
321 var context = this.element.getContext("2d");
322
323 var labelStyle = {"style":
324 {"position": "absolute",
325 "fontSize": this.options.axisLabelFontSize + "px",
326 "zIndex": 10,
327 "color": this.options.axisLabelColor.toRGBString(),
328 "width": this.options.axisLabelWidth + "px",
329 "overflow": "hidden"
330 }
331 };
332
333 // axis lines
334 context.save();
335 context.strokeStyle = this.options.axisLineColor.toRGBString();
336 context.lineWidth = this.options.axisLineWidth;
337
338
339 if (this.options.drawYAxis) {
340 if (this.layout.yticks) {
2160ed4a
DV
341 for (var i = 0; i < this.layout.yticks.length; i++) {
342 var tick = this.layout.yticks[i];
fbe31dc8
DV
343 if (typeof(tick) == "function") return;
344 var x = this.area.x;
345 var y = this.area.y + tick[0] * this.area.h;
346 context.beginPath();
347 context.moveTo(x, y);
348 context.lineTo(x - this.options.axisTickSize, y);
349 context.closePath();
350 context.stroke();
351
352 var label = DIV(labelStyle, tick[1]);
353 var top = (y - this.options.axisLabelFontSize / 2);
354 if (top < 0) top = 0;
355
356 if (top + this.options.axisLabelFontSize + 3 > this.height) {
357 label.style.bottom = "0px";
358 } else {
359 label.style.top = top + "px";
360 }
361 label.style.left = "0px";
362 label.style.textAlign = "right";
363 label.style.width = this.options.yAxisLabelWidth + "px";
364 MochiKit.DOM.appendChildNodes(this.container, label);
365 this.ylabels.push(label);
2160ed4a 366 }
fbe31dc8
DV
367
368 // The lowest tick on the y-axis often overlaps with the leftmost
369 // tick on the x-axis. Shift the bottom tick up a little bit to
370 // compensate if necessary.
371 var bottomTick = this.ylabels[0];
372 var fontSize = this.options.axisLabelFontSize;
373 var bottom = parseInt(bottomTick.style.top) + fontSize;
374 if (bottom > this.height - fontSize) {
375 bottomTick.style.top = (parseInt(bottomTick.style.top) -
376 fontSize / 2) + "px";
377 }
378 }
379
380 context.beginPath();
381 context.moveTo(this.area.x, this.area.y);
382 context.lineTo(this.area.x, this.area.y + this.area.h);
383 context.closePath();
384 context.stroke();
385 }
386
387 if (this.options.drawXAxis) {
388 if (this.layout.xticks) {
2160ed4a
DV
389 for (var i = 0; i < this.layout.xticks.length; i++) {
390 var tick = this.layout.xticks[i];
fbe31dc8
DV
391 if (typeof(dataset) == "function") return;
392
393 var x = this.area.x + tick[0] * this.area.w;
394 var y = this.area.y + this.area.h;
395 context.beginPath();
396 context.moveTo(x, y);
397 context.lineTo(x, y + this.options.axisTickSize);
398 context.closePath();
399 context.stroke();
400
401 var label = DIV(labelStyle, tick[1]);
402 label.style.textAlign = "center";
403 label.style.bottom = "0px";
404
405 var left = (x - this.options.axisLabelWidth/2);
406 if (left + this.options.axisLabelWidth > this.width) {
407 left = this.width - this.options.xAxisLabelWidth;
408 label.style.textAlign = "right";
409 }
410 if (left < 0) {
411 left = 0;
412 label.style.textAlign = "left";
413 }
414
415 label.style.left = left + "px";
416 label.style.width = this.options.xAxisLabelWidth + "px";
417 MochiKit.DOM.appendChildNodes(this.container, label);
418 this.xlabels.push(label);
2160ed4a 419 }
fbe31dc8
DV
420 }
421
422 context.beginPath();
423 context.moveTo(this.area.x, this.area.y + this.area.h);
424 context.lineTo(this.area.x + this.area.w, this.area.y + this.area.h);
425 context.closePath();
426 context.stroke();
427 }
428
429 context.restore();
6a1aa64f
DV
430};
431
fbe31dc8 432
6a1aa64f
DV
433/**
434 * Overrides the CanvasRenderer method to draw error bars
435 */
285a6bda 436DygraphCanvasRenderer.prototype._renderLineChart = function() {
6a1aa64f
DV
437 var context = this.element.getContext("2d");
438 var colorCount = this.options.colorScheme.length;
439 var colorScheme = this.options.colorScheme;
440 var setNames = MochiKit.Base.keys(this.layout.datasets);
441 var errorBars = this.layout.options.errorBars;
442 var setCount = setNames.length;
443 var bind = MochiKit.Base.bind;
444 var partial = MochiKit.Base.partial;
445
446 //Update Points
2160ed4a
DV
447 for (var i = 0; i < this.layout.points.length; i++) {
448 var point = this.layout.points[i];
6a1aa64f
DV
449 point.canvasx = this.area.w * point.x + this.area.x;
450 point.canvasy = this.area.h * point.y + this.area.y;
451 }
6a1aa64f
DV
452
453 // create paths
9317362d 454 var isOK = function(x) { return x && !isNaN(x); };
6a1aa64f
DV
455 var makePath = function(ctx) {
456 for (var i = 0; i < setCount; i++) {
457 var setName = setNames[i];
458 var color = colorScheme[i%colorCount];
459 var strokeX = this.options.strokeColorTransform;
460
461 // setup graphics context
462 context.save();
463 context.strokeStyle = color.toRGBString();
464 context.lineWidth = this.options.strokeWidth;
6a1aa64f 465 var point = this.layout.points[0];
9317362d
DV
466 var pointSize = this.dygraph_.attr_("pointSize");
467 var prevX = null, prevY = null;
468 var drawPoints = this.dygraph_.attr_("drawPoints");
469 var points = this.layout.points;
470 for (var j = 0; j < points.length; j++) {
471 var point = points[j];
6a1aa64f 472 if (point.name == setName) {
9317362d 473 if (!isOK(point.canvasy)) {
9a730910 474 // this will make us move to the next point, not draw a line to it.
9317362d 475 prevX = prevY = null;
9a730910 476 } else {
9317362d
DV
477 // A point is "isolated" if it is non-null but both the previous
478 // and next points are null.
479 var isIsolated = (!prevX && (j == points.length - 1 ||
480 !isOK(points[j+1].canvasy)));
481
482 if (!prevX) {
483 prevX = point.canvasx;
484 prevY = point.canvasy;
9a730910 485 } else {
9317362d
DV
486 ctx.beginPath();
487 ctx.moveTo(prevX, prevY);
488 prevX = point.canvasx;
489 prevY = point.canvasy;
490 ctx.lineTo(prevX, prevY);
491 ctx.stroke();
492 }
493
494 if (drawPoints || isIsolated) {
495 ctx.beginPath();
496 ctx.fillStyle = color.toRGBString();
497 ctx.arc(point.canvasx, point.canvasy, pointSize, 0, 360, false);
498 ctx.fill();
9a730910
DV
499 }
500 }
6a1aa64f 501 }
9317362d 502 }
6a1aa64f
DV
503 }
504 };
505
506 var makeErrorBars = function(ctx) {
507 for (var i = 0; i < setCount; i++) {
508 var setName = setNames[i];
509 var color = colorScheme[i % colorCount];
510 var strokeX = this.options.strokeColorTransform;
511
512 // setup graphics context
513 context.save();
514 context.strokeStyle = color.toRGBString();
515 context.lineWidth = this.options.strokeWidth;
516 var prevX = -1;
517 var prevYs = [-1, -1];
518 var count = 0;
519 var yscale = this.layout.yscale;
05c9d0c4
DV
520 // should be same color as the lines
521 var err_color = color.colorWithAlpha(0.15);
522 ctx.fillStyle = err_color.toRGBString();
523 ctx.beginPath();
524 for (var j = 0; j < this.layout.points.length; j++) {
525 var point = this.layout.points[j];
6a1aa64f
DV
526 count++;
527 if (point.name == setName) {
5011e7a1
DV
528 if (!point.y || isNaN(point.y)) {
529 prevX = -1;
530 return;
531 }
6a1aa64f
DV
532 var newYs = [ point.y - point.errorPlus * yscale,
533 point.y + point.errorMinus * yscale ];
534 newYs[0] = this.area.h * newYs[0] + this.area.y;
535 newYs[1] = this.area.h * newYs[1] + this.area.y;
536 if (prevX >= 0) {
05c9d0c4
DV
537 ctx.moveTo(prevX, prevYs[0]);
538 ctx.lineTo(point.canvasx, newYs[0]);
539 ctx.lineTo(point.canvasx, newYs[1]);
540 ctx.lineTo(prevX, prevYs[1]);
541 ctx.closePath();
6a1aa64f
DV
542 }
543 prevYs[0] = newYs[0];
544 prevYs[1] = newYs[1];
545 prevX = point.canvasx;
546 }
05c9d0c4 547 }
6a1aa64f
DV
548 ctx.fill();
549 }
550 };
551
552 if (errorBars)
553 bind(makeErrorBars, this)(context);
554 bind(makePath, this)(context);
555 context.restore();
556};