Fix typo spotted by Morgan
[dygraphs.git] / dygraph-canvas.js
... / ...
CommitLineData
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 */
17DygraphLayout = function(dygraph, options) {
18 this.dygraph_ = dygraph;
19 this.options = {}; // TODO(danvk): remove, use attr_ instead.
20 Dygraph.update(this.options, options ? options : {});
21 this.datasets = new Array();
22};
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 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;
49
50 var x2 = series[series.length - 1][0];
51 if (!this.maxxval || x2 > this.maxxval) this.maxxval = x2;
52 }
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) {
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 // TODO(danvk): here
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 }
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
117
118/**
119 * Behaves the same way as PlotKit.Layout, but also copies the errors
120 * @private
121 */
122DygraphLayout.prototype.evaluateWithError = function() {
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) {
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 }
143 }
144};
145
146/**
147 * Convenience function to remove all the data sets from a graph
148 */
149DygraphLayout.prototype.removeAllDatasets = function() {
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 */
158DygraphLayout.prototype.updateOptions = function(new_options) {
159 Dygraph.update(this.options, new_options ? new_options : {});
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
169 * @param {Layout} layout The DygraphLayout object for this graph.
170 * @param {Object} options Options to pass on to CanvasRenderer
171 */
172DygraphCanvasRenderer = function(dygraph, element, layout, options) {
173 // TODO(danvk): remove options, just use dygraph.attr_.
174 this.dygraph_ = dygraph;
175
176 // default options
177 this.options = {
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)"
191 };
192 Dygraph.update(this.options, options);
193
194 this.layout = layout;
195 this.element = element;
196 this.container = this.element.parentNode;
197
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
217 this.container.style.position = "relative";
218 this.container.style.width = this.width + "px";
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) {
232 // TODO(danvk): this is broken, since MochiKit.Async is gone.
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
242 for (var i = 0; i < this.xlabels.length; i++) {
243 var el = this.xlabels[i];
244 el.parentNode.removeChild(el);
245 }
246 for (var i = 0; i < this.ylabels.length; i++) {
247 var el = this.ylabels[i];
248 el.parentNode.removeChild(el);
249 }
250 this.xlabels = new Array();
251 this.ylabels = new Array();
252};
253
254
255DygraphCanvasRenderer.isSupported = function(canvasName) {
256 var canvas = null;
257 try {
258 if (typeof(canvasName) == 'undefined' || canvasName == null)
259 canvas = document.createElement("canvas");
260 else
261 canvas = canvasName;
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;
272};
273
274/**
275 * Draw an X/Y grid on top of the existing plot
276 */
277DygraphCanvasRenderer.prototype.render = function() {
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();
283 ctx.strokeStyle = this.options.gridLineColor;
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();
299 ctx.strokeStyle = this.options.gridLineColor;
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 }
311
312 // Do the ordinary rendering, as before
313 this._renderLineChart();
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
324 var labelStyle = {
325 "position": "absolute",
326 "fontSize": this.options.axisLabelFontSize + "px",
327 "zIndex": 10,
328 "color": this.options.axisLabelColor,
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) {
335 if (labelStyle.hasOwnProperty(name)) {
336 div.style[name] = labelStyle[name];
337 }
338 }
339 div.appendChild(document.createTextNode(txt));
340 return div;
341 };
342
343 // axis lines
344 context.save();
345 context.strokeStyle = this.options.axisLineColor;
346 context.lineWidth = this.options.axisLineWidth;
347
348 if (this.options.drawYAxis) {
349 if (this.layout.yticks && this.layout.yticks.length > 0) {
350 for (var i = 0; i < this.layout.yticks.length; i++) {
351 var tick = this.layout.yticks[i];
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
361 var label = makeDiv(tick[1]);
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";
373 this.container.appendChild(label);
374 this.ylabels.push(label);
375 }
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) {
398 for (var i = 0; i < this.layout.xticks.length; i++) {
399 var tick = this.layout.xticks[i];
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
410 var label = makeDiv(tick[1]);
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";
426 this.container.appendChild(label);
427 this.xlabels.push(label);
428 }
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();
439};
440
441
442/**
443 * Overrides the CanvasRenderer method to draw error bars
444 */
445DygraphCanvasRenderer.prototype._renderLineChart = function() {
446 var context = this.element.getContext("2d");
447 var colorCount = this.options.colorScheme.length;
448 var colorScheme = this.options.colorScheme;
449 var errorBars = this.layout.options.errorBars;
450 var fillGraph = this.layout.options.fillGraph;
451
452 var setNames = [];
453 for (var name in this.layout.datasets) {
454 if (this.layout.datasets.hasOwnProperty(name)) {
455 setNames.push(name);
456 }
457 }
458 var setCount = setNames.length;
459
460 // Update Points
461 // TODO(danvk): here
462 for (var i = 0; i < this.layout.points.length; i++) {
463 var point = this.layout.points[i];
464 point.canvasx = this.area.w * point.x + this.area.x;
465 point.canvasy = this.area.h * point.y + this.area.y;
466 }
467
468 // create paths
469 var isOK = function(x) { return x && !isNaN(x); };
470
471 var ctx = context;
472 if (errorBars) {
473 if (fillGraph) {
474 this.dygraph_.warn("Can't use fillGraph option with error bars");
475 }
476
477 for (var i = 0; i < setCount; i++) {
478 var setName = setNames[i];
479 var color = colorScheme[i % colorCount];
480
481 // setup graphics context
482 ctx.save();
483 ctx.strokeStyle = color;
484 ctx.lineWidth = this.options.strokeWidth;
485 var prevX = -1;
486 var prevYs = [-1, -1];
487 var count = 0;
488 var yscale = this.layout.yscale;
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;
493 ctx.beginPath();
494 for (var j = 0; j < this.layout.points.length; j++) {
495 var point = this.layout.points[j];
496 count++;
497 if (point.name == setName) {
498 if (!isOK(point.y)) {
499 prevX = -1;
500 continue;
501 }
502 // TODO(danvk): here
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;
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) {
522 // TODO(danvk): merge this code with the logic above; they're very similar.
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;
556 if (prevX >= 0) {
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();
562 }
563 prevYs[0] = newYs[0];
564 prevYs[1] = newYs[1];
565 prevX = point.canvasx;
566 }
567 }
568 ctx.fill();
569 }
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;
612 ctx.arc(point.canvasx, point.canvasy, pointSize,
613 0, 2 * Math.PI, false);
614 ctx.fill();
615 }
616 }
617 }
618 }
619 }
620
621 context.restore();
622};