factor out dashed-canvas.js and use it in dygraph-canvas.js. one test failing
[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 ctx.save();
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 var pointsOnLine;
269 var strategy;
270 if (stroking) {
271 ctx.installPattern(strokePattern);
272 }
273
274 strategy = trivialStrategy(ctx, color, strokeWidth);
275 pointsOnLine = this._drawSeries(ctx, iter, strokeWidth, pointSize, drawPoints, drawGapPoints, stepPlot, strategy);
276 this._drawPointsOnLine(ctx, pointsOnLine, drawPointCallback, setName, color, pointSize);
277
278 if (stroking) {
279 ctx.uninstallPattern();
280 }
281
282 ctx.restore();
283 };
284
285 var trivialStrategy = function(ctx, color, strokeWidth) {
286 return new function() {
287 this.init = function() {
288 ctx.beginPath();
289 ctx.strokeStyle = color;
290 ctx.lineWidth = strokeWidth;
291 };
292 this.finish = function() {
293 ctx.stroke(); // should this include closePath?
294 };
295 this.startSegment = function() { };
296 this.endSegment = function() { };
297 this.drawLine = function(x1, y1, x2, y2) {
298 ctx.moveTo(x1, y1);
299 ctx.lineTo(x2, y2);
300 };
301 // don't skip pixels.
302 this.skipPixel = function() {
303 return false;
304 };
305 };
306 };
307
308 DygraphCanvasRenderer.prototype._drawPointsOnLine = function(ctx, pointsOnLine, drawPointCallback, setName, color, pointSize) {
309 for (var idx = 0; idx < pointsOnLine.length; idx++) {
310 var cb = pointsOnLine[idx];
311 ctx.save();
312 drawPointCallback(
313 this.dygraph_, setName, ctx, cb[0], cb[1], color, pointSize);
314 ctx.restore();
315 }
316 }
317
318 DygraphCanvasRenderer.prototype._drawSeries = function(
319 ctx, iter, strokeWidth, pointSize, drawPoints, drawGapPoints,
320 stepPlot, strategy) {
321
322 var prevCanvasX = null;
323 var prevCanvasY = null;
324 var nextCanvasY = null;
325 var isIsolated; // true if this point is isolated (no line segments)
326 var point; // the point being processed in the while loop
327 var pointsOnLine = []; // Array of [canvasx, canvasy] pairs.
328 var first = true; // the first cycle through the while loop
329
330 strategy.init();
331
332 while(iter.hasNext) {
333 point = iter.next();
334 if (point.canvasy === null || point.canvasy != point.canvasy) {
335 if (stepPlot && prevCanvasX !== null) {
336 // Draw a horizontal line to the start of the missing data
337 strategy.startSegment();
338 strategy.drawLine(prevX, prevY, point.canvasx, prevY);
339 strategy.endSegment();
340 }
341 prevCanvasX = prevCanvasY = null;
342 } else {
343 nextCanvasY = iter.hasNext ? iter.peek.canvasy : null;
344 // TODO: we calculate isNullOrNaN for this point, and the next, and then,
345 // when we iterate, test for isNullOrNaN again. Why bother?
346 var isNextCanvasYNullOrNaN = nextCanvasY === null || nextCanvasY != nextCanvasY;
347 isIsolated = (!prevCanvasX && isNextCanvasYNullOrNaN);
348 if (drawGapPoints) {
349 // Also consider a point to be "isolated" if it's adjacent to a
350 // null point, excluding the graph edges.
351 if ((!first && !prevCanvasX) ||
352 (iter.hasNext && isNextCanvasYNullOrNaN)) {
353 isIsolated = true;
354 }
355 }
356 if (prevCanvasX !== null) {
357 if (strategy.skipPixel(prevCanvasX, prevCanvasY, point.canvasx, point.canvasy)) {
358 continue;
359 }
360 if (strokeWidth) {
361 strategy.startSegment();
362 if (stepPlot) {
363 strategy.drawLine(prevCanvasX, prevCanvasY, point.canvasx, prevCanvasY);
364 prevCanvasX = point.canvasx;
365 }
366 strategy.drawLine(prevCanvasX, prevCanvasY, point.canvasx, point.canvasy);
367 strategy.endSegment();
368 }
369 }
370 if (drawPoints || isIsolated) {
371 pointsOnLine.push([point.canvasx, point.canvasy]);
372 }
373 prevCanvasX = point.canvasx;
374 prevCanvasY = point.canvasy;
375 }
376 first = false;
377 }
378 strategy.finish();
379 return pointsOnLine;
380 };
381
382 DygraphCanvasRenderer.prototype._drawLine = function(ctx, i) {
383 var setNames = this.layout.setNames;
384 var setName = setNames[i];
385
386 var strokeWidth = this.dygraph_.attr_("strokeWidth", setName);
387 var borderWidth = this.dygraph_.attr_("strokeBorderWidth", setName);
388 var drawPointCallback = this.dygraph_.attr_("drawPointCallback", setName) ||
389 Dygraph.Circles.DEFAULT;
390
391 if (borderWidth && strokeWidth) {
392 this._drawStyledLine(ctx, i, setName,
393 this.dygraph_.attr_("strokeBorderColor", setName),
394 strokeWidth + 2 * borderWidth,
395 this.dygraph_.attr_("strokePattern", setName),
396 this.dygraph_.attr_("drawPoints", setName),
397 drawPointCallback,
398 this.dygraph_.attr_("pointSize", setName));
399 }
400
401 this._drawStyledLine(ctx, i, setName,
402 this.colors[setName],
403 strokeWidth,
404 this.dygraph_.attr_("strokePattern", setName),
405 this.dygraph_.attr_("drawPoints", setName),
406 drawPointCallback,
407 this.dygraph_.attr_("pointSize", setName));
408 };
409
410 /**
411 * Actually draw the lines chart, including error bars.
412 * @private
413 */
414 DygraphCanvasRenderer.prototype._renderLineChart = function() {
415 var ctx = this.elementContext;
416 var errorBars = this.attr_("errorBars") || this.attr_("customBars");
417 var fillGraph = this.attr_("fillGraph");
418 var i;
419
420 var setNames = this.layout.setNames;
421 var setCount = setNames.length;
422
423 this.colors = this.dygraph_.colorsMap_;
424
425 // Update Points
426 // TODO(danvk): here
427 //
428 // TODO(bhs): this loop is a hot-spot for high-point-count charts. These
429 // transformations can be pushed into the canvas via linear transformation
430 // matrices.
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 */
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 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 (point.name == setName) { // TODO(klausw): this is always true
503 if (!Dygraph.isOK(point.y)) {
504 prevX = NaN;
505 continue;
506 }
507
508 // TODO(danvk): here
509 if (stepPlot) {
510 newYs = [ point.y_bottom, point.y_top ];
511 prevY = point.y;
512 } else {
513 newYs = [ point.y_bottom, point.y_top ];
514 }
515 newYs[0] = this.area.h * newYs[0] + this.area.y;
516 newYs[1] = this.area.h * newYs[1] + this.area.y;
517 if (!isNaN(prevX)) {
518 if (stepPlot) {
519 ctx.moveTo(prevX, newYs[0]);
520 } else {
521 ctx.moveTo(prevX, prevYs[0]);
522 }
523 ctx.lineTo(point.canvasx, newYs[0]);
524 ctx.lineTo(point.canvasx, newYs[1]);
525 if (stepPlot) {
526 ctx.lineTo(prevX, newYs[1]);
527 } else {
528 ctx.lineTo(prevX, prevYs[1]);
529 }
530 ctx.closePath();
531 }
532 prevYs = newYs;
533 prevX = point.canvasx;
534 }
535 }
536 ctx.fill();
537 }
538 };
539
540 /**
541 * Draws the shaded regions when "fillGraph" is set. Not to be confused with
542 * error bars.
543 *
544 * @private
545 */
546 DygraphCanvasRenderer.prototype.drawFillBars_ = function(points) {
547 var ctx = this.elementContext;
548 var setNames = this.layout.setNames;
549 var setCount = setNames.length;
550 var fillAlpha = this.attr_('fillAlpha');
551 var stepPlot = this.attr_('stepPlot');
552 var stackedGraph = this.attr_("stackedGraph");
553
554 var baseline = {}; // for stacked graphs: baseline for filling
555 var currBaseline;
556
557 // process sets in reverse order (needed for stacked graphs)
558 for (var i = setCount - 1; i >= 0; i--) {
559 var setName = setNames[i];
560 var color = this.colors[setName];
561 var axis = this.dygraph_.axisPropertiesForSeries(setName);
562 var axisY = 1.0 + axis.minyval * axis.yscale;
563 if (axisY < 0.0) axisY = 0.0;
564 else if (axisY > 1.0) axisY = 1.0;
565 axisY = this.area.h * axisY + this.area.y;
566 var firstIndexInSet = this.layout.setPointsOffsets[i];
567 var setLength = this.layout.setPointsLengths[i];
568
569 var iter = Dygraph.createIterator(points, firstIndexInSet, setLength,
570 DygraphCanvasRenderer._getIteratorPredicate(
571 this.attr_("connectSeparatedPoints")));
572
573 // setup graphics context
574 var prevX = NaN;
575 var prevYs = [-1, -1];
576 var newYs;
577 var yscale = axis.yscale;
578 // should be same color as the lines but only 15% opaque.
579 var rgb = new RGBColor(color);
580 var err_color =
581 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + fillAlpha + ')';
582 ctx.fillStyle = err_color;
583 ctx.beginPath();
584 while(iter.hasNext) {
585 var point = iter.next();
586 if (point.name == setName) { // TODO(klausw): this is always true
587 if (!Dygraph.isOK(point.y)) {
588 prevX = NaN;
589 continue;
590 }
591 if (stackedGraph) {
592 currBaseline = baseline[point.canvasx];
593 var lastY;
594 if (currBaseline === undefined) {
595 lastY = axisY;
596 } else {
597 if(stepPlot) {
598 lastY = currBaseline[0];
599 } else {
600 lastY = currBaseline;
601 }
602 }
603 newYs = [ point.canvasy, lastY ];
604
605 if(stepPlot) {
606 // Step plots must keep track of the top and bottom of
607 // the baseline at each point.
608 if(prevYs[0] === -1) {
609 baseline[point.canvasx] = [ point.canvasy, axisY ];
610 } else {
611 baseline[point.canvasx] = [ point.canvasy, prevYs[0] ];
612 }
613 } else {
614 baseline[point.canvasx] = point.canvasy;
615 }
616
617 } else {
618 newYs = [ point.canvasy, axisY ];
619 }
620 if (!isNaN(prevX)) {
621 ctx.moveTo(prevX, prevYs[0]);
622
623 if (stepPlot) {
624 ctx.lineTo(point.canvasx, prevYs[0]);
625 if(currBaseline) {
626 // Draw to the bottom of the baseline
627 ctx.lineTo(point.canvasx, currBaseline[1]);
628 } else {
629 ctx.lineTo(point.canvasx, newYs[1]);
630 }
631 } else {
632 ctx.lineTo(point.canvasx, newYs[0]);
633 ctx.lineTo(point.canvasx, newYs[1]);
634 }
635
636 ctx.lineTo(prevX, prevYs[1]);
637 ctx.closePath();
638 }
639 prevYs = newYs;
640 prevX = point.canvasx;
641 }
642 }
643 ctx.fill();
644 }
645 };