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