add more comments to dashed-canvas.js
[dygraphs.git] / dygraph-canvas.js
... / ...
CommitLineData
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 */
49var 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
90DygraphCanvasRenderer.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 */
100DygraphCanvasRenderer.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 */
127DygraphCanvasRenderer.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 */
154DygraphCanvasRenderer.prototype.render = function() {
155 this._renderLineChart();
156};
157
158DygraphCanvasRenderer.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 */
234DygraphCanvasRenderer._getIteratorPredicate = function(connectSeparatedPoints) {
235 return connectSeparatedPoints
236 ? DygraphCanvasRenderer._predicateThatSkipsEmptyPoints
237 : null;
238};
239
240DygraphCanvasRenderer._predicateThatSkipsEmptyPoints =
241 function(array, idx) {
242 return array[idx].yval !== null;
243};
244
245/**
246 *
247 * @private
248 */
249DygraphCanvasRenderer.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
283DygraphCanvasRenderer.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
293DygraphCanvasRenderer.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 // NOTE: we break the iterator's encapsulation here for about a 25% speedup.
310 var arr = iter.array_;
311 var limit = iter.end_;
312 var predicate = iter.predicate_;
313
314 for (var i = iter.start_; i < limit; i++) {
315 point = arr[i];
316 if (predicate) {
317 while (i < limit && !predicate(arr, i)) {
318 i++;
319 }
320 if (i == limit) break;
321 point = arr[i];
322 }
323
324 if (point.canvasy === null || point.canvasy != point.canvasy) {
325 if (stepPlot && prevCanvasX !== null) {
326 // Draw a horizontal line to the start of the missing data
327 ctx.moveTo(prevX, prevY);
328 ctx.lineTo(point.canvasx, prevY);
329 }
330 prevCanvasX = prevCanvasY = null;
331 } else {
332 isIsolated = false;
333 if (drawGapPoints || !prevCanvasX) {
334 iter.nextIdx_ = i;
335 var peek = iter.next();
336 nextCanvasY = iter.hasNext ? iter.peek.canvasy : null;
337
338 var isNextCanvasYNullOrNaN = nextCanvasY === null ||
339 nextCanvasY != nextCanvasY;
340 isIsolated = (!prevCanvasX && isNextCanvasYNullOrNaN);
341 if (drawGapPoints) {
342 // Also consider a point to be "isolated" if it's adjacent to a
343 // null point, excluding the graph edges.
344 if ((!first && !prevCanvasX) ||
345 (iter.hasNext && isNextCanvasYNullOrNaN)) {
346 isIsolated = true;
347 }
348 }
349 }
350
351 if (prevCanvasX !== null) {
352 if (strokeWidth) {
353 if (stepPlot) {
354 ctx.moveTo(prevCanvasX, prevCanvasY);
355 ctx.lineTo(point.canvasx, prevCanvasY);
356 prevCanvasX = point.canvasx;
357 }
358
359 // TODO(danvk): this moveTo is rarely necessary
360 ctx.moveTo(prevCanvasX, prevCanvasY);
361 ctx.lineTo(point.canvasx, point.canvasy);
362 }
363 }
364 if (drawPoints || isIsolated) {
365 pointsOnLine.push([point.canvasx, point.canvasy]);
366 }
367 prevCanvasX = point.canvasx;
368 prevCanvasY = point.canvasy;
369 }
370 first = false;
371 }
372 ctx.stroke();
373 return pointsOnLine;
374};
375
376DygraphCanvasRenderer.prototype._drawLine = function(ctx, i) {
377 var setNames = this.layout.setNames;
378 var setName = setNames[i];
379
380 var strokeWidth = this.dygraph_.attr_("strokeWidth", setName);
381 var borderWidth = this.dygraph_.attr_("strokeBorderWidth", setName);
382 var drawPointCallback = this.dygraph_.attr_("drawPointCallback", setName) ||
383 Dygraph.Circles.DEFAULT;
384
385 if (borderWidth && strokeWidth) {
386 this._drawStyledLine(ctx, i, setName,
387 this.dygraph_.attr_("strokeBorderColor", setName),
388 strokeWidth + 2 * borderWidth,
389 this.dygraph_.attr_("strokePattern", setName),
390 this.dygraph_.attr_("drawPoints", setName),
391 drawPointCallback,
392 this.dygraph_.attr_("pointSize", setName));
393 }
394
395 this._drawStyledLine(ctx, i, setName,
396 this.colors[setName],
397 strokeWidth,
398 this.dygraph_.attr_("strokePattern", setName),
399 this.dygraph_.attr_("drawPoints", setName),
400 drawPointCallback,
401 this.dygraph_.attr_("pointSize", setName));
402};
403
404/**
405 * Actually draw the lines chart, including error bars.
406 * @private
407 */
408DygraphCanvasRenderer.prototype._renderLineChart = function() {
409 var ctx = this.elementContext;
410 var errorBars = this.attr_("errorBars") || this.attr_("customBars");
411 var fillGraph = this.attr_("fillGraph");
412 var i;
413
414 var setNames = this.layout.setNames;
415 var setCount = setNames.length;
416
417 this.colors = this.dygraph_.colorsMap_;
418
419 // Update Points
420 // TODO(danvk): here
421 //
422 // TODO(bhs): this loop is a hot-spot for high-point-count charts. These
423 // transformations can be pushed into the canvas via linear transformation
424 // matrices.
425 // NOTE(danvk): this is trickier than it sounds at first. The transformation
426 // needs to be done before the .moveTo() and .lineTo() calls, but must be
427 // undone before the .stroke() call to ensure that the stroke width is
428 // unaffected. An alternative is to reduce the stroke width in the
429 // transformed coordinate space, but you can't specify different values for
430 // each dimension (as you can with .scale()). The speedup here is ~12%.
431 var points = this.layout.points;
432 for (i = points.length; i--;) {
433 var point = points[i];
434 point.canvasx = this.area.w * point.x + this.area.x;
435 point.canvasy = this.area.h * point.y + this.area.y;
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 */
468DygraphCanvasRenderer.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 i = 0; i < setCount; i++) {
478 var setName = setNames[i];
479 var axis = this.dygraph_.axisPropertiesForSeries(setName);
480 var color = this.colors[setName];
481
482 var firstIndexInSet = this.layout.setPointsOffsets[i];
483 var setLength = this.layout.setPointsLengths[i];
484
485 var iter = Dygraph.createIterator(points, firstIndexInSet, setLength,
486 DygraphCanvasRenderer._getIteratorPredicate(
487 this.attr_("connectSeparatedPoints")));
488
489 // setup graphics context
490 var prevX = NaN;
491 var prevY = NaN;
492 var prevYs = [-1, -1];
493 var yscale = axis.yscale;
494 // should be same color as the lines but only 15% opaque.
495 var rgb = new RGBColor(color);
496 var err_color =
497 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + fillAlpha + ')';
498 ctx.fillStyle = err_color;
499 ctx.beginPath();
500 while (iter.hasNext) {
501 var point = iter.next();
502 if (!Dygraph.isOK(point.y)) {
503 prevX = NaN;
504 continue;
505 }
506
507 if (stepPlot) {
508 newYs = [ point.y_bottom, point.y_top ];
509 prevY = point.y;
510 } else {
511 newYs = [ point.y_bottom, point.y_top ];
512 }
513 newYs[0] = this.area.h * newYs[0] + this.area.y;
514 newYs[1] = this.area.h * newYs[1] + this.area.y;
515 if (!isNaN(prevX)) {
516 if (stepPlot) {
517 ctx.moveTo(prevX, newYs[0]);
518 } else {
519 ctx.moveTo(prevX, prevYs[0]);
520 }
521 ctx.lineTo(point.canvasx, newYs[0]);
522 ctx.lineTo(point.canvasx, newYs[1]);
523 if (stepPlot) {
524 ctx.lineTo(prevX, newYs[1]);
525 } else {
526 ctx.lineTo(prevX, prevYs[1]);
527 }
528 ctx.closePath();
529 }
530 prevYs = newYs;
531 prevX = point.canvasx;
532 }
533 ctx.fill();
534 }
535};
536
537/**
538 * Draws the shaded regions when "fillGraph" is set. Not to be confused with
539 * error bars.
540 *
541 * @private
542 */
543DygraphCanvasRenderer.prototype.drawFillBars_ = function(points) {
544 var ctx = this.elementContext;
545 var setNames = this.layout.setNames;
546 var setCount = setNames.length;
547 var fillAlpha = this.attr_('fillAlpha');
548 var stepPlot = this.attr_('stepPlot');
549 var stackedGraph = this.attr_("stackedGraph");
550
551 var baseline = {}; // for stacked graphs: baseline for filling
552 var currBaseline;
553
554 // process sets in reverse order (needed for stacked graphs)
555 for (var i = setCount - 1; i >= 0; i--) {
556 var setName = setNames[i];
557 var color = this.colors[setName];
558 var axis = this.dygraph_.axisPropertiesForSeries(setName);
559 var axisY = 1.0 + axis.minyval * axis.yscale;
560 if (axisY < 0.0) axisY = 0.0;
561 else if (axisY > 1.0) axisY = 1.0;
562 axisY = this.area.h * axisY + this.area.y;
563 var firstIndexInSet = this.layout.setPointsOffsets[i];
564 var setLength = this.layout.setPointsLengths[i];
565
566 var iter = Dygraph.createIterator(points, firstIndexInSet, setLength,
567 DygraphCanvasRenderer._getIteratorPredicate(
568 this.attr_("connectSeparatedPoints")));
569
570 // setup graphics context
571 var prevX = NaN;
572 var prevYs = [-1, -1];
573 var newYs;
574 var yscale = axis.yscale;
575 // should be same color as the lines but only 15% opaque.
576 var rgb = new RGBColor(color);
577 var err_color =
578 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + fillAlpha + ')';
579 ctx.fillStyle = err_color;
580 ctx.beginPath();
581 while(iter.hasNext) {
582 var point = iter.next();
583 if (!Dygraph.isOK(point.y)) {
584 prevX = NaN;
585 continue;
586 }
587 if (stackedGraph) {
588 currBaseline = baseline[point.canvasx];
589 var lastY;
590 if (currBaseline === undefined) {
591 lastY = axisY;
592 } else {
593 if(stepPlot) {
594 lastY = currBaseline[0];
595 } else {
596 lastY = currBaseline;
597 }
598 }
599 newYs = [ point.canvasy, lastY ];
600
601 if(stepPlot) {
602 // Step plots must keep track of the top and bottom of
603 // the baseline at each point.
604 if(prevYs[0] === -1) {
605 baseline[point.canvasx] = [ point.canvasy, axisY ];
606 } else {
607 baseline[point.canvasx] = [ point.canvasy, prevYs[0] ];
608 }
609 } else {
610 baseline[point.canvasx] = point.canvasy;
611 }
612
613 } else {
614 newYs = [ point.canvasy, axisY ];
615 }
616 if (!isNaN(prevX)) {
617 ctx.moveTo(prevX, prevYs[0]);
618
619 if (stepPlot) {
620 ctx.lineTo(point.canvasx, prevYs[0]);
621 if(currBaseline) {
622 // Draw to the bottom of the baseline
623 ctx.lineTo(point.canvasx, currBaseline[1]);
624 } else {
625 ctx.lineTo(point.canvasx, newYs[1]);
626 }
627 } else {
628 ctx.lineTo(point.canvasx, newYs[0]);
629 ctx.lineTo(point.canvasx, newYs[1]);
630 }
631
632 ctx.lineTo(prevX, prevYs[1]);
633 ctx.closePath();
634 }
635 prevYs = newYs;
636 prevX = point.canvasx;
637 }
638 ctx.fill();
639 }
640};