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