Checkpoint: axes fully ported to plugin system. All tests pass.
[dygraphs.git] / dygraph-canvas.js
CommitLineData
88e95c46
DV
1/**
2 * @license
3 * Copyright 2006 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
5 */
6a1aa64f
DV
6
7/**
74a5af31
DV
8 * @fileoverview Based on PlotKit.CanvasRenderer, but modified to meet the
9 * needs of dygraphs.
10 *
3df0ccf0 11 * In particular, support for:
0abfbd7e 12 * - grid overlays
3df0ccf0
DV
13 * - error bars
14 * - dygraphs attribute system
6a1aa64f
DV
15 */
16
6a1aa64f 17/**
423f5ed3
DV
18 * The DygraphCanvasRenderer class does the actual rendering of the chart onto
19 * a canvas. It's based on PlotKit.CanvasRenderer.
6a1aa64f 20 * @param {Object} element The canvas to attach to
2cf95fff
RK
21 * @param {Object} elementContext The 2d context of the canvas (injected so it
22 * can be mocked for testing.)
285a6bda 23 * @param {Layout} layout The DygraphLayout object for this graph.
74a5af31 24 * @constructor
6a1aa64f 25 */
c0f54d4f 26
758a629f
DV
27/*jshint globalstrict: true */
28/*global Dygraph:false,RGBColor:false */
c0f54d4f
DV
29"use strict";
30
79253bd0 31
8cfe592f
DV
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 */
c0f54d4f 49var DygraphCanvasRenderer = function(dygraph, element, elementContext, layout) {
9317362d 50 this.dygraph_ = dygraph;
fbe31dc8 51
fbe31dc8 52 this.layout = layout;
b0c3b730 53 this.element = element;
2cf95fff 54 this.elementContext = elementContext;
fbe31dc8
DV
55 this.container = this.element.parentNode;
56
fbe31dc8
DV
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
70be5ed1 65 this.area = layout.getPlotArea();
423f5ed3
DV
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.
920208fb
PF
71 if (this.dygraph_.isUsingExcanvas_) {
72 this._createIEClipArea();
73 } else {
971870e5
DV
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();
920208fb 81
971870e5
DV
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 }
920208fb 87 }
423f5ed3
DV
88};
89
90DygraphCanvasRenderer.prototype.attr_ = function(x) {
91 return this.dygraph_.attr_(x);
92};
93
8cfe592f
DV
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 */
fbe31dc8 100DygraphCanvasRenderer.prototype.clear = function() {
758a629f 101 var context;
fbe31dc8
DV
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 }
758a629f 109 context = this.elementContext;
fbe31dc8
DV
110 }
111 catch (e) {
76171648 112 // TODO(danvk): this is broken, since MochiKit.Async is gone.
758a629f
DV
113 // this.clearDelay = MochiKit.Async.wait(this.IEDelay);
114 // this.clearDelay.addCallback(bind(this.clear, this));
fbe31dc8
DV
115 return;
116 }
117 }
118
758a629f 119 context = this.elementContext;
fbe31dc8 120 context.clearRect(0, 0, this.width, this.height);
fbe31dc8
DV
121};
122
8cfe592f
DV
123/**
124 * Checks whether the browser supports the <canvas> tag.
125 * @private
126 */
fbe31dc8
DV
127DygraphCanvasRenderer.isSupported = function(canvasName) {
128 var canvas = null;
129 try {
758a629f 130 if (typeof(canvasName) == 'undefined' || canvasName === null) {
b0c3b730 131 canvas = document.createElement("canvas");
758a629f 132 } else {
b0c3b730 133 canvas = canvasName;
758a629f
DV
134 }
135 canvas.getContext("2d");
fbe31dc8
DV
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;
6a1aa64f 145};
6a1aa64f
DV
146
147/**
600d841a
DV
148 * @param { [String] } colors Array of color strings. Should have one entry for
149 * each series to be rendered.
150 */
151DygraphCanvasRenderer.prototype.setColors = function(colors) {
152 this.colorScheme_ = colors;
153};
154
155/**
8cfe592f
DV
156 * This method is responsible for drawing everything on the chart, including
157 * lines, error bars, fills and axes.
158 * It is called immediately after clear() on every frame, including during pans
159 * and zooms.
160 * @private
6a1aa64f 161 */
285a6bda 162DygraphCanvasRenderer.prototype.render = function() {
528ce7e5
DV
163 // Draw the new X/Y grid. Lines appear crisper when pixels are rounded to
164 // half-integers. This prevents them from drawing in two rows/cols.
2cf95fff 165 var ctx = this.elementContext;
758a629f
DV
166 function halfUp(x) { return Math.round(x) + 0.5; }
167 function halfDown(y){ return Math.round(y) - 0.5; }
e7746234 168
423f5ed3 169 if (this.attr_('underlayCallback')) {
1e41bd2d
DV
170 // NOTE: we pass the dygraph object to this callback twice to avoid breaking
171 // users who expect a deprecated form of this callback.
423f5ed3 172 this.attr_('underlayCallback')(ctx, this.area, this.dygraph_, this.dygraph_);
e7746234
EC
173 }
174
758a629f 175 var x, y, i, ticks;
423f5ed3 176 if (this.attr_('drawYGrid')) {
758a629f 177 ticks = this.layout.yticks;
bbba718a 178 // TODO(konigsberg): I don't think these calls to save() have a corresponding restore().
6a1aa64f 179 ctx.save();
423f5ed3 180 ctx.strokeStyle = this.attr_('gridLineColor');
990d6a35 181 ctx.lineWidth = this.attr_('gridLineWidth');
758a629f 182 for (i = 0; i < ticks.length; i++) {
880a574f 183 // TODO(danvk): allow secondary axes to draw a grid, too.
758a629f
DV
184 if (ticks[i][0] !== 0) continue;
185 x = halfUp(this.area.x);
186 y = halfDown(this.area.y + ticks[i][1] * this.area.h);
6a1aa64f
DV
187 ctx.beginPath();
188 ctx.moveTo(x, y);
189 ctx.lineTo(x + this.area.w, y);
190 ctx.closePath();
191 ctx.stroke();
192 }
6bf4df7f 193 ctx.restore();
6a1aa64f
DV
194 }
195
423f5ed3 196 if (this.attr_('drawXGrid')) {
758a629f 197 ticks = this.layout.xticks;
6a1aa64f 198 ctx.save();
423f5ed3 199 ctx.strokeStyle = this.attr_('gridLineColor');
990d6a35 200 ctx.lineWidth = this.attr_('gridLineWidth');
758a629f
DV
201 for (i=0; i<ticks.length; i++) {
202 x = halfUp(this.area.x + ticks[i][0] * this.area.w);
203 y = halfDown(this.area.y + this.area.h);
6a1aa64f 204 ctx.beginPath();
880a574f 205 ctx.moveTo(x, y);
6a1aa64f
DV
206 ctx.lineTo(x, this.area.y);
207 ctx.closePath();
208 ctx.stroke();
209 }
6bf4df7f 210 ctx.restore();
6a1aa64f 211 }
2ce09b19
DV
212
213 // Do the ordinary rendering, as before
2ce09b19 214 this._renderLineChart();
fbe31dc8
DV
215};
216
920208fb
PF
217DygraphCanvasRenderer.prototype._createIEClipArea = function() {
218 var className = 'dygraph-clip-div';
219 var graphDiv = this.dygraph_.graphDiv;
220
221 // Remove old clip divs.
222 for (var i = graphDiv.childNodes.length-1; i >= 0; i--) {
223 if (graphDiv.childNodes[i].className == className) {
224 graphDiv.removeChild(graphDiv.childNodes[i]);
225 }
226 }
227
228 // Determine background color to give clip divs.
229 var backgroundColor = document.bgColor;
230 var element = this.dygraph_.graphDiv;
231 while (element != document) {
232 var bgcolor = element.currentStyle.backgroundColor;
233 if (bgcolor && bgcolor != 'transparent') {
234 backgroundColor = bgcolor;
235 break;
236 }
237 element = element.parentNode;
238 }
239
240 function createClipDiv(area) {
758a629f 241 if (area.w === 0 || area.h === 0) {
920208fb
PF
242 return;
243 }
244 var elem = document.createElement('div');
245 elem.className = className;
246 elem.style.backgroundColor = backgroundColor;
247 elem.style.position = 'absolute';
248 elem.style.left = area.x + 'px';
249 elem.style.top = area.y + 'px';
250 elem.style.width = area.w + 'px';
251 elem.style.height = area.h + 'px';
252 graphDiv.appendChild(elem);
253 }
254
255 var plotArea = this.area;
256 // Left side
758a629f
DV
257 createClipDiv({
258 x:0, y:0,
259 w:plotArea.x,
260 h:this.height
261 });
262
920208fb 263 // Top
758a629f
DV
264 createClipDiv({
265 x: plotArea.x, y: 0,
266 w: this.width - plotArea.x,
267 h: plotArea.y
268 });
269
920208fb 270 // Right side
758a629f
DV
271 createClipDiv({
272 x: plotArea.x + plotArea.w, y: 0,
273 w: this.width-plotArea.x - plotArea.w,
274 h: this.height
275 });
276
920208fb 277 // Bottom
758a629f
DV
278 createClipDiv({
279 x: plotArea.x,
280 y: plotArea.y + plotArea.h,
281 w: this.width - plotArea.x,
282 h: this.height - plotArea.h - plotArea.y
283 });
284};
fbe31dc8 285
fbe31dc8 286
ccb0001c 287/**
8722284b
RK
288 * Returns a predicate to be used with an iterator, which will
289 * iterate over points appropriately, depending on whether
290 * connectSeparatedPoints is true. When it's false, the predicate will
291 * skip over points with missing yVals.
ccb0001c 292 */
8722284b
RK
293DygraphCanvasRenderer._getIteratorPredicate = function(connectSeparatedPoints) {
294 return connectSeparatedPoints ? DygraphCanvasRenderer._predicateThatSkipsEmptyPoints : null;
295}
296
297DygraphCanvasRenderer._predicateThatSkipsEmptyPoints =
298 function(array, idx) { return array[idx].yval !== null; }
04c104d7 299
857a6931 300DygraphCanvasRenderer.prototype._drawStyledLine = function(
5469113b
KW
301 ctx, i, setName, color, strokeWidth, strokePattern, drawPoints,
302 drawPointCallback, pointSize) {
99a77a04 303 // TODO(konigsberg): Compute attributes outside this method call.
857a6931
KW
304 var stepPlot = this.attr_("stepPlot");
305 var firstIndexInSet = this.layout.setPointsOffsets[i];
306 var setLength = this.layout.setPointsLengths[i];
857a6931 307 var points = this.layout.points;
857a6931
KW
308 if (!Dygraph.isArrayLike(strokePattern)) {
309 strokePattern = null;
310 }
a5a50727 311 var drawGapPoints = this.dygraph_.attr_('drawGapEdgePoints', setName);
857a6931 312
b843b52c 313 ctx.save();
7d1afbb9 314
7d1afbb9 315 var iter = Dygraph.createIterator(points, firstIndexInSet, setLength,
8722284b 316 DygraphCanvasRenderer._getIteratorPredicate(this.attr_("connectSeparatedPoints")));
7d1afbb9 317
31f8e58b
RK
318 var pointsOnLine;
319 var strategy;
320 if (!strokePattern || strokePattern.length <= 1) {
321 strategy = trivialStrategy(ctx, color, strokeWidth);
b843b52c 322 } else {
31f8e58b 323 strategy = nonTrivialStrategy(this, ctx, color, strokeWidth, strokePattern);
b843b52c 324 }
31f8e58b
RK
325 pointsOnLine = this._drawSeries(ctx, iter, strokeWidth, pointSize, drawPoints, drawGapPoints, stepPlot, strategy);
326 this._drawPointsOnLine(ctx, pointsOnLine, drawPointCallback, setName, color, pointSize);
327
b843b52c
RK
328 ctx.restore();
329};
330
31f8e58b
RK
331var nonTrivialStrategy = function(renderer, ctx, color, strokeWidth, strokePattern) {
332 return new function() {
333 this.init = function() { };
334 this.finish = function() { };
335 this.startSegment = function() {
336 ctx.beginPath();
337 ctx.strokeStyle = color;
338 ctx.lineWidth = strokeWidth;
339 };
340 this.endSegment = function() {
341 ctx.stroke(); // should this include closePath?
342 };
343 this.drawLine = function(x1, y1, x2, y2) {
344 renderer._dashedLine(ctx, x1, y1, x2, y2, strokePattern);
345 };
346 this.skipPixel = function(prevX, prevY, curX, curY) {
347 // TODO(konigsberg): optimize with http://jsperf.com/math-round-vs-hack/6 ?
348 return (Math.round(prevX) == Math.round(curX) &&
349 Math.round(prevY) == Math.round(curY));
350 };
351 };
352};
353
354var trivialStrategy = function(ctx, color, strokeWidth) {
355 return new function() {
356 this.init = function() {
357 ctx.beginPath();
358 ctx.strokeStyle = color;
359 ctx.lineWidth = strokeWidth;
360 };
361 this.finish = function() {
362 ctx.stroke(); // should this include closePath?
363 };
364 this.startSegment = function() { };
365 this.endSegment = function() { };
366 this.drawLine = function(x1, y1, x2, y2) {
367 ctx.moveTo(x1, y1);
368 ctx.lineTo(x2, y2);
369 };
370 // don't skip pixels.
371 this.skipPixel = function() {
372 return false;
373 };
374 };
375};
376
a401ca8a
RK
377DygraphCanvasRenderer.prototype._drawPointsOnLine = function(ctx, pointsOnLine, drawPointCallback, setName, color, pointSize) {
378 for (var idx = 0; idx < pointsOnLine.length; idx++) {
379 var cb = pointsOnLine[idx];
380 ctx.save();
381 drawPointCallback(
382 this.dygraph_, setName, ctx, cb[0], cb[1], color, pointSize);
383 ctx.restore();
384 }
385}
386
31f8e58b
RK
387DygraphCanvasRenderer.prototype._drawSeries = function(
388 ctx, iter, strokeWidth, pointSize, drawPoints, drawGapPoints,
389 stepPlot, strategy) {
390
31f8e58b
RK
391 var prevCanvasX = null;
392 var prevCanvasY = null;
393 var nextCanvasY = null;
394 var isIsolated; // true if this point is isolated (no line segments)
395 var point; // the point being processed in the while loop
b843b52c 396 var pointsOnLine = []; // Array of [canvasx, canvasy] pairs.
31f8e58b
RK
397 var first = true; // the first cycle through the while loop
398
399 strategy.init();
400
7d1afbb9
RK
401 while(iter.hasNext()) {
402 point = iter.next();
a02978e2 403 if (point.canvasy === null || point.canvasy != point.canvasy) {
31f8e58b 404 if (stepPlot && prevCanvasX !== null) {
857a6931 405 // Draw a horizontal line to the start of the missing data
31f8e58b
RK
406 strategy.startSegment();
407 strategy.drawLine(prevX, prevY, point.canvasx, prevY);
408 strategy.endSegment();
857a6931 409 }
31f8e58b 410 prevCanvasX = prevCanvasY = null;
857a6931 411 } else {
31f8e58b 412 nextCanvasY = iter.hasNext() ? iter.peek().canvasy : null;
a02978e2
RK
413 // TODO: we calculate isNullOrNaN for this point, and the next, and then, when
414 // we iterate, test for isNullOrNaN again. Why bother?
415 var isNextCanvasYNullOrNaN = nextCanvasY === null || nextCanvasY != nextCanvasY;
416 isIsolated = (!prevCanvasX && isNextCanvasYNullOrNaN);
19b84fe7 417 if (drawGapPoints) {
31f8e58b 418 // Also consider a point to be "isolated" if it's adjacent to a
19b84fe7 419 // null point, excluding the graph edges.
31f8e58b 420 if ((!first && !prevCanvasX) ||
a02978e2 421 (iter.hasNext() && isNextCanvasYNullOrNaN)) {
19b84fe7
KW
422 isIsolated = true;
423 }
424 }
31f8e58b
RK
425 if (prevCanvasX !== null) {
426 if (strategy.skipPixel(prevCanvasX, prevCanvasY, point.canvasx, point.canvasy)) {
857a6931
KW
427 continue;
428 }
857a6931 429 if (strokeWidth) {
31f8e58b 430 strategy.startSegment();
857a6931 431 if (stepPlot) {
31f8e58b
RK
432 strategy.drawLine(prevCanvasX, prevCanvasY, point.canvasx, prevCanvasY);
433 prevCanvasX = point.canvasx;
857a6931 434 }
31f8e58b
RK
435 strategy.drawLine(prevCanvasX, prevCanvasY, point.canvasx, point.canvasy);
436 strategy.endSegment();
b843b52c
RK
437 }
438 }
b843b52c
RK
439 if (drawPoints || isIsolated) {
440 pointsOnLine.push([point.canvasx, point.canvasy]);
441 }
31f8e58b
RK
442 prevCanvasX = point.canvasx;
443 prevCanvasY = point.canvasy;
b843b52c 444 }
7d1afbb9 445 first = false;
b843b52c 446 }
31f8e58b
RK
447 strategy.finish();
448 return pointsOnLine;
857a6931
KW
449};
450
451DygraphCanvasRenderer.prototype._drawLine = function(ctx, i) {
452 var setNames = this.layout.setNames;
453 var setName = setNames[i];
454
455 var strokeWidth = this.dygraph_.attr_("strokeWidth", setName);
456 var borderWidth = this.dygraph_.attr_("strokeBorderWidth", setName);
5469113b
KW
457 var drawPointCallback = this.dygraph_.attr_("drawPointCallback", setName) ||
458 Dygraph.Circles.DEFAULT;
99a77a04 459
857a6931 460 if (borderWidth && strokeWidth) {
5469113b 461 this._drawStyledLine(ctx, i, setName,
857a6931
KW
462 this.dygraph_.attr_("strokeBorderColor", setName),
463 strokeWidth + 2 * borderWidth,
464 this.dygraph_.attr_("strokePattern", setName),
465 this.dygraph_.attr_("drawPoints", setName),
5469113b 466 drawPointCallback,
857a6931
KW
467 this.dygraph_.attr_("pointSize", setName));
468 }
469
5469113b 470 this._drawStyledLine(ctx, i, setName,
857a6931
KW
471 this.colors[setName],
472 strokeWidth,
473 this.dygraph_.attr_("strokePattern", setName),
474 this.dygraph_.attr_("drawPoints", setName),
5469113b 475 drawPointCallback,
857a6931
KW
476 this.dygraph_.attr_("pointSize", setName));
477};
ce49c2fa 478
6a1aa64f 479/**
758a629f
DV
480 * Actually draw the lines chart, including error bars.
481 * TODO(danvk): split this into several smaller functions.
482 * @private
6a1aa64f 483 */
285a6bda 484DygraphCanvasRenderer.prototype._renderLineChart = function() {
44c6bc29 485 // TODO(danvk): use this.attr_ for many of these.
857a6931 486 var ctx = this.elementContext;
423f5ed3 487 var fillAlpha = this.attr_('fillAlpha');
e4182459 488 var errorBars = this.attr_("errorBars") || this.attr_("customBars");
44c6bc29 489 var fillGraph = this.attr_("fillGraph");
b2c9222a
DV
490 var stackedGraph = this.attr_("stackedGraph");
491 var stepPlot = this.attr_("stepPlot");
c3e1495b
AR
492 var points = this.layout.points;
493 var pointsLength = points.length;
8722284b 494 var point, i, prevX, prevY, prevYs, color, setName, newYs, err_color, rgb, yscale, axis;
21d3323f 495
82c6fe4d 496 var setNames = this.layout.setNames;
21d3323f 497 var setCount = setNames.length;
6a1aa64f 498
ee53deb9 499 this.colors = this.dygraph_.colorsMap_;
f032c51d 500
ff00d3e2
DV
501 // Update Points
502 // TODO(danvk): here
b843b52c
RK
503 //
504 // TODO(bhs): this loop is a hot-spot for high-point-count charts. These
505 // transformations can be pushed into the canvas via linear transformation
506 // matrices.
758a629f
DV
507 for (i = pointsLength; i--;) {
508 point = points[i];
6a1aa64f
DV
509 point.canvasx = this.area.w * point.x + this.area.x;
510 point.canvasy = this.area.h * point.y + this.area.y;
511 }
6a1aa64f
DV
512
513 // create paths
80aaae18 514 if (errorBars) {
857a6931 515 ctx.save();
6a834bbb
DV
516 if (fillGraph) {
517 this.dygraph_.warn("Can't use fillGraph option with error bars");
518 }
519
758a629f
DV
520 for (i = 0; i < setCount; i++) {
521 setName = setNames[i];
522 axis = this.dygraph_.axisPropertiesForSeries(setName);
523 color = this.colors[setName];
6a1aa64f 524
04c104d7
KW
525 var firstIndexInSet = this.layout.setPointsOffsets[i];
526 var setLength = this.layout.setPointsLengths[i];
04c104d7 527
8722284b
RK
528 var iter = Dygraph.createIterator(points, firstIndexInSet, setLength,
529 DygraphCanvasRenderer._getIteratorPredicate(this.attr_("connectSeparatedPoints")));
04c104d7 530
6a1aa64f 531 // setup graphics context
758a629f
DV
532 prevX = NaN;
533 prevY = NaN;
534 prevYs = [-1, -1];
535 yscale = axis.yscale;
f474c2a3 536 // should be same color as the lines but only 15% opaque.
758a629f
DV
537 rgb = new RGBColor(color);
538 err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
43af96e7 539 fillAlpha + ')';
f474c2a3 540 ctx.fillStyle = err_color;
05c9d0c4 541 ctx.beginPath();
8722284b
RK
542 while (iter.hasNext()) {
543 point = iter.next();
04c104d7 544 if (point.name == setName) { // TODO(klausw): this is always true
e9fe4a2f 545 if (!Dygraph.isOK(point.y)) {
56623f3b 546 prevX = NaN;
ae85914a 547 continue;
5011e7a1 548 }
ce49c2fa 549
3637724f 550 // TODO(danvk): here
afdc483f 551 if (stepPlot) {
758a629f 552 newYs = [ point.y_bottom, point.y_top ];
afdc483f
NN
553 prevY = point.y;
554 } else {
758a629f 555 newYs = [ point.y_bottom, point.y_top ];
afdc483f 556 }
6a1aa64f
DV
557 newYs[0] = this.area.h * newYs[0] + this.area.y;
558 newYs[1] = this.area.h * newYs[1] + this.area.y;
56623f3b 559 if (!isNaN(prevX)) {
afdc483f 560 if (stepPlot) {
47600757 561 ctx.moveTo(prevX, newYs[0]);
afdc483f 562 } else {
47600757 563 ctx.moveTo(prevX, prevYs[0]);
afdc483f 564 }
5954ef32
DV
565 ctx.lineTo(point.canvasx, newYs[0]);
566 ctx.lineTo(point.canvasx, newYs[1]);
afdc483f 567 if (stepPlot) {
47600757 568 ctx.lineTo(prevX, newYs[1]);
afdc483f 569 } else {
47600757 570 ctx.lineTo(prevX, prevYs[1]);
afdc483f 571 }
5954ef32
DV
572 ctx.closePath();
573 }
354e15ab 574 prevYs = newYs;
5954ef32
DV
575 prevX = point.canvasx;
576 }
577 }
578 ctx.fill();
579 }
857a6931 580 ctx.restore();
5954ef32 581 } else if (fillGraph) {
857a6931 582 ctx.save();
349dd9ba
DW
583 var baseline = {}; // for stacked graphs: baseline for filling
584 var currBaseline;
354e15ab
DE
585
586 // process sets in reverse order (needed for stacked graphs)
758a629f
DV
587 for (i = setCount - 1; i >= 0; i--) {
588 setName = setNames[i];
589 color = this.colors[setName];
590 axis = this.dygraph_.axisPropertiesForSeries(setName);
ea4942ed
DV
591 var axisY = 1.0 + axis.minyval * axis.yscale;
592 if (axisY < 0.0) axisY = 0.0;
593 else if (axisY > 1.0) axisY = 1.0;
594 axisY = this.area.h * axisY + this.area.y;
04c104d7
KW
595 var firstIndexInSet = this.layout.setPointsOffsets[i];
596 var setLength = this.layout.setPointsLengths[i];
04c104d7 597
8722284b
RK
598 var iter = Dygraph.createIterator(points, firstIndexInSet, setLength,
599 DygraphCanvasRenderer._getIteratorPredicate(this.attr_("connectSeparatedPoints")));
5954ef32
DV
600
601 // setup graphics context
758a629f
DV
602 prevX = NaN;
603 prevYs = [-1, -1];
604 yscale = axis.yscale;
5954ef32 605 // should be same color as the lines but only 15% opaque.
758a629f
DV
606 rgb = new RGBColor(color);
607 err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
43af96e7 608 fillAlpha + ')';
5954ef32
DV
609 ctx.fillStyle = err_color;
610 ctx.beginPath();
8722284b
RK
611 while(iter.hasNext()) {
612 point = iter.next();
04c104d7 613 if (point.name == setName) { // TODO(klausw): this is always true
e9fe4a2f 614 if (!Dygraph.isOK(point.y)) {
56623f3b 615 prevX = NaN;
5954ef32
DV
616 continue;
617 }
354e15ab 618 if (stackedGraph) {
349dd9ba
DW
619 currBaseline = baseline[point.canvasx];
620 var lastY;
621 if (currBaseline === undefined) {
622 lastY = axisY;
623 } else {
624 if(stepPlot) {
625 lastY = currBaseline[0];
626 } else {
627 lastY = currBaseline;
628 }
629 }
354e15ab 630 newYs = [ point.canvasy, lastY ];
b843b52c 631
349dd9ba
DW
632 if(stepPlot) {
633 // Step plots must keep track of the top and bottom of
634 // the baseline at each point.
635 if(prevYs[0] === -1) {
636 baseline[point.canvasx] = [ point.canvasy, axisY ];
637 } else {
638 baseline[point.canvasx] = [ point.canvasy, prevYs[0] ];
639 }
640 } else {
641 baseline[point.canvasx] = point.canvasy;
642 }
b843b52c 643
354e15ab
DE
644 } else {
645 newYs = [ point.canvasy, axisY ];
646 }
56623f3b 647 if (!isNaN(prevX)) {
05c9d0c4 648 ctx.moveTo(prevX, prevYs[0]);
b843b52c 649
afdc483f 650 if (stepPlot) {
47600757 651 ctx.lineTo(point.canvasx, prevYs[0]);
349dd9ba
DW
652 if(currBaseline) {
653 // Draw to the bottom of the baseline
654 ctx.lineTo(point.canvasx, currBaseline[1]);
655 } else {
656 ctx.lineTo(point.canvasx, newYs[1]);
657 }
afdc483f 658 } else {
47600757 659 ctx.lineTo(point.canvasx, newYs[0]);
349dd9ba 660 ctx.lineTo(point.canvasx, newYs[1]);
afdc483f 661 }
b843b52c 662
05c9d0c4
DV
663 ctx.lineTo(prevX, prevYs[1]);
664 ctx.closePath();
6a1aa64f 665 }
354e15ab 666 prevYs = newYs;
6a1aa64f
DV
667 prevX = point.canvasx;
668 }
05c9d0c4 669 }
6a1aa64f
DV
670 ctx.fill();
671 }
857a6931 672 ctx.restore();
80aaae18
DV
673 }
674
f9414b11 675 // Drawing the lines.
758a629f 676 for (i = 0; i < setCount; i += 1) {
857a6931 677 this._drawLine(ctx, i);
80aaae18 678 }
6a1aa64f 679};
79253bd0 680
681/**
682 * This does dashed lines onto a canvas for a given pattern. You must call
683 * ctx.stroke() after to actually draw it, much line ctx.lineTo(). It remembers
684 * the state of the line in regards to where we left off on drawing the pattern.
685 * You can draw a dashed line in several function calls and the pattern will be
686 * continous as long as you didn't call this function with a different pattern
687 * in between.
688 * @param ctx The canvas 2d context to draw on.
689 * @param x The start of the line's x coordinate.
690 * @param y The start of the line's y coordinate.
691 * @param x2 The end of the line's x coordinate.
692 * @param y2 The end of the line's y coordinate.
693 * @param pattern The dash pattern to draw, an array of integers where even
694 * index is drawn and odd index is not drawn (Ex. [10, 2, 5, 2], 10 is drawn 5
695 * is drawn, 2 is the space between.). A null pattern, array of length one, or
696 * empty array will do just a solid line.
697 * @private
698 */
699DygraphCanvasRenderer.prototype._dashedLine = function(ctx, x, y, x2, y2, pattern) {
700 // Original version http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
701 // Modified by Russell Valentine to keep line history and continue the pattern
702 // where it left off.
703 var dx, dy, len, rot, patternIndex, segment;
704
705 // If we don't have a pattern or it is an empty array or of size one just
706 // do a solid line.
707 if (!pattern || pattern.length <= 1) {
708 ctx.moveTo(x, y);
709 ctx.lineTo(x2, y2);
710 return;
711 }
712
713 // If we have a different dash pattern than the last time this was called we
714 // reset our dash history and start the pattern from the begging
715 // regardless of state of the last pattern.
716 if (!Dygraph.compareArrays(pattern, this._dashedLineToHistoryPattern)) {
717 this._dashedLineToHistoryPattern = pattern;
718 this._dashedLineToHistory = [0, 0];
719 }
720 ctx.save();
721
722 // Calculate transformation parameters
723 dx = (x2-x);
724 dy = (y2-y);
725 len = Math.sqrt(dx*dx + dy*dy);
726 rot = Math.atan2(dy, dx);
727
728 // Set transformation
729 ctx.translate(x, y);
730 ctx.moveTo(0, 0);
731 ctx.rotate(rot);
732
733 // Set last pattern index we used for this pattern.
734 patternIndex = this._dashedLineToHistory[0];
735 x = 0;
736 while (len > x) {
737 // Get the length of the pattern segment we are dealing with.
738 segment = pattern[patternIndex];
739 // If our last draw didn't complete the pattern segment all the way we
740 // will try to finish it. Otherwise we will try to do the whole segment.
741 if (this._dashedLineToHistory[1]) {
742 x += this._dashedLineToHistory[1];
743 } else {
744 x += segment;
745 }
746 if (x > len) {
747 // We were unable to complete this pattern index all the way, keep
748 // where we are the history so our next draw continues where we left off
749 // in the pattern.
750 this._dashedLineToHistory = [patternIndex, x-len];
751 x = len;
752 } else {
753 // We completed this patternIndex, we put in the history that we are on
754 // the beginning of the next segment.
755 this._dashedLineToHistory = [(patternIndex+1)%pattern.length, 0];
756 }
757
758 // We do a line on a even pattern index and just move on a odd pattern index.
759 // The move is the empty space in the dash.
760 if(patternIndex % 2 === 0) {
761 ctx.lineTo(x, 0);
762 } else {
763 ctx.moveTo(x, 0);
764 }
765 // If we are not done, next loop process the next pattern segment, or the
766 // first segment again if we are at the end of the pattern.
767 patternIndex = (patternIndex+1) % pattern.length;
768 }
769 ctx.restore();
770};