remove if statement
[dygraphs.git] / dygraph-canvas.js
1 /**
2 * @license
3 * Copyright 2006 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
5 */
6
7 /**
8 * @fileoverview Based on PlotKit.CanvasRenderer, but modified to meet the
9 * needs of dygraphs.
10 *
11 * In particular, support for:
12 * - grid overlays
13 * - error bars
14 * - dygraphs attribute system
15 */
16
17 /**
18 * The DygraphCanvasRenderer class does the actual rendering of the chart onto
19 * a canvas. It's based on PlotKit.CanvasRenderer.
20 * @param {Object} element The canvas to attach to
21 * @param {Object} elementContext The 2d context of the canvas (injected so it
22 * can be mocked for testing.)
23 * @param {Layout} layout The DygraphLayout object for this graph.
24 * @constructor
25 */
26
27 /*jshint globalstrict: true */
28 /*global Dygraph:false,RGBColor:false */
29 "use strict";
30
31
32 /**
33 * @constructor
34 *
35 * This gets called when there are "new points" to chart. This is generally the
36 * case when the underlying data being charted has changed. It is _not_ called
37 * in the common case that the user has zoomed or is panning the view.
38 *
39 * The chart canvas has already been created by the Dygraph object. The
40 * renderer simply gets a drawing context.
41 *
42 * @param {Dyraph} dygraph The chart to which this renderer belongs.
43 * @param {Canvas} element The <canvas> DOM element on which to draw.
44 * @param {CanvasRenderingContext2D} elementContext The drawing context.
45 * @param {DygraphLayout} layout The chart's DygraphLayout object.
46 *
47 * TODO(danvk): remove the elementContext property.
48 */
49 var DygraphCanvasRenderer = function(dygraph, element, elementContext, layout) {
50 this.dygraph_ = dygraph;
51
52 this.layout = layout;
53 this.element = element;
54 this.elementContext = elementContext;
55 this.container = this.element.parentNode;
56
57 this.height = this.element.height;
58 this.width = this.element.width;
59
60 // --- check whether everything is ok before we return
61 if (!this.isIE && !(DygraphCanvasRenderer.isSupported(this.element)))
62 throw "Canvas is not supported.";
63
64 // internal state
65 this.area = layout.getPlotArea();
66 this.container.style.position = "relative";
67 this.container.style.width = this.width + "px";
68
69 // Set up a clipping area for the canvas (and the interaction canvas).
70 // This ensures that we don't overdraw.
71 if (this.dygraph_.isUsingExcanvas_) {
72 this._createIEClipArea();
73 } else {
74 // on Android 3 and 4, setting a clipping area on a canvas prevents it from
75 // displaying anything.
76 if (!Dygraph.isAndroid()) {
77 var ctx = this.dygraph_.canvas_ctx_;
78 ctx.beginPath();
79 ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h);
80 ctx.clip();
81
82 ctx = this.dygraph_.hidden_ctx_;
83 ctx.beginPath();
84 ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h);
85 ctx.clip();
86 }
87 }
88 };
89
90 DygraphCanvasRenderer.prototype.attr_ = function(x) {
91 return this.dygraph_.attr_(x);
92 };
93
94 /**
95 * Clears out all chart content and DOM elements.
96 * This is called immediately before render() on every frame, including
97 * during zooms and pans.
98 * @private
99 */
100 DygraphCanvasRenderer.prototype.clear = function() {
101 var context;
102 if (this.isIE) {
103 // VML takes a while to start up, so we just poll every this.IEDelay
104 try {
105 if (this.clearDelay) {
106 this.clearDelay.cancel();
107 this.clearDelay = null;
108 }
109 context = this.elementContext;
110 }
111 catch (e) {
112 // TODO(danvk): this is broken, since MochiKit.Async is gone.
113 // this.clearDelay = MochiKit.Async.wait(this.IEDelay);
114 // this.clearDelay.addCallback(bind(this.clear, this));
115 return;
116 }
117 }
118
119 context = this.elementContext;
120 context.clearRect(0, 0, this.width, this.height);
121 };
122
123 /**
124 * Checks whether the browser supports the <canvas> tag.
125 * @private
126 */
127 DygraphCanvasRenderer.isSupported = function(canvasName) {
128 var canvas = null;
129 try {
130 if (typeof(canvasName) == 'undefined' || canvasName === null) {
131 canvas = document.createElement("canvas");
132 } else {
133 canvas = canvasName;
134 }
135 canvas.getContext("2d");
136 }
137 catch (e) {
138 var ie = navigator.appVersion.match(/MSIE (\d\.\d)/);
139 var opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
140 if ((!ie) || (ie[1] < 6) || (opera))
141 return false;
142 return true;
143 }
144 return true;
145 };
146
147 /**
148 * This method is responsible for drawing everything on the chart, including
149 * lines, error bars, fills and axes.
150 * It is called immediately after clear() on every frame, including during pans
151 * and zooms.
152 * @private
153 */
154 DygraphCanvasRenderer.prototype.render = function() {
155 this._renderLineChart();
156 };
157
158 DygraphCanvasRenderer.prototype._createIEClipArea = function() {
159 var className = 'dygraph-clip-div';
160 var graphDiv = this.dygraph_.graphDiv;
161
162 // Remove old clip divs.
163 for (var i = graphDiv.childNodes.length-1; i >= 0; i--) {
164 if (graphDiv.childNodes[i].className == className) {
165 graphDiv.removeChild(graphDiv.childNodes[i]);
166 }
167 }
168
169 // Determine background color to give clip divs.
170 var backgroundColor = document.bgColor;
171 var element = this.dygraph_.graphDiv;
172 while (element != document) {
173 var bgcolor = element.currentStyle.backgroundColor;
174 if (bgcolor && bgcolor != 'transparent') {
175 backgroundColor = bgcolor;
176 break;
177 }
178 element = element.parentNode;
179 }
180
181 function createClipDiv(area) {
182 if (area.w === 0 || area.h === 0) {
183 return;
184 }
185 var elem = document.createElement('div');
186 elem.className = className;
187 elem.style.backgroundColor = backgroundColor;
188 elem.style.position = 'absolute';
189 elem.style.left = area.x + 'px';
190 elem.style.top = area.y + 'px';
191 elem.style.width = area.w + 'px';
192 elem.style.height = area.h + 'px';
193 graphDiv.appendChild(elem);
194 }
195
196 var plotArea = this.area;
197 // Left side
198 createClipDiv({
199 x:0, y:0,
200 w:plotArea.x,
201 h:this.height
202 });
203
204 // Top
205 createClipDiv({
206 x: plotArea.x, y: 0,
207 w: this.width - plotArea.x,
208 h: plotArea.y
209 });
210
211 // Right side
212 createClipDiv({
213 x: plotArea.x + plotArea.w, y: 0,
214 w: this.width-plotArea.x - plotArea.w,
215 h: this.height
216 });
217
218 // Bottom
219 createClipDiv({
220 x: plotArea.x,
221 y: plotArea.y + plotArea.h,
222 w: this.width - plotArea.x,
223 h: this.height - plotArea.h - plotArea.y
224 });
225 };
226
227
228 /**
229 * Returns a predicate to be used with an iterator, which will
230 * iterate over points appropriately, depending on whether
231 * connectSeparatedPoints is true. When it's false, the predicate will
232 * skip over points with missing yVals.
233 */
234 DygraphCanvasRenderer._getIteratorPredicate = function(connectSeparatedPoints) {
235 return connectSeparatedPoints
236 ? DygraphCanvasRenderer._predicateThatSkipsEmptyPoints
237 : null;
238 }
239
240 DygraphCanvasRenderer._predicateThatSkipsEmptyPoints =
241 function(array, idx) { return array[idx].yval !== null; }
242
243 /**
244 *
245 * @private
246 */
247 DygraphCanvasRenderer.prototype._drawStyledLine = function(
248 ctx, i, setName, color, strokeWidth, strokePattern, drawPoints,
249 drawPointCallback, pointSize) {
250 // TODO(konigsberg): Compute attributes outside this method call.
251 var stepPlot = this.attr_("stepPlot");
252 var firstIndexInSet = this.layout.setPointsOffsets[i];
253 var setLength = this.layout.setPointsLengths[i];
254 var points = this.layout.points;
255 if (!Dygraph.isArrayLike(strokePattern)) {
256 strokePattern = null;
257 }
258 var drawGapPoints = this.dygraph_.attr_('drawGapEdgePoints', setName);
259
260 var iter = Dygraph.createIterator(points, firstIndexInSet, setLength,
261 DygraphCanvasRenderer._getIteratorPredicate(
262 this.attr_("connectSeparatedPoints")));
263
264 var stroking = strokePattern && (strokePattern.length >= 2);
265
266 ctx.save();
267 if (stroking) {
268 ctx.installPattern(strokePattern);
269 }
270
271 var pointsOnLine = this._drawSeries(ctx, iter, strokeWidth, pointSize, drawPoints, drawGapPoints, stepPlot, color);
272 this._drawPointsOnLine(ctx, pointsOnLine, drawPointCallback, setName, color, pointSize);
273
274 if (stroking) {
275 ctx.uninstallPattern();
276 }
277
278 ctx.restore();
279 };
280
281 DygraphCanvasRenderer.prototype._drawPointsOnLine = function(ctx, pointsOnLine, drawPointCallback, setName, color, pointSize) {
282 for (var idx = 0; idx < pointsOnLine.length; idx++) {
283 var cb = pointsOnLine[idx];
284 ctx.save();
285 drawPointCallback(
286 this.dygraph_, setName, ctx, cb[0], cb[1], color, pointSize);
287 ctx.restore();
288 }
289 }
290
291 DygraphCanvasRenderer.prototype._drawSeries = function(
292 ctx, iter, strokeWidth, pointSize, drawPoints, drawGapPoints,
293 stepPlot, color) {
294
295 var prevCanvasX = null;
296 var prevCanvasY = null;
297 var nextCanvasY = null;
298 var isIsolated; // true if this point is isolated (no line segments)
299 var point; // the point being processed in the while loop
300 var pointsOnLine = []; // Array of [canvasx, canvasy] pairs.
301 var first = true; // the first cycle through the while loop
302
303 ctx.beginPath();
304 ctx.strokeStyle = color;
305 ctx.lineWidth = strokeWidth;
306
307 while (iter.hasNext) {
308 point = iter.next();
309 if (point.canvasy === null || point.canvasy != point.canvasy) {
310 if (stepPlot && prevCanvasX !== null) {
311 // Draw a horizontal line to the start of the missing data
312 ctx.moveTo(prevX, prevY);
313 ctx.lineTo(point.canvasx, prevY);
314 }
315 prevCanvasX = prevCanvasY = null;
316 } else {
317 nextCanvasY = iter.hasNext ? iter.peek.canvasy : null;
318 // TODO: we calculate isNullOrNaN for this point, and the next, and then,
319 // when we iterate, test for isNullOrNaN again. Why bother?
320 var isNextCanvasYNullOrNaN = nextCanvasY === null || nextCanvasY != nextCanvasY;
321 isIsolated = (!prevCanvasX && isNextCanvasYNullOrNaN);
322 if (drawGapPoints) {
323 // Also consider a point to be "isolated" if it's adjacent to a
324 // null point, excluding the graph edges.
325 if ((!first && !prevCanvasX) ||
326 (iter.hasNext && isNextCanvasYNullOrNaN)) {
327 isIsolated = true;
328 }
329 }
330 if (prevCanvasX !== null) {
331 if (strokeWidth) {
332 if (stepPlot) {
333 ctx.moveTo(prevCanvasX, prevCanvasY);
334 ctx.lineTo(point.canvasx, prevCanvasY);
335 prevCanvasX = point.canvasx;
336 }
337 ctx.moveTo(prevCanvasX, prevCanvasY);
338 ctx.lineTo(point.canvasx, point.canvasy);
339 }
340 }
341 if (drawPoints || isIsolated) {
342 pointsOnLine.push([point.canvasx, point.canvasy]);
343 }
344 prevCanvasX = point.canvasx;
345 prevCanvasY = point.canvasy;
346 }
347 first = false;
348 }
349 ctx.stroke();
350 return pointsOnLine;
351 };
352
353 DygraphCanvasRenderer.prototype._drawLine = function(ctx, i) {
354 var setNames = this.layout.setNames;
355 var setName = setNames[i];
356
357 var strokeWidth = this.dygraph_.attr_("strokeWidth", setName);
358 var borderWidth = this.dygraph_.attr_("strokeBorderWidth", setName);
359 var drawPointCallback = this.dygraph_.attr_("drawPointCallback", setName) ||
360 Dygraph.Circles.DEFAULT;
361
362 if (borderWidth && strokeWidth) {
363 this._drawStyledLine(ctx, i, setName,
364 this.dygraph_.attr_("strokeBorderColor", setName),
365 strokeWidth + 2 * borderWidth,
366 this.dygraph_.attr_("strokePattern", setName),
367 this.dygraph_.attr_("drawPoints", setName),
368 drawPointCallback,
369 this.dygraph_.attr_("pointSize", setName));
370 }
371
372 this._drawStyledLine(ctx, i, setName,
373 this.colors[setName],
374 strokeWidth,
375 this.dygraph_.attr_("strokePattern", setName),
376 this.dygraph_.attr_("drawPoints", setName),
377 drawPointCallback,
378 this.dygraph_.attr_("pointSize", setName));
379 };
380
381 /**
382 * Actually draw the lines chart, including error bars.
383 * @private
384 */
385 DygraphCanvasRenderer.prototype._renderLineChart = function() {
386 var ctx = this.elementContext;
387 var errorBars = this.attr_("errorBars") || this.attr_("customBars");
388 var fillGraph = this.attr_("fillGraph");
389 var i;
390
391 var setNames = this.layout.setNames;
392 var setCount = setNames.length;
393
394 this.colors = this.dygraph_.colorsMap_;
395
396 // Update Points
397 // TODO(danvk): here
398 //
399 // TODO(bhs): this loop is a hot-spot for high-point-count charts. These
400 // transformations can be pushed into the canvas via linear transformation
401 // matrices.
402 var points = this.layout.points;
403 for (i = points.length; i--;) {
404 var point = points[i];
405 point.canvasx = this.area.w * point.x + this.area.x;
406 point.canvasy = this.area.h * point.y + this.area.y;
407 }
408
409 // Draw any "fills", i.e. error bars or the filled area under a series.
410 // These must all be drawn before any lines, so that the main lines of a
411 // series are drawn on top.
412 if (errorBars) {
413 if (fillGraph) {
414 this.dygraph_.warn("Can't use fillGraph option with error bars");
415 }
416
417 ctx.save();
418 this.drawErrorBars_(points);
419 ctx.restore();
420 } else if (fillGraph) {
421 ctx.save();
422 this.drawFillBars_(points);
423 ctx.restore();
424 }
425
426 // Drawing the lines.
427 for (i = 0; i < setCount; i += 1) {
428 this._drawLine(ctx, i);
429 }
430 };
431
432 /**
433 * Draws the shaded error bars/confidence intervals for each series.
434 * This happens before the center lines are drawn, since the center lines
435 * need to be drawn on top of the error bars for all series.
436 *
437 * @private
438 */
439 DygraphCanvasRenderer.prototype.drawErrorBars_ = function(points) {
440 var ctx = this.elementContext;
441 var setNames = this.layout.setNames;
442 var setCount = setNames.length;
443 var fillAlpha = this.attr_('fillAlpha');
444 var stepPlot = this.attr_('stepPlot');
445
446 var newYs;
447
448 for (var i = 0; i < setCount; i++) {
449 var setName = setNames[i];
450 var axis = this.dygraph_.axisPropertiesForSeries(setName);
451 var color = this.colors[setName];
452
453 var firstIndexInSet = this.layout.setPointsOffsets[i];
454 var setLength = this.layout.setPointsLengths[i];
455
456 var iter = Dygraph.createIterator(points, firstIndexInSet, setLength,
457 DygraphCanvasRenderer._getIteratorPredicate(
458 this.attr_("connectSeparatedPoints")));
459
460 // setup graphics context
461 var prevX = NaN;
462 var prevY = NaN;
463 var prevYs = [-1, -1];
464 var yscale = axis.yscale;
465 // should be same color as the lines but only 15% opaque.
466 var rgb = new RGBColor(color);
467 var err_color =
468 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + fillAlpha + ')';
469 ctx.fillStyle = err_color;
470 ctx.beginPath();
471 while (iter.hasNext) {
472 var point = iter.next();
473 if (point.name == setName) { // TODO(klausw): this is always true
474 if (!Dygraph.isOK(point.y)) {
475 prevX = NaN;
476 continue;
477 }
478
479 // TODO(danvk): here
480 if (stepPlot) {
481 newYs = [ point.y_bottom, point.y_top ];
482 prevY = point.y;
483 } else {
484 newYs = [ point.y_bottom, point.y_top ];
485 }
486 newYs[0] = this.area.h * newYs[0] + this.area.y;
487 newYs[1] = this.area.h * newYs[1] + this.area.y;
488 if (!isNaN(prevX)) {
489 if (stepPlot) {
490 ctx.moveTo(prevX, newYs[0]);
491 } else {
492 ctx.moveTo(prevX, prevYs[0]);
493 }
494 ctx.lineTo(point.canvasx, newYs[0]);
495 ctx.lineTo(point.canvasx, newYs[1]);
496 if (stepPlot) {
497 ctx.lineTo(prevX, newYs[1]);
498 } else {
499 ctx.lineTo(prevX, prevYs[1]);
500 }
501 ctx.closePath();
502 }
503 prevYs = newYs;
504 prevX = point.canvasx;
505 }
506 }
507 ctx.fill();
508 }
509 };
510
511 /**
512 * Draws the shaded regions when "fillGraph" is set. Not to be confused with
513 * error bars.
514 *
515 * @private
516 */
517 DygraphCanvasRenderer.prototype.drawFillBars_ = function(points) {
518 var ctx = this.elementContext;
519 var setNames = this.layout.setNames;
520 var setCount = setNames.length;
521 var fillAlpha = this.attr_('fillAlpha');
522 var stepPlot = this.attr_('stepPlot');
523 var stackedGraph = this.attr_("stackedGraph");
524
525 var baseline = {}; // for stacked graphs: baseline for filling
526 var currBaseline;
527
528 // process sets in reverse order (needed for stacked graphs)
529 for (var i = setCount - 1; i >= 0; i--) {
530 var setName = setNames[i];
531 var color = this.colors[setName];
532 var axis = this.dygraph_.axisPropertiesForSeries(setName);
533 var axisY = 1.0 + axis.minyval * axis.yscale;
534 if (axisY < 0.0) axisY = 0.0;
535 else if (axisY > 1.0) axisY = 1.0;
536 axisY = this.area.h * axisY + this.area.y;
537 var firstIndexInSet = this.layout.setPointsOffsets[i];
538 var setLength = this.layout.setPointsLengths[i];
539
540 var iter = Dygraph.createIterator(points, firstIndexInSet, setLength,
541 DygraphCanvasRenderer._getIteratorPredicate(
542 this.attr_("connectSeparatedPoints")));
543
544 // setup graphics context
545 var prevX = NaN;
546 var prevYs = [-1, -1];
547 var newYs;
548 var yscale = axis.yscale;
549 // should be same color as the lines but only 15% opaque.
550 var rgb = new RGBColor(color);
551 var err_color =
552 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + fillAlpha + ')';
553 ctx.fillStyle = err_color;
554 ctx.beginPath();
555 while(iter.hasNext) {
556 var point = iter.next();
557 if (!Dygraph.isOK(point.y)) {
558 prevX = NaN;
559 continue;
560 }
561 if (stackedGraph) {
562 currBaseline = baseline[point.canvasx];
563 var lastY;
564 if (currBaseline === undefined) {
565 lastY = axisY;
566 } else {
567 if(stepPlot) {
568 lastY = currBaseline[0];
569 } else {
570 lastY = currBaseline;
571 }
572 }
573 newYs = [ point.canvasy, lastY ];
574
575 if(stepPlot) {
576 // Step plots must keep track of the top and bottom of
577 // the baseline at each point.
578 if(prevYs[0] === -1) {
579 baseline[point.canvasx] = [ point.canvasy, axisY ];
580 } else {
581 baseline[point.canvasx] = [ point.canvasy, prevYs[0] ];
582 }
583 } else {
584 baseline[point.canvasx] = point.canvasy;
585 }
586
587 } else {
588 newYs = [ point.canvasy, axisY ];
589 }
590 if (!isNaN(prevX)) {
591 ctx.moveTo(prevX, prevYs[0]);
592
593 if (stepPlot) {
594 ctx.lineTo(point.canvasx, prevYs[0]);
595 if(currBaseline) {
596 // Draw to the bottom of the baseline
597 ctx.lineTo(point.canvasx, currBaseline[1]);
598 } else {
599 ctx.lineTo(point.canvasx, newYs[1]);
600 }
601 } else {
602 ctx.lineTo(point.canvasx, newYs[0]);
603 ctx.lineTo(point.canvasx, newYs[1]);
604 }
605
606 ctx.lineTo(prevX, prevYs[1]);
607 ctx.closePath();
608 }
609 prevYs = newYs;
610 prevX = point.canvasx;
611 }
612 ctx.fill();
613 }
614 };