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