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