only expected failures
[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) {
242 return array[idx].yval !== null;
243 };
244
245 /**
246 *
247 * @private
248 */
249 DygraphCanvasRenderer.prototype._drawStyledLine = function(
250 ctx, i, setName, color, strokeWidth, strokePattern, drawPoints,
251 drawPointCallback, pointSize) {
252 // TODO(konigsberg): Compute attributes outside this method call.
253 var stepPlot = this.attr_("stepPlot");
254 var firstIndexInSet = this.layout.setPointsOffsets[i];
255 var setLength = this.layout.setPointsLengths[i];
256 var points = this.layout.points;
257 if (!Dygraph.isArrayLike(strokePattern)) {
258 strokePattern = null;
259 }
260 var drawGapPoints = this.dygraph_.attr_('drawGapEdgePoints', setName);
261
262 var iter = Dygraph.createIterator(points, firstIndexInSet, setLength,
263 DygraphCanvasRenderer._getIteratorPredicate(
264 this.attr_("connectSeparatedPoints")));
265
266 var stroking = strokePattern && (strokePattern.length >= 2);
267
268 ctx.save();
269 if (stroking) {
270 ctx.installPattern(strokePattern);
271 }
272
273 var pointsOnLine = this._drawSeries(ctx, iter, strokeWidth, pointSize, drawPoints, drawGapPoints, stepPlot, color);
274 this._drawPointsOnLine(ctx, pointsOnLine, drawPointCallback, setName, color, pointSize);
275
276 if (stroking) {
277 ctx.uninstallPattern();
278 }
279
280 ctx.restore();
281 };
282
283 DygraphCanvasRenderer.prototype._drawPointsOnLine = function(ctx, pointsOnLine, drawPointCallback, setName, color, pointSize) {
284 for (var idx = 0; idx < pointsOnLine.length; idx++) {
285 var cb = pointsOnLine[idx];
286 ctx.save();
287 drawPointCallback(
288 this.dygraph_, setName, ctx, cb[0], cb[1], color, pointSize);
289 ctx.restore();
290 }
291 }
292
293 DygraphCanvasRenderer.prototype._drawSeries = function(
294 ctx, iter, strokeWidth, pointSize, drawPoints, drawGapPoints,
295 stepPlot, color) {
296
297 var prevCanvasX = null;
298 var prevCanvasY = null;
299 var nextCanvasY = null;
300 var isIsolated; // true if this point is isolated (no line segments)
301 var point; // the point being processed in the while loop
302 var pointsOnLine = []; // Array of [canvasx, canvasy] pairs.
303 var first = true; // the first cycle through the while loop
304
305 ctx.beginPath();
306 ctx.strokeStyle = color;
307 ctx.lineWidth = strokeWidth;
308
309 for (var i = iter.start_; i < iter.end_; i++) {
310 // while (iter.hasNext) {
311 point = iter.array_[i];
312 if (iter.predicate_) {
313 while (i < iter.end_ && !iter.predicate_(iter.array_, i)) {
314 i++;
315 }
316 if (i == iter.end_) break;
317 point = iter.array_[i];
318 }
319
320 if (point.canvasy === null || point.canvasy != point.canvasy) {
321 if (stepPlot && prevCanvasX !== null) {
322 // Draw a horizontal line to the start of the missing data
323 ctx.moveTo(prevX, prevY);
324 ctx.lineTo(point.canvasx, prevY);
325 }
326 prevCanvasX = prevCanvasY = null;
327 } else {
328 isIsolated = false;
329 if (drawGapPoints || !prevCanvasX) {
330 // nextCanvasY = iter.hasNext ? iter.peek.canvasy : null;
331 // var next_i = i + 1;
332 // while (next_i < iter.end_ && (!iter.predicate_ || !iter.predicate_(iter.array_, next_i))) {
333 // next_i++;
334 // }
335 iter.nextIdx_ = i;
336 var peek = iter.next();
337 nextCanvasY = iter.hasNext ? iter.peek.canvasy : null;
338 // nextCanvasY = next_i < iter.end_ ? iter.array_[next_i].canvasy : null;
339
340 // TODO: we calculate isNullOrNaN for this point, and the next, and then,
341 // when we iterate, test for isNullOrNaN again. Why bother?
342 var isNextCanvasYNullOrNaN = nextCanvasY === null ||
343 nextCanvasY != nextCanvasY;
344 isIsolated = (!prevCanvasX && isNextCanvasYNullOrNaN);
345 if (drawGapPoints) {
346 // Also consider a point to be "isolated" if it's adjacent to a
347 // null point, excluding the graph edges.
348 if ((!first && !prevCanvasX) ||
349 (iter.hasNext && isNextCanvasYNullOrNaN)) {
350 isIsolated = true;
351 }
352 }
353 }
354
355 if (prevCanvasX !== null) {
356 if (strokeWidth) {
357 if (stepPlot) {
358 ctx.moveTo(prevCanvasX, prevCanvasY);
359 ctx.lineTo(point.canvasx, prevCanvasY);
360 prevCanvasX = point.canvasx;
361 }
362 ctx.moveTo(prevCanvasX, prevCanvasY);
363 ctx.lineTo(point.canvasx, point.canvasy);
364 }
365 }
366 if (drawPoints || isIsolated) {
367 pointsOnLine.push([point.canvasx, point.canvasy]);
368 }
369 prevCanvasX = point.canvasx;
370 prevCanvasY = point.canvasy;
371 }
372 first = false;
373 }
374 ctx.stroke();
375 return pointsOnLine;
376 };
377
378 DygraphCanvasRenderer.prototype._drawLine = function(ctx, i) {
379 var setNames = this.layout.setNames;
380 var setName = setNames[i];
381
382 var strokeWidth = this.dygraph_.attr_("strokeWidth", setName);
383 var borderWidth = this.dygraph_.attr_("strokeBorderWidth", setName);
384 var drawPointCallback = this.dygraph_.attr_("drawPointCallback", setName) ||
385 Dygraph.Circles.DEFAULT;
386
387 if (borderWidth && strokeWidth) {
388 this._drawStyledLine(ctx, i, setName,
389 this.dygraph_.attr_("strokeBorderColor", setName),
390 strokeWidth + 2 * borderWidth,
391 this.dygraph_.attr_("strokePattern", setName),
392 this.dygraph_.attr_("drawPoints", setName),
393 drawPointCallback,
394 this.dygraph_.attr_("pointSize", setName));
395 }
396
397 this._drawStyledLine(ctx, i, setName,
398 this.colors[setName],
399 strokeWidth,
400 this.dygraph_.attr_("strokePattern", setName),
401 this.dygraph_.attr_("drawPoints", setName),
402 drawPointCallback,
403 this.dygraph_.attr_("pointSize", setName));
404 };
405
406 /**
407 * Actually draw the lines chart, including error bars.
408 * @private
409 */
410 DygraphCanvasRenderer.prototype._renderLineChart = function() {
411 var ctx = this.elementContext;
412 var errorBars = this.attr_("errorBars") || this.attr_("customBars");
413 var fillGraph = this.attr_("fillGraph");
414 var i;
415
416 var setNames = this.layout.setNames;
417 var setCount = setNames.length;
418
419 this.colors = this.dygraph_.colorsMap_;
420
421 // Update Points
422 // TODO(danvk): here
423 //
424 // TODO(bhs): this loop is a hot-spot for high-point-count charts. These
425 // transformations can be pushed into the canvas via linear transformation
426 // matrices.
427 var points = this.layout.points;
428 for (i = points.length; i--;) {
429 var point = points[i];
430 point.canvasx = this.area.w * point.x + this.area.x;
431 point.canvasy = this.area.h * point.y + this.area.y;
432 }
433
434 // Draw any "fills", i.e. error bars or the filled area under a series.
435 // These must all be drawn before any lines, so that the main lines of a
436 // series are drawn on top.
437 if (errorBars) {
438 if (fillGraph) {
439 this.dygraph_.warn("Can't use fillGraph option with error bars");
440 }
441
442 ctx.save();
443 this.drawErrorBars_(points);
444 ctx.restore();
445 } else if (fillGraph) {
446 ctx.save();
447 this.drawFillBars_(points);
448 ctx.restore();
449 }
450
451 // Drawing the lines.
452 for (i = 0; i < setCount; i += 1) {
453 this._drawLine(ctx, i);
454 }
455 };
456
457 /**
458 * Draws the shaded error bars/confidence intervals for each series.
459 * This happens before the center lines are drawn, since the center lines
460 * need to be drawn on top of the error bars for all series.
461 *
462 * @private
463 */
464 DygraphCanvasRenderer.prototype.drawErrorBars_ = function(points) {
465 var ctx = this.elementContext;
466 var setNames = this.layout.setNames;
467 var setCount = setNames.length;
468 var fillAlpha = this.attr_('fillAlpha');
469 var stepPlot = this.attr_('stepPlot');
470
471 var newYs;
472
473 for (var i = 0; i < setCount; i++) {
474 var setName = setNames[i];
475 var axis = this.dygraph_.axisPropertiesForSeries(setName);
476 var color = this.colors[setName];
477
478 var firstIndexInSet = this.layout.setPointsOffsets[i];
479 var setLength = this.layout.setPointsLengths[i];
480
481 var iter = Dygraph.createIterator(points, firstIndexInSet, setLength,
482 DygraphCanvasRenderer._getIteratorPredicate(
483 this.attr_("connectSeparatedPoints")));
484
485 // setup graphics context
486 var prevX = NaN;
487 var prevY = NaN;
488 var prevYs = [-1, -1];
489 var yscale = axis.yscale;
490 // should be same color as the lines but only 15% opaque.
491 var rgb = new RGBColor(color);
492 var err_color =
493 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + fillAlpha + ')';
494 ctx.fillStyle = err_color;
495 ctx.beginPath();
496 while (iter.hasNext) {
497 var point = iter.next();
498 if (!Dygraph.isOK(point.y)) {
499 prevX = NaN;
500 continue;
501 }
502
503 // TODO(danvk): here
504 if (stepPlot) {
505 newYs = [ point.y_bottom, point.y_top ];
506 prevY = point.y;
507 } else {
508 newYs = [ point.y_bottom, point.y_top ];
509 }
510 newYs[0] = this.area.h * newYs[0] + this.area.y;
511 newYs[1] = this.area.h * newYs[1] + this.area.y;
512 if (!isNaN(prevX)) {
513 if (stepPlot) {
514 ctx.moveTo(prevX, newYs[0]);
515 } else {
516 ctx.moveTo(prevX, prevYs[0]);
517 }
518 ctx.lineTo(point.canvasx, newYs[0]);
519 ctx.lineTo(point.canvasx, newYs[1]);
520 if (stepPlot) {
521 ctx.lineTo(prevX, newYs[1]);
522 } else {
523 ctx.lineTo(prevX, prevYs[1]);
524 }
525 ctx.closePath();
526 }
527 prevYs = newYs;
528 prevX = point.canvasx;
529 }
530 ctx.fill();
531 }
532 };
533
534 /**
535 * Draws the shaded regions when "fillGraph" is set. Not to be confused with
536 * error bars.
537 *
538 * @private
539 */
540 DygraphCanvasRenderer.prototype.drawFillBars_ = function(points) {
541 var ctx = this.elementContext;
542 var setNames = this.layout.setNames;
543 var setCount = setNames.length;
544 var fillAlpha = this.attr_('fillAlpha');
545 var stepPlot = this.attr_('stepPlot');
546 var stackedGraph = this.attr_("stackedGraph");
547
548 var baseline = {}; // for stacked graphs: baseline for filling
549 var currBaseline;
550
551 // process sets in reverse order (needed for stacked graphs)
552 for (var i = setCount - 1; i >= 0; i--) {
553 var setName = setNames[i];
554 var color = this.colors[setName];
555 var axis = this.dygraph_.axisPropertiesForSeries(setName);
556 var axisY = 1.0 + axis.minyval * axis.yscale;
557 if (axisY < 0.0) axisY = 0.0;
558 else if (axisY > 1.0) axisY = 1.0;
559 axisY = this.area.h * axisY + this.area.y;
560 var firstIndexInSet = this.layout.setPointsOffsets[i];
561 var setLength = this.layout.setPointsLengths[i];
562
563 var iter = Dygraph.createIterator(points, firstIndexInSet, setLength,
564 DygraphCanvasRenderer._getIteratorPredicate(
565 this.attr_("connectSeparatedPoints")));
566
567 // setup graphics context
568 var prevX = NaN;
569 var prevYs = [-1, -1];
570 var newYs;
571 var yscale = axis.yscale;
572 // should be same color as the lines but only 15% opaque.
573 var rgb = new RGBColor(color);
574 var err_color =
575 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + fillAlpha + ')';
576 ctx.fillStyle = err_color;
577 ctx.beginPath();
578 while(iter.hasNext) {
579 var point = iter.next();
580 if (!Dygraph.isOK(point.y)) {
581 prevX = NaN;
582 continue;
583 }
584 if (stackedGraph) {
585 currBaseline = baseline[point.canvasx];
586 var lastY;
587 if (currBaseline === undefined) {
588 lastY = axisY;
589 } else {
590 if(stepPlot) {
591 lastY = currBaseline[0];
592 } else {
593 lastY = currBaseline;
594 }
595 }
596 newYs = [ point.canvasy, lastY ];
597
598 if(stepPlot) {
599 // Step plots must keep track of the top and bottom of
600 // the baseline at each point.
601 if(prevYs[0] === -1) {
602 baseline[point.canvasx] = [ point.canvasy, axisY ];
603 } else {
604 baseline[point.canvasx] = [ point.canvasy, prevYs[0] ];
605 }
606 } else {
607 baseline[point.canvasx] = point.canvasy;
608 }
609
610 } else {
611 newYs = [ point.canvasy, axisY ];
612 }
613 if (!isNaN(prevX)) {
614 ctx.moveTo(prevX, prevYs[0]);
615
616 if (stepPlot) {
617 ctx.lineTo(point.canvasx, prevYs[0]);
618 if(currBaseline) {
619 // Draw to the bottom of the baseline
620 ctx.lineTo(point.canvasx, currBaseline[1]);
621 } else {
622 ctx.lineTo(point.canvasx, newYs[1]);
623 }
624 } else {
625 ctx.lineTo(point.canvasx, newYs[0]);
626 ctx.lineTo(point.canvasx, newYs[1]);
627 }
628
629 ctx.lineTo(prevX, prevYs[1]);
630 ctx.closePath();
631 }
632 prevYs = newYs;
633 prevX = point.canvasx;
634 }
635 ctx.fill();
636 }
637 };