apply patches from mark swanson
[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;
40 for (var name in this.datasets) {
ca43052c
DV
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 }
efe0829a
DV
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
59DygraphLayout.prototype._evaluateLineCharts = function() {
60 // add all the rects
61 this.points = new Array();
62 for (var setName in this.datasets) {
ca43052c
DV
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 }
efe0829a
DV
87 }
88};
89
90DygraphLayout.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
6a1aa64f
DV
112
113/**
114 * Behaves the same way as PlotKit.Layout, but also copies the errors
115 * @private
116 */
285a6bda 117DygraphLayout.prototype.evaluateWithError = function() {
6a1aa64f
DV
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) {
ca43052c
DV
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 }
6a1aa64f
DV
139 }
140};
141
142/**
143 * Convenience function to remove all the data sets from a graph
144 */
285a6bda 145DygraphLayout.prototype.removeAllDatasets = function() {
6a1aa64f
DV
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 */
285a6bda 154DygraphLayout.prototype.updateOptions = function(new_options) {
fc80a396 155 Dygraph.update(this.options, new_options ? new_options : {});
6a1aa64f
DV
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
285a6bda 165 * @param {Layout} layout The DygraphLayout object for this graph.
6a1aa64f
DV
166 * @param {Object} options Options to pass on to CanvasRenderer
167 */
9317362d
DV
168DygraphCanvasRenderer = function(dygraph, element, layout, options) {
169 // TODO(danvk): remove options, just use dygraph.attr_.
9317362d 170 this.dygraph_ = dygraph;
fbe31dc8
DV
171
172 // default options
173 this.options = {
f474c2a3
DV
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)"
fbe31dc8 187 };
fc80a396 188 Dygraph.update(this.options, options);
6a1aa64f 189
fbe31dc8 190 this.layout = layout;
b0c3b730 191 this.element = element;
fbe31dc8
DV
192 this.container = this.element.parentNode;
193
fbe31dc8
DV
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
b0c3b730
DV
213 this.container.style.position = "relative";
214 this.container.style.width = this.width + "px";
fbe31dc8
DV
215};
216
217DygraphCanvasRenderer.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) {
76171648 228 // TODO(danvk): this is broken, since MochiKit.Async is gone.
fbe31dc8
DV
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
2160ed4a 238 for (var i = 0; i < this.xlabels.length; i++) {
b0c3b730
DV
239 var el = this.xlabels[i];
240 el.parentNode.removeChild(el);
2160ed4a
DV
241 }
242 for (var i = 0; i < this.ylabels.length; i++) {
b0c3b730
DV
243 var el = this.ylabels[i];
244 el.parentNode.removeChild(el);
2160ed4a 245 }
fbe31dc8
DV
246 this.xlabels = new Array();
247 this.ylabels = new Array();
248};
249
250
251DygraphCanvasRenderer.isSupported = function(canvasName) {
252 var canvas = null;
253 try {
21d3323f 254 if (typeof(canvasName) == 'undefined' || canvasName == null)
b0c3b730 255 canvas = document.createElement("canvas");
fbe31dc8 256 else
b0c3b730 257 canvas = canvasName;
fbe31dc8
DV
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;
6a1aa64f 268};
6a1aa64f
DV
269
270/**
271 * Draw an X/Y grid on top of the existing plot
272 */
285a6bda 273DygraphCanvasRenderer.prototype.render = function() {
6a1aa64f
DV
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();
f2f24402 279 ctx.strokeStyle = this.options.gridLineColor;
6a1aa64f
DV
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();
f2f24402 295 ctx.strokeStyle = this.options.gridLineColor;
6a1aa64f
DV
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 }
2ce09b19
DV
307
308 // Do the ordinary rendering, as before
2ce09b19 309 this._renderLineChart();
fbe31dc8
DV
310 this._renderAxis();
311};
312
313
314DygraphCanvasRenderer.prototype._renderAxis = function() {
315 if (!this.options.drawXAxis && !this.options.drawYAxis)
316 return;
317
318 var context = this.element.getContext("2d");
319
34fedff8
DV
320 var labelStyle = {
321 "position": "absolute",
322 "fontSize": this.options.axisLabelFontSize + "px",
323 "zIndex": 10,
f474c2a3 324 "color": this.options.axisLabelColor,
34fedff8
DV
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) {
ca43052c
DV
331 if (labelStyle.hasOwnProperty(name)) {
332 div.style[name] = labelStyle[name];
333 }
fbe31dc8 334 }
34fedff8
DV
335 div.appendChild(document.createTextNode(txt));
336 return div;
fbe31dc8
DV
337 };
338
339 // axis lines
340 context.save();
f474c2a3 341 context.strokeStyle = this.options.axisLineColor;
fbe31dc8
DV
342 context.lineWidth = this.options.axisLineWidth;
343
fbe31dc8
DV
344 if (this.options.drawYAxis) {
345 if (this.layout.yticks) {
2160ed4a
DV
346 for (var i = 0; i < this.layout.yticks.length; i++) {
347 var tick = this.layout.yticks[i];
fbe31dc8
DV
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
34fedff8 357 var label = makeDiv(tick[1]);
fbe31dc8
DV
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";
b0c3b730 369 this.container.appendChild(label);
fbe31dc8 370 this.ylabels.push(label);
2160ed4a 371 }
fbe31dc8
DV
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) {
2160ed4a
DV
394 for (var i = 0; i < this.layout.xticks.length; i++) {
395 var tick = this.layout.xticks[i];
fbe31dc8
DV
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
34fedff8 406 var label = makeDiv(tick[1]);
fbe31dc8
DV
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";
b0c3b730 422 this.container.appendChild(label);
fbe31dc8 423 this.xlabels.push(label);
2160ed4a 424 }
fbe31dc8
DV
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();
6a1aa64f
DV
435};
436
fbe31dc8 437
6a1aa64f
DV
438/**
439 * Overrides the CanvasRenderer method to draw error bars
440 */
285a6bda 441DygraphCanvasRenderer.prototype._renderLineChart = function() {
6a1aa64f
DV
442 var context = this.element.getContext("2d");
443 var colorCount = this.options.colorScheme.length;
444 var colorScheme = this.options.colorScheme;
6a1aa64f 445 var errorBars = this.layout.options.errorBars;
21d3323f
DV
446
447 var setNames = [];
ca43052c
DV
448 for (var name in this.layout.datasets) {
449 if (this.layout.datasets.hasOwnProperty(name)) {
450 setNames.push(name);
451 }
452 }
21d3323f 453 var setCount = setNames.length;
6a1aa64f
DV
454
455 //Update Points
2160ed4a
DV
456 for (var i = 0; i < this.layout.points.length; i++) {
457 var point = this.layout.points[i];
6a1aa64f
DV
458 point.canvasx = this.area.w * point.x + this.area.x;
459 point.canvasy = this.area.h * point.y + this.area.y;
460 }
6a1aa64f
DV
461
462 // create paths
9317362d 463 var isOK = function(x) { return x && !isNaN(x); };
6a1aa64f 464
80aaae18
DV
465 var ctx = context;
466 if (errorBars) {
6a1aa64f
DV
467 for (var i = 0; i < setCount; i++) {
468 var setName = setNames[i];
469 var color = colorScheme[i % colorCount];
6a1aa64f
DV
470
471 // setup graphics context
80aaae18
DV
472 ctx.save();
473 ctx.strokeStyle = color;
474 ctx.lineWidth = this.options.strokeWidth;
6a1aa64f
DV
475 var prevX = -1;
476 var prevYs = [-1, -1];
477 var count = 0;
478 var yscale = this.layout.yscale;
f474c2a3
DV
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;
05c9d0c4
DV
483 ctx.beginPath();
484 for (var j = 0; j < this.layout.points.length; j++) {
485 var point = this.layout.points[j];
6a1aa64f
DV
486 count++;
487 if (point.name == setName) {
5011e7a1
DV
488 if (!point.y || isNaN(point.y)) {
489 prevX = -1;
ae85914a 490 continue;
5011e7a1 491 }
6a1aa64f
DV
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) {
05c9d0c4
DV
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();
6a1aa64f
DV
502 }
503 prevYs[0] = newYs[0];
504 prevYs[1] = newYs[1];
505 prevX = point.canvasx;
506 }
05c9d0c4 507 }
6a1aa64f
DV
508 ctx.fill();
509 }
80aaae18
DV
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;
7bf6a9fe
DV
552 ctx.arc(point.canvasx, point.canvasy, pointSize,
553 0, 2 * Math.PI, false);
80aaae18
DV
554 ctx.fill();
555 }
556 }
557 }
558 }
559 }
6a1aa64f 560
6a1aa64f
DV
561 context.restore();
562};