dependence on PlotKit.Canvas is severed
[dygraphs.git] / dygraph-canvas.js
CommitLineData
6a1aa64f
DV
1// Copyright 2006 Dan Vanderkam (danvdk@gmail.com)
2// All Rights Reserved.
3
4/**
5 * @fileoverview Subclasses various parts of PlotKit to meet the additional
285a6bda 6 * needs of Dygraph: grid overlays and error bars
6a1aa64f
DV
7 */
8
9// Subclass PlotKit.Layout to add:
10// 1. Sigma/errorBars properties
11// 2. Copy error terms for PlotKit.CanvasRenderer._renderLineChart
12
13/**
285a6bda 14 * Creates a new DygraphLayout object. Options are the same as those allowed
6a1aa64f
DV
15 * by the PlotKit.Layout constructor.
16 * @param {Object} options Options for PlotKit.Layout
285a6bda 17 * @return {Object} The DygraphLayout object
6a1aa64f 18 */
efe0829a
DV
19DygraphLayout = function(dygraph, options) {
20 this.dygraph_ = dygraph;
21 this.options = {}; // TODO(danvk): remove, use attr_ instead.
22 MochiKit.Base.update(this.options, options ? options : {});
23 this.datasets = new Array();
6a1aa64f 24};
efe0829a
DV
25
26DygraphLayout.prototype.attr_ = function(name) {
27 return this.dygraph_.attr_(name);
28};
29
30DygraphLayout.prototype.addDataset = function(setname, set_xy) {
31 this.datasets[setname] = set_xy;
32};
33
34DygraphLayout.prototype.evaluate = function() {
35 this._evaluateLimits();
36 this._evaluateLineCharts();
37 this._evaluateLineTicks();
38};
39
40DygraphLayout.prototype._evaluateLimits = function() {
41 this.minxval = this.maxxval = null;
42 for (var name in this.datasets) {
43 var series = this.datasets[name];
44 var x1 = series[0][0];
45 if (!this.minxval || x1 < this.minxval) this.minxval = x1;
46
47 var x2 = series[series.length - 1][0];
48 if (!this.maxxval || x2 > this.maxxval) this.maxxval = x2;
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) {
63 var dataset = this.datasets[setName];
64 for (var j = 0; j < dataset.length; j++) {
65 var item = dataset[j];
66 var point = {
67 x: ((parseFloat(item[0]) - this.minxval) * this.xscale),
68 y: 1.0 - ((parseFloat(item[1]) - this.minyval) * this.yscale),
69 xval: parseFloat(item[0]),
70 yval: parseFloat(item[1]),
71 name: setName
72 };
73
74 // limit the x, y values so they do not overdraw
75 if (point.y <= 0.0) {
76 point.y = 0.0;
77 }
78 if (point.y >= 1.0) {
79 point.y = 1.0;
80 }
81 if ((point.x >= 0.0) && (point.x <= 1.0)) {
82 this.points.push(point);
83 }
84 }
85 }
86};
87
88DygraphLayout.prototype._evaluateLineTicks = function() {
89 this.xticks = new Array();
90 for (var i = 0; i < this.options.xTicks.length; i++) {
91 var tick = this.options.xTicks[i];
92 var label = tick.label;
93 var pos = this.xscale * (tick.v - this.minxval);
94 if ((pos >= 0.0) && (pos <= 1.0)) {
95 this.xticks.push([pos, label]);
96 }
97 }
98
99 this.yticks = new Array();
100 for (var i = 0; i < this.options.yTicks.length; i++) {
101 var tick = this.options.yTicks[i];
102 var label = tick.label;
103 var pos = 1.0 - (this.yscale * (tick.v - this.minyval));
104 if ((pos >= 0.0) && (pos <= 1.0)) {
105 this.yticks.push([pos, label]);
106 }
107 }
108};
109
6a1aa64f
DV
110
111/**
112 * Behaves the same way as PlotKit.Layout, but also copies the errors
113 * @private
114 */
285a6bda 115DygraphLayout.prototype.evaluateWithError = function() {
6a1aa64f
DV
116 this.evaluate();
117 if (!this.options.errorBars) return;
118
119 // Copy over the error terms
120 var i = 0; // index in this.points
121 for (var setName in this.datasets) {
122 var j = 0;
123 var dataset = this.datasets[setName];
124 if (PlotKit.Base.isFuncLike(dataset)) continue;
125 for (var j = 0; j < dataset.length; j++, i++) {
126 var item = dataset[j];
127 var xv = parseFloat(item[0]);
128 var yv = parseFloat(item[1]);
129
130 if (xv == this.points[i].xval &&
131 yv == this.points[i].yval) {
132 this.points[i].errorMinus = parseFloat(item[2]);
133 this.points[i].errorPlus = parseFloat(item[3]);
134 }
135 }
136 }
137};
138
139/**
140 * Convenience function to remove all the data sets from a graph
141 */
285a6bda 142DygraphLayout.prototype.removeAllDatasets = function() {
6a1aa64f
DV
143 delete this.datasets;
144 this.datasets = new Array();
145};
146
147/**
148 * Change the values of various layout options
149 * @param {Object} new_options an associative array of new properties
150 */
285a6bda 151DygraphLayout.prototype.updateOptions = function(new_options) {
6a1aa64f
DV
152 MochiKit.Base.update(this.options, new_options ? new_options : {});
153};
154
155// Subclass PlotKit.CanvasRenderer to add:
156// 1. X/Y grid overlay
157// 2. Ability to draw error bars (if required)
158
159/**
160 * Sets some PlotKit.CanvasRenderer options
161 * @param {Object} element The canvas to attach to
285a6bda 162 * @param {Layout} layout The DygraphLayout object for this graph.
6a1aa64f
DV
163 * @param {Object} options Options to pass on to CanvasRenderer
164 */
9317362d
DV
165DygraphCanvasRenderer = function(dygraph, element, layout, options) {
166 // TODO(danvk): remove options, just use dygraph.attr_.
9317362d 167 this.dygraph_ = dygraph;
fbe31dc8
DV
168
169 // default options
170 this.options = {
171 "strokeWidth": 0.5,
172 "drawXAxis": true,
173 "drawYAxis": true,
174 "axisLineColor": Color.blackColor(),
175 "axisLineWidth": 0.5,
176 "axisTickSize": 3,
177 "axisLabelColor": Color.blackColor(),
178 "axisLabelFont": "Arial",
179 "axisLabelFontSize": 9,
180 "axisLabelWidth": 50,
181 "drawYGrid": true,
182 "drawXGrid": true,
183 "gridLineColor": MochiKit.Color.Color.grayColor()
184 };
6a1aa64f
DV
185 MochiKit.Base.update(this.options, options);
186
fbe31dc8
DV
187 this.layout = layout;
188 this.element = MochiKit.DOM.getElement(element);
189 this.container = this.element.parentNode;
190
191 // Stuff relating to Canvas on IE support
192 this.isIE = PlotKit.Base.excanvasSupported();
193
194 if (this.isIE && !isNil(G_vmlCanvasManager)) {
195 this.IEDelay = 0.5;
196 this.maxTries = 5;
197 this.renderDelay = null;
198 this.clearDelay = null;
199 this.element = G_vmlCanvasManager.initElement(this.element);
200 }
201
202 this.height = this.element.height;
203 this.width = this.element.width;
204
205 // --- check whether everything is ok before we return
206 if (!this.isIE && !(DygraphCanvasRenderer.isSupported(this.element)))
207 throw "Canvas is not supported.";
208
209 // internal state
210 this.xlabels = new Array();
211 this.ylabels = new Array();
212
213 this.area = {
214 x: this.options.yAxisLabelWidth + 2 * this.options.axisTickSize,
215 y: 0
216 };
217 this.area.w = this.width - this.area.x - this.options.rightGap;
218 this.area.h = this.height - this.options.axisLabelFontSize -
219 2 * this.options.axisTickSize;
220
221 MochiKit.DOM.updateNodeAttributes(this.container,
222 {"style":{ "position": "relative", "width": this.width + "px"}});
223};
224
225DygraphCanvasRenderer.prototype.clear = function() {
226 if (this.isIE) {
227 // VML takes a while to start up, so we just poll every this.IEDelay
228 try {
229 if (this.clearDelay) {
230 this.clearDelay.cancel();
231 this.clearDelay = null;
232 }
233 var context = this.element.getContext("2d");
234 }
235 catch (e) {
236 this.clearDelay = MochiKit.Async.wait(this.IEDelay);
237 this.clearDelay.addCallback(bind(this.clear, this));
238 return;
239 }
240 }
241
242 var context = this.element.getContext("2d");
243 context.clearRect(0, 0, this.width, this.height);
244
245 MochiKit.Iter.forEach(this.xlabels, MochiKit.DOM.removeElement);
246 MochiKit.Iter.forEach(this.ylabels, MochiKit.DOM.removeElement);
247 this.xlabels = new Array();
248 this.ylabels = new Array();
249};
250
251
252DygraphCanvasRenderer.isSupported = function(canvasName) {
253 var canvas = null;
254 try {
255 if (MochiKit.Base.isUndefinedOrNull(canvasName))
256 canvas = MochiKit.DOM.CANVAS({});
257 else
258 canvas = MochiKit.DOM.getElement(canvasName);
259 var context = canvas.getContext("2d");
260 }
261 catch (e) {
262 var ie = navigator.appVersion.match(/MSIE (\d\.\d)/);
263 var opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
264 if ((!ie) || (ie[1] < 6) || (opera))
265 return false;
266 return true;
267 }
268 return true;
6a1aa64f 269};
6a1aa64f
DV
270
271/**
272 * Draw an X/Y grid on top of the existing plot
273 */
285a6bda 274DygraphCanvasRenderer.prototype.render = function() {
6a1aa64f
DV
275 // Draw the new X/Y grid
276 var ctx = this.element.getContext("2d");
277 if (this.options.drawYGrid) {
278 var ticks = this.layout.yticks;
279 ctx.save();
280 ctx.strokeStyle = this.options.gridLineColor.toRGBString();
281 ctx.lineWidth = this.options.axisLineWidth;
282 for (var i = 0; i < ticks.length; i++) {
283 var x = this.area.x;
284 var y = this.area.y + ticks[i][0] * this.area.h;
285 ctx.beginPath();
286 ctx.moveTo(x, y);
287 ctx.lineTo(x + this.area.w, y);
288 ctx.closePath();
289 ctx.stroke();
290 }
291 }
292
293 if (this.options.drawXGrid) {
294 var ticks = this.layout.xticks;
295 ctx.save();
296 ctx.strokeStyle = this.options.gridLineColor.toRGBString();
297 ctx.lineWidth = this.options.axisLineWidth;
298 for (var i=0; i<ticks.length; i++) {
299 var x = this.area.x + ticks[i][0] * this.area.w;
300 var y = this.area.y + this.area.h;
301 ctx.beginPath();
302 ctx.moveTo(x, y);
303 ctx.lineTo(x, this.area.y);
304 ctx.closePath();
305 ctx.stroke();
306 }
307 }
2ce09b19
DV
308
309 // Do the ordinary rendering, as before
310 // TODO(danvk) Call super.render()
311 this._renderLineChart();
fbe31dc8
DV
312 this._renderAxis();
313};
314
315
316DygraphCanvasRenderer.prototype._renderAxis = function() {
317 if (!this.options.drawXAxis && !this.options.drawYAxis)
318 return;
319
320 var context = this.element.getContext("2d");
321
322 var labelStyle = {"style":
323 {"position": "absolute",
324 "fontSize": this.options.axisLabelFontSize + "px",
325 "zIndex": 10,
326 "color": this.options.axisLabelColor.toRGBString(),
327 "width": this.options.axisLabelWidth + "px",
328 "overflow": "hidden"
329 }
330 };
331
332 // axis lines
333 context.save();
334 context.strokeStyle = this.options.axisLineColor.toRGBString();
335 context.lineWidth = this.options.axisLineWidth;
336
337
338 if (this.options.drawYAxis) {
339 if (this.layout.yticks) {
340 var drawTick = function(tick) {
341 if (typeof(tick) == "function") return;
342 var x = this.area.x;
343 var y = this.area.y + tick[0] * this.area.h;
344 context.beginPath();
345 context.moveTo(x, y);
346 context.lineTo(x - this.options.axisTickSize, y);
347 context.closePath();
348 context.stroke();
349
350 var label = DIV(labelStyle, tick[1]);
351 var top = (y - this.options.axisLabelFontSize / 2);
352 if (top < 0) top = 0;
353
354 if (top + this.options.axisLabelFontSize + 3 > this.height) {
355 label.style.bottom = "0px";
356 } else {
357 label.style.top = top + "px";
358 }
359 label.style.left = "0px";
360 label.style.textAlign = "right";
361 label.style.width = this.options.yAxisLabelWidth + "px";
362 MochiKit.DOM.appendChildNodes(this.container, label);
363 this.ylabels.push(label);
364 };
365
366 MochiKit.Iter.forEach(this.layout.yticks, bind(drawTick, this));
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) {
389 var drawTick = function(tick) {
390 if (typeof(dataset) == "function") return;
391
392 var x = this.area.x + tick[0] * this.area.w;
393 var y = this.area.y + this.area.h;
394 context.beginPath();
395 context.moveTo(x, y);
396 context.lineTo(x, y + this.options.axisTickSize);
397 context.closePath();
398 context.stroke();
399
400 var label = DIV(labelStyle, tick[1]);
401 label.style.textAlign = "center";
402 label.style.bottom = "0px";
403
404 var left = (x - this.options.axisLabelWidth/2);
405 if (left + this.options.axisLabelWidth > this.width) {
406 left = this.width - this.options.xAxisLabelWidth;
407 label.style.textAlign = "right";
408 }
409 if (left < 0) {
410 left = 0;
411 label.style.textAlign = "left";
412 }
413
414 label.style.left = left + "px";
415 label.style.width = this.options.xAxisLabelWidth + "px";
416 MochiKit.DOM.appendChildNodes(this.container, label);
417 this.xlabels.push(label);
418 };
419
420 MochiKit.Iter.forEach(this.layout.xticks, bind(drawTick, this));
421 }
422
423 context.beginPath();
424 context.moveTo(this.area.x, this.area.y + this.area.h);
425 context.lineTo(this.area.x + this.area.w, this.area.y + this.area.h);
426 context.closePath();
427 context.stroke();
428 }
429
430 context.restore();
6a1aa64f
DV
431};
432
fbe31dc8 433
6a1aa64f
DV
434/**
435 * Overrides the CanvasRenderer method to draw error bars
436 */
285a6bda 437DygraphCanvasRenderer.prototype._renderLineChart = function() {
6a1aa64f
DV
438 var context = this.element.getContext("2d");
439 var colorCount = this.options.colorScheme.length;
440 var colorScheme = this.options.colorScheme;
441 var setNames = MochiKit.Base.keys(this.layout.datasets);
442 var errorBars = this.layout.options.errorBars;
443 var setCount = setNames.length;
444 var bind = MochiKit.Base.bind;
445 var partial = MochiKit.Base.partial;
446
447 //Update Points
448 var updatePoint = function(point) {
449 point.canvasx = this.area.w * point.x + this.area.x;
450 point.canvasy = this.area.h * point.y + this.area.y;
451 }
452 MochiKit.Iter.forEach(this.layout.points, updatePoint, this);
453
454 // create paths
9317362d 455 var isOK = function(x) { return x && !isNaN(x); };
6a1aa64f
DV
456 var makePath = function(ctx) {
457 for (var i = 0; i < setCount; i++) {
458 var setName = setNames[i];
459 var color = colorScheme[i%colorCount];
460 var strokeX = this.options.strokeColorTransform;
461
462 // setup graphics context
463 context.save();
464 context.strokeStyle = color.toRGBString();
465 context.lineWidth = this.options.strokeWidth;
6a1aa64f 466 var point = this.layout.points[0];
9317362d
DV
467 var pointSize = this.dygraph_.attr_("pointSize");
468 var prevX = null, prevY = null;
469 var drawPoints = this.dygraph_.attr_("drawPoints");
470 var points = this.layout.points;
471 for (var j = 0; j < points.length; j++) {
472 var point = points[j];
6a1aa64f 473 if (point.name == setName) {
9317362d 474 if (!isOK(point.canvasy)) {
9a730910 475 // this will make us move to the next point, not draw a line to it.
9317362d 476 prevX = prevY = null;
9a730910 477 } else {
9317362d
DV
478 // A point is "isolated" if it is non-null but both the previous
479 // and next points are null.
480 var isIsolated = (!prevX && (j == points.length - 1 ||
481 !isOK(points[j+1].canvasy)));
482
483 if (!prevX) {
484 prevX = point.canvasx;
485 prevY = point.canvasy;
9a730910 486 } else {
9317362d
DV
487 ctx.beginPath();
488 ctx.moveTo(prevX, prevY);
489 prevX = point.canvasx;
490 prevY = point.canvasy;
491 ctx.lineTo(prevX, prevY);
492 ctx.stroke();
493 }
494
495 if (drawPoints || isIsolated) {
496 ctx.beginPath();
497 ctx.fillStyle = color.toRGBString();
498 ctx.arc(point.canvasx, point.canvasy, pointSize, 0, 360, false);
499 ctx.fill();
9a730910
DV
500 }
501 }
6a1aa64f 502 }
9317362d 503 }
6a1aa64f
DV
504 }
505 };
506
507 var makeErrorBars = function(ctx) {
508 for (var i = 0; i < setCount; i++) {
509 var setName = setNames[i];
510 var color = colorScheme[i % colorCount];
511 var strokeX = this.options.strokeColorTransform;
512
513 // setup graphics context
514 context.save();
515 context.strokeStyle = color.toRGBString();
516 context.lineWidth = this.options.strokeWidth;
517 var prevX = -1;
518 var prevYs = [-1, -1];
519 var count = 0;
520 var yscale = this.layout.yscale;
521 var errorTrapezoid = function(ctx_,point) {
522 count++;
523 if (point.name == setName) {
5011e7a1
DV
524 if (!point.y || isNaN(point.y)) {
525 prevX = -1;
526 return;
527 }
6a1aa64f
DV
528 var newYs = [ point.y - point.errorPlus * yscale,
529 point.y + point.errorMinus * yscale ];
530 newYs[0] = this.area.h * newYs[0] + this.area.y;
531 newYs[1] = this.area.h * newYs[1] + this.area.y;
532 if (prevX >= 0) {
533 ctx_.moveTo(prevX, prevYs[0]);
534 ctx_.lineTo(point.canvasx, newYs[0]);
535 ctx_.lineTo(point.canvasx, newYs[1]);
536 ctx_.lineTo(prevX, prevYs[1]);
537 ctx_.closePath();
538 }
539 prevYs[0] = newYs[0];
540 prevYs[1] = newYs[1];
541 prevX = point.canvasx;
542 }
543 };
544 // should be same color as the lines
545 var err_color = color.colorWithAlpha(0.15);
546 ctx.fillStyle = err_color.toRGBString();
547 ctx.beginPath();
548 MochiKit.Iter.forEach(this.layout.points, partial(errorTrapezoid, ctx), this);
549 ctx.fill();
550 }
551 };
552
553 if (errorBars)
554 bind(makeErrorBars, this)(context);
555 bind(makePath, this)(context);
556 context.restore();
557};