grid plugin mostly working
[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
2ce09b19 175 // Do the ordinary rendering, as before
2ce09b19 176 this._renderLineChart();
fbe31dc8
DV
177};
178
920208fb
PF
179DygraphCanvasRenderer.prototype._createIEClipArea = function() {
180 var className = 'dygraph-clip-div';
181 var graphDiv = this.dygraph_.graphDiv;
182
183 // Remove old clip divs.
184 for (var i = graphDiv.childNodes.length-1; i >= 0; i--) {
185 if (graphDiv.childNodes[i].className == className) {
186 graphDiv.removeChild(graphDiv.childNodes[i]);
187 }
188 }
189
190 // Determine background color to give clip divs.
191 var backgroundColor = document.bgColor;
192 var element = this.dygraph_.graphDiv;
193 while (element != document) {
194 var bgcolor = element.currentStyle.backgroundColor;
195 if (bgcolor && bgcolor != 'transparent') {
196 backgroundColor = bgcolor;
197 break;
198 }
199 element = element.parentNode;
200 }
201
202 function createClipDiv(area) {
758a629f 203 if (area.w === 0 || area.h === 0) {
920208fb
PF
204 return;
205 }
206 var elem = document.createElement('div');
207 elem.className = className;
208 elem.style.backgroundColor = backgroundColor;
209 elem.style.position = 'absolute';
210 elem.style.left = area.x + 'px';
211 elem.style.top = area.y + 'px';
212 elem.style.width = area.w + 'px';
213 elem.style.height = area.h + 'px';
214 graphDiv.appendChild(elem);
215 }
216
217 var plotArea = this.area;
218 // Left side
758a629f
DV
219 createClipDiv({
220 x:0, y:0,
221 w:plotArea.x,
222 h:this.height
223 });
224
920208fb 225 // Top
758a629f
DV
226 createClipDiv({
227 x: plotArea.x, y: 0,
228 w: this.width - plotArea.x,
229 h: plotArea.y
230 });
231
920208fb 232 // Right side
758a629f
DV
233 createClipDiv({
234 x: plotArea.x + plotArea.w, y: 0,
235 w: this.width-plotArea.x - plotArea.w,
236 h: this.height
237 });
238
920208fb 239 // Bottom
758a629f
DV
240 createClipDiv({
241 x: plotArea.x,
242 y: plotArea.y + plotArea.h,
243 w: this.width - plotArea.x,
244 h: this.height - plotArea.h - plotArea.y
245 });
246};
fbe31dc8 247
fbe31dc8 248
ccb0001c 249/**
8722284b
RK
250 * Returns a predicate to be used with an iterator, which will
251 * iterate over points appropriately, depending on whether
252 * connectSeparatedPoints is true. When it's false, the predicate will
253 * skip over points with missing yVals.
ccb0001c 254 */
8722284b
RK
255DygraphCanvasRenderer._getIteratorPredicate = function(connectSeparatedPoints) {
256 return connectSeparatedPoints ? DygraphCanvasRenderer._predicateThatSkipsEmptyPoints : null;
257}
258
259DygraphCanvasRenderer._predicateThatSkipsEmptyPoints =
260 function(array, idx) { return array[idx].yval !== null; }
04c104d7 261
857a6931 262DygraphCanvasRenderer.prototype._drawStyledLine = function(
5469113b
KW
263 ctx, i, setName, color, strokeWidth, strokePattern, drawPoints,
264 drawPointCallback, pointSize) {
99a77a04 265 // TODO(konigsberg): Compute attributes outside this method call.
857a6931
KW
266 var stepPlot = this.attr_("stepPlot");
267 var firstIndexInSet = this.layout.setPointsOffsets[i];
268 var setLength = this.layout.setPointsLengths[i];
857a6931 269 var points = this.layout.points;
857a6931
KW
270 if (!Dygraph.isArrayLike(strokePattern)) {
271 strokePattern = null;
272 }
a5a50727 273 var drawGapPoints = this.dygraph_.attr_('drawGapEdgePoints', setName);
857a6931 274
b843b52c 275 ctx.save();
7d1afbb9 276
7d1afbb9 277 var iter = Dygraph.createIterator(points, firstIndexInSet, setLength,
8722284b 278 DygraphCanvasRenderer._getIteratorPredicate(this.attr_("connectSeparatedPoints")));
7d1afbb9 279
31f8e58b
RK
280 var pointsOnLine;
281 var strategy;
282 if (!strokePattern || strokePattern.length <= 1) {
283 strategy = trivialStrategy(ctx, color, strokeWidth);
b843b52c 284 } else {
31f8e58b 285 strategy = nonTrivialStrategy(this, ctx, color, strokeWidth, strokePattern);
b843b52c 286 }
31f8e58b
RK
287 pointsOnLine = this._drawSeries(ctx, iter, strokeWidth, pointSize, drawPoints, drawGapPoints, stepPlot, strategy);
288 this._drawPointsOnLine(ctx, pointsOnLine, drawPointCallback, setName, color, pointSize);
289
b843b52c
RK
290 ctx.restore();
291};
292
31f8e58b
RK
293var nonTrivialStrategy = function(renderer, ctx, color, strokeWidth, strokePattern) {
294 return new function() {
295 this.init = function() { };
296 this.finish = function() { };
297 this.startSegment = function() {
298 ctx.beginPath();
299 ctx.strokeStyle = color;
300 ctx.lineWidth = strokeWidth;
301 };
302 this.endSegment = function() {
303 ctx.stroke(); // should this include closePath?
304 };
305 this.drawLine = function(x1, y1, x2, y2) {
306 renderer._dashedLine(ctx, x1, y1, x2, y2, strokePattern);
307 };
308 this.skipPixel = function(prevX, prevY, curX, curY) {
309 // TODO(konigsberg): optimize with http://jsperf.com/math-round-vs-hack/6 ?
310 return (Math.round(prevX) == Math.round(curX) &&
311 Math.round(prevY) == Math.round(curY));
312 };
313 };
314};
315
316var trivialStrategy = function(ctx, color, strokeWidth) {
317 return new function() {
318 this.init = function() {
319 ctx.beginPath();
320 ctx.strokeStyle = color;
321 ctx.lineWidth = strokeWidth;
322 };
323 this.finish = function() {
324 ctx.stroke(); // should this include closePath?
325 };
326 this.startSegment = function() { };
327 this.endSegment = function() { };
328 this.drawLine = function(x1, y1, x2, y2) {
329 ctx.moveTo(x1, y1);
330 ctx.lineTo(x2, y2);
331 };
332 // don't skip pixels.
333 this.skipPixel = function() {
334 return false;
335 };
336 };
337};
338
a401ca8a
RK
339DygraphCanvasRenderer.prototype._drawPointsOnLine = function(ctx, pointsOnLine, drawPointCallback, setName, color, pointSize) {
340 for (var idx = 0; idx < pointsOnLine.length; idx++) {
341 var cb = pointsOnLine[idx];
342 ctx.save();
343 drawPointCallback(
344 this.dygraph_, setName, ctx, cb[0], cb[1], color, pointSize);
345 ctx.restore();
346 }
347}
348
31f8e58b
RK
349DygraphCanvasRenderer.prototype._drawSeries = function(
350 ctx, iter, strokeWidth, pointSize, drawPoints, drawGapPoints,
351 stepPlot, strategy) {
352
31f8e58b
RK
353 var prevCanvasX = null;
354 var prevCanvasY = null;
355 var nextCanvasY = null;
356 var isIsolated; // true if this point is isolated (no line segments)
357 var point; // the point being processed in the while loop
b843b52c 358 var pointsOnLine = []; // Array of [canvasx, canvasy] pairs.
31f8e58b
RK
359 var first = true; // the first cycle through the while loop
360
361 strategy.init();
362
7d1afbb9
RK
363 while(iter.hasNext()) {
364 point = iter.next();
a02978e2 365 if (point.canvasy === null || point.canvasy != point.canvasy) {
31f8e58b 366 if (stepPlot && prevCanvasX !== null) {
857a6931 367 // Draw a horizontal line to the start of the missing data
31f8e58b
RK
368 strategy.startSegment();
369 strategy.drawLine(prevX, prevY, point.canvasx, prevY);
370 strategy.endSegment();
857a6931 371 }
31f8e58b 372 prevCanvasX = prevCanvasY = null;
857a6931 373 } else {
31f8e58b 374 nextCanvasY = iter.hasNext() ? iter.peek().canvasy : null;
a02978e2
RK
375 // TODO: we calculate isNullOrNaN for this point, and the next, and then, when
376 // we iterate, test for isNullOrNaN again. Why bother?
377 var isNextCanvasYNullOrNaN = nextCanvasY === null || nextCanvasY != nextCanvasY;
378 isIsolated = (!prevCanvasX && isNextCanvasYNullOrNaN);
19b84fe7 379 if (drawGapPoints) {
31f8e58b 380 // Also consider a point to be "isolated" if it's adjacent to a
19b84fe7 381 // null point, excluding the graph edges.
31f8e58b 382 if ((!first && !prevCanvasX) ||
a02978e2 383 (iter.hasNext() && isNextCanvasYNullOrNaN)) {
19b84fe7
KW
384 isIsolated = true;
385 }
386 }
31f8e58b
RK
387 if (prevCanvasX !== null) {
388 if (strategy.skipPixel(prevCanvasX, prevCanvasY, point.canvasx, point.canvasy)) {
857a6931
KW
389 continue;
390 }
857a6931 391 if (strokeWidth) {
31f8e58b 392 strategy.startSegment();
857a6931 393 if (stepPlot) {
31f8e58b
RK
394 strategy.drawLine(prevCanvasX, prevCanvasY, point.canvasx, prevCanvasY);
395 prevCanvasX = point.canvasx;
857a6931 396 }
31f8e58b
RK
397 strategy.drawLine(prevCanvasX, prevCanvasY, point.canvasx, point.canvasy);
398 strategy.endSegment();
b843b52c
RK
399 }
400 }
b843b52c
RK
401 if (drawPoints || isIsolated) {
402 pointsOnLine.push([point.canvasx, point.canvasy]);
403 }
31f8e58b
RK
404 prevCanvasX = point.canvasx;
405 prevCanvasY = point.canvasy;
b843b52c 406 }
7d1afbb9 407 first = false;
b843b52c 408 }
31f8e58b
RK
409 strategy.finish();
410 return pointsOnLine;
857a6931
KW
411};
412
413DygraphCanvasRenderer.prototype._drawLine = function(ctx, i) {
414 var setNames = this.layout.setNames;
415 var setName = setNames[i];
416
417 var strokeWidth = this.dygraph_.attr_("strokeWidth", setName);
418 var borderWidth = this.dygraph_.attr_("strokeBorderWidth", setName);
5469113b
KW
419 var drawPointCallback = this.dygraph_.attr_("drawPointCallback", setName) ||
420 Dygraph.Circles.DEFAULT;
99a77a04 421
857a6931 422 if (borderWidth && strokeWidth) {
5469113b 423 this._drawStyledLine(ctx, i, setName,
857a6931
KW
424 this.dygraph_.attr_("strokeBorderColor", setName),
425 strokeWidth + 2 * borderWidth,
426 this.dygraph_.attr_("strokePattern", setName),
427 this.dygraph_.attr_("drawPoints", setName),
5469113b 428 drawPointCallback,
857a6931
KW
429 this.dygraph_.attr_("pointSize", setName));
430 }
431
5469113b 432 this._drawStyledLine(ctx, i, setName,
857a6931
KW
433 this.colors[setName],
434 strokeWidth,
435 this.dygraph_.attr_("strokePattern", setName),
436 this.dygraph_.attr_("drawPoints", setName),
5469113b 437 drawPointCallback,
857a6931
KW
438 this.dygraph_.attr_("pointSize", setName));
439};
ce49c2fa 440
6a1aa64f 441/**
758a629f
DV
442 * Actually draw the lines chart, including error bars.
443 * TODO(danvk): split this into several smaller functions.
444 * @private
6a1aa64f 445 */
285a6bda 446DygraphCanvasRenderer.prototype._renderLineChart = function() {
44c6bc29 447 // TODO(danvk): use this.attr_ for many of these.
857a6931 448 var ctx = this.elementContext;
423f5ed3 449 var fillAlpha = this.attr_('fillAlpha');
e4182459 450 var errorBars = this.attr_("errorBars") || this.attr_("customBars");
44c6bc29 451 var fillGraph = this.attr_("fillGraph");
b2c9222a
DV
452 var stackedGraph = this.attr_("stackedGraph");
453 var stepPlot = this.attr_("stepPlot");
c3e1495b
AR
454 var points = this.layout.points;
455 var pointsLength = points.length;
8722284b 456 var point, i, prevX, prevY, prevYs, color, setName, newYs, err_color, rgb, yscale, axis;
21d3323f 457
82c6fe4d 458 var setNames = this.layout.setNames;
21d3323f 459 var setCount = setNames.length;
6a1aa64f 460
ee53deb9 461 this.colors = this.dygraph_.colorsMap_;
f032c51d 462
ff00d3e2
DV
463 // Update Points
464 // TODO(danvk): here
b843b52c
RK
465 //
466 // TODO(bhs): this loop is a hot-spot for high-point-count charts. These
467 // transformations can be pushed into the canvas via linear transformation
468 // matrices.
758a629f
DV
469 for (i = pointsLength; i--;) {
470 point = points[i];
6a1aa64f
DV
471 point.canvasx = this.area.w * point.x + this.area.x;
472 point.canvasy = this.area.h * point.y + this.area.y;
473 }
6a1aa64f
DV
474
475 // create paths
80aaae18 476 if (errorBars) {
857a6931 477 ctx.save();
6a834bbb
DV
478 if (fillGraph) {
479 this.dygraph_.warn("Can't use fillGraph option with error bars");
480 }
481
758a629f
DV
482 for (i = 0; i < setCount; i++) {
483 setName = setNames[i];
484 axis = this.dygraph_.axisPropertiesForSeries(setName);
485 color = this.colors[setName];
6a1aa64f 486
04c104d7
KW
487 var firstIndexInSet = this.layout.setPointsOffsets[i];
488 var setLength = this.layout.setPointsLengths[i];
04c104d7 489
8722284b
RK
490 var iter = Dygraph.createIterator(points, firstIndexInSet, setLength,
491 DygraphCanvasRenderer._getIteratorPredicate(this.attr_("connectSeparatedPoints")));
04c104d7 492
6a1aa64f 493 // setup graphics context
758a629f
DV
494 prevX = NaN;
495 prevY = NaN;
496 prevYs = [-1, -1];
497 yscale = axis.yscale;
f474c2a3 498 // should be same color as the lines but only 15% opaque.
758a629f
DV
499 rgb = new RGBColor(color);
500 err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
43af96e7 501 fillAlpha + ')';
f474c2a3 502 ctx.fillStyle = err_color;
05c9d0c4 503 ctx.beginPath();
8722284b
RK
504 while (iter.hasNext()) {
505 point = iter.next();
04c104d7 506 if (point.name == setName) { // TODO(klausw): this is always true
e9fe4a2f 507 if (!Dygraph.isOK(point.y)) {
56623f3b 508 prevX = NaN;
ae85914a 509 continue;
5011e7a1 510 }
ce49c2fa 511
3637724f 512 // TODO(danvk): here
afdc483f 513 if (stepPlot) {
758a629f 514 newYs = [ point.y_bottom, point.y_top ];
afdc483f
NN
515 prevY = point.y;
516 } else {
758a629f 517 newYs = [ point.y_bottom, point.y_top ];
afdc483f 518 }
6a1aa64f
DV
519 newYs[0] = this.area.h * newYs[0] + this.area.y;
520 newYs[1] = this.area.h * newYs[1] + this.area.y;
56623f3b 521 if (!isNaN(prevX)) {
afdc483f 522 if (stepPlot) {
47600757 523 ctx.moveTo(prevX, newYs[0]);
afdc483f 524 } else {
47600757 525 ctx.moveTo(prevX, prevYs[0]);
afdc483f 526 }
5954ef32
DV
527 ctx.lineTo(point.canvasx, newYs[0]);
528 ctx.lineTo(point.canvasx, newYs[1]);
afdc483f 529 if (stepPlot) {
47600757 530 ctx.lineTo(prevX, newYs[1]);
afdc483f 531 } else {
47600757 532 ctx.lineTo(prevX, prevYs[1]);
afdc483f 533 }
5954ef32
DV
534 ctx.closePath();
535 }
354e15ab 536 prevYs = newYs;
5954ef32
DV
537 prevX = point.canvasx;
538 }
539 }
540 ctx.fill();
541 }
857a6931 542 ctx.restore();
5954ef32 543 } else if (fillGraph) {
857a6931 544 ctx.save();
349dd9ba
DW
545 var baseline = {}; // for stacked graphs: baseline for filling
546 var currBaseline;
354e15ab
DE
547
548 // process sets in reverse order (needed for stacked graphs)
758a629f
DV
549 for (i = setCount - 1; i >= 0; i--) {
550 setName = setNames[i];
551 color = this.colors[setName];
552 axis = this.dygraph_.axisPropertiesForSeries(setName);
ea4942ed
DV
553 var axisY = 1.0 + axis.minyval * axis.yscale;
554 if (axisY < 0.0) axisY = 0.0;
555 else if (axisY > 1.0) axisY = 1.0;
556 axisY = this.area.h * axisY + this.area.y;
04c104d7
KW
557 var firstIndexInSet = this.layout.setPointsOffsets[i];
558 var setLength = this.layout.setPointsLengths[i];
04c104d7 559
8722284b
RK
560 var iter = Dygraph.createIterator(points, firstIndexInSet, setLength,
561 DygraphCanvasRenderer._getIteratorPredicate(this.attr_("connectSeparatedPoints")));
5954ef32
DV
562
563 // setup graphics context
758a629f
DV
564 prevX = NaN;
565 prevYs = [-1, -1];
566 yscale = axis.yscale;
5954ef32 567 // should be same color as the lines but only 15% opaque.
758a629f
DV
568 rgb = new RGBColor(color);
569 err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' +
43af96e7 570 fillAlpha + ')';
5954ef32
DV
571 ctx.fillStyle = err_color;
572 ctx.beginPath();
8722284b
RK
573 while(iter.hasNext()) {
574 point = iter.next();
04c104d7 575 if (point.name == setName) { // TODO(klausw): this is always true
e9fe4a2f 576 if (!Dygraph.isOK(point.y)) {
56623f3b 577 prevX = NaN;
5954ef32
DV
578 continue;
579 }
354e15ab 580 if (stackedGraph) {
349dd9ba
DW
581 currBaseline = baseline[point.canvasx];
582 var lastY;
583 if (currBaseline === undefined) {
584 lastY = axisY;
585 } else {
586 if(stepPlot) {
587 lastY = currBaseline[0];
588 } else {
589 lastY = currBaseline;
590 }
591 }
354e15ab 592 newYs = [ point.canvasy, lastY ];
b843b52c 593
349dd9ba
DW
594 if(stepPlot) {
595 // Step plots must keep track of the top and bottom of
596 // the baseline at each point.
597 if(prevYs[0] === -1) {
598 baseline[point.canvasx] = [ point.canvasy, axisY ];
599 } else {
600 baseline[point.canvasx] = [ point.canvasy, prevYs[0] ];
601 }
602 } else {
603 baseline[point.canvasx] = point.canvasy;
604 }
b843b52c 605
354e15ab
DE
606 } else {
607 newYs = [ point.canvasy, axisY ];
608 }
56623f3b 609 if (!isNaN(prevX)) {
05c9d0c4 610 ctx.moveTo(prevX, prevYs[0]);
b843b52c 611
afdc483f 612 if (stepPlot) {
47600757 613 ctx.lineTo(point.canvasx, prevYs[0]);
349dd9ba
DW
614 if(currBaseline) {
615 // Draw to the bottom of the baseline
616 ctx.lineTo(point.canvasx, currBaseline[1]);
617 } else {
618 ctx.lineTo(point.canvasx, newYs[1]);
619 }
afdc483f 620 } else {
47600757 621 ctx.lineTo(point.canvasx, newYs[0]);
349dd9ba 622 ctx.lineTo(point.canvasx, newYs[1]);
afdc483f 623 }
b843b52c 624
05c9d0c4
DV
625 ctx.lineTo(prevX, prevYs[1]);
626 ctx.closePath();
6a1aa64f 627 }
354e15ab 628 prevYs = newYs;
6a1aa64f
DV
629 prevX = point.canvasx;
630 }
05c9d0c4 631 }
6a1aa64f
DV
632 ctx.fill();
633 }
857a6931 634 ctx.restore();
80aaae18
DV
635 }
636
f9414b11 637 // Drawing the lines.
758a629f 638 for (i = 0; i < setCount; i += 1) {
857a6931 639 this._drawLine(ctx, i);
80aaae18 640 }
6a1aa64f 641};
79253bd0 642
643/**
644 * This does dashed lines onto a canvas for a given pattern. You must call
645 * ctx.stroke() after to actually draw it, much line ctx.lineTo(). It remembers
646 * the state of the line in regards to where we left off on drawing the pattern.
647 * You can draw a dashed line in several function calls and the pattern will be
648 * continous as long as you didn't call this function with a different pattern
649 * in between.
650 * @param ctx The canvas 2d context to draw on.
651 * @param x The start of the line's x coordinate.
652 * @param y The start of the line's y coordinate.
653 * @param x2 The end of the line's x coordinate.
654 * @param y2 The end of the line's y coordinate.
655 * @param pattern The dash pattern to draw, an array of integers where even
656 * index is drawn and odd index is not drawn (Ex. [10, 2, 5, 2], 10 is drawn 5
657 * is drawn, 2 is the space between.). A null pattern, array of length one, or
658 * empty array will do just a solid line.
659 * @private
660 */
661DygraphCanvasRenderer.prototype._dashedLine = function(ctx, x, y, x2, y2, pattern) {
662 // Original version http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
663 // Modified by Russell Valentine to keep line history and continue the pattern
664 // where it left off.
665 var dx, dy, len, rot, patternIndex, segment;
666
667 // If we don't have a pattern or it is an empty array or of size one just
668 // do a solid line.
669 if (!pattern || pattern.length <= 1) {
670 ctx.moveTo(x, y);
671 ctx.lineTo(x2, y2);
672 return;
673 }
674
675 // If we have a different dash pattern than the last time this was called we
676 // reset our dash history and start the pattern from the begging
677 // regardless of state of the last pattern.
678 if (!Dygraph.compareArrays(pattern, this._dashedLineToHistoryPattern)) {
679 this._dashedLineToHistoryPattern = pattern;
680 this._dashedLineToHistory = [0, 0];
681 }
682 ctx.save();
683
684 // Calculate transformation parameters
685 dx = (x2-x);
686 dy = (y2-y);
687 len = Math.sqrt(dx*dx + dy*dy);
688 rot = Math.atan2(dy, dx);
689
690 // Set transformation
691 ctx.translate(x, y);
692 ctx.moveTo(0, 0);
693 ctx.rotate(rot);
694
695 // Set last pattern index we used for this pattern.
696 patternIndex = this._dashedLineToHistory[0];
697 x = 0;
698 while (len > x) {
699 // Get the length of the pattern segment we are dealing with.
700 segment = pattern[patternIndex];
701 // If our last draw didn't complete the pattern segment all the way we
702 // will try to finish it. Otherwise we will try to do the whole segment.
703 if (this._dashedLineToHistory[1]) {
704 x += this._dashedLineToHistory[1];
705 } else {
706 x += segment;
707 }
708 if (x > len) {
709 // We were unable to complete this pattern index all the way, keep
710 // where we are the history so our next draw continues where we left off
711 // in the pattern.
712 this._dashedLineToHistory = [patternIndex, x-len];
713 x = len;
714 } else {
715 // We completed this patternIndex, we put in the history that we are on
716 // the beginning of the next segment.
717 this._dashedLineToHistory = [(patternIndex+1)%pattern.length, 0];
718 }
719
720 // We do a line on a even pattern index and just move on a odd pattern index.
721 // The move is the empty space in the dash.
722 if(patternIndex % 2 === 0) {
723 ctx.lineTo(x, 0);
724 } else {
725 ctx.moveTo(x, 0);
726 }
727 // If we are not done, next loop process the next pattern segment, or the
728 // first segment again if we are at the end of the pattern.
729 patternIndex = (patternIndex+1) % pattern.length;
730 }
731 ctx.restore();
732};