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 | |
3ce712e6 | 27 | var DygraphCanvasRenderer = (function() { |
464b5f50 | 28 | /*global Dygraph: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 | * | |
7b00a3cd | 42 | * @param {Dygraph} dygraph The chart to which this renderer belongs. |
48fc4786 | 43 | * @param {HTMLCanvasElement} element The <canvas> DOM element on which to draw. |
8cfe592f DV |
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 | 55 | |
7c39bb3a DV |
56 | this.height = dygraph.height_; |
57 | this.width = dygraph.width_; | |
fbe31dc8 DV |
58 | |
59 | // --- check whether everything is ok before we return | |
9901b0c1 DV |
60 | if (!Dygraph.isCanvasSupported(this.element)) { |
61 | throw "Canvas is not supported."; | |
62 | } | |
fbe31dc8 DV |
63 | |
64 | // internal state | |
70be5ed1 | 65 | this.area = layout.getPlotArea(); |
423f5ed3 DV |
66 | |
67 | // Set up a clipping area for the canvas (and the interaction canvas). | |
68 | // This ensures that we don't overdraw. | |
9901b0c1 DV |
69 | // on Android 3 and 4, setting a clipping area on a canvas prevents it from |
70 | // displaying anything. | |
71 | if (!Dygraph.isAndroid()) { | |
72 | var ctx = this.dygraph_.canvas_ctx_; | |
73 | ctx.beginPath(); | |
74 | ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h); | |
75 | ctx.clip(); | |
76 | ||
77 | ctx = this.dygraph_.hidden_ctx_; | |
78 | ctx.beginPath(); | |
79 | ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h); | |
80 | ctx.clip(); | |
920208fb | 81 | } |
423f5ed3 DV |
82 | }; |
83 | ||
38e3d209 | 84 | /** |
8cfe592f DV |
85 | * Clears out all chart content and DOM elements. |
86 | * This is called immediately before render() on every frame, including | |
87 | * during zooms and pans. | |
88 | * @private | |
89 | */ | |
fbe31dc8 | 90 | DygraphCanvasRenderer.prototype.clear = function() { |
9901b0c1 | 91 | this.elementContext.clearRect(0, 0, this.width, this.height); |
fbe31dc8 DV |
92 | }; |
93 | ||
8cfe592f | 94 | /** |
8cfe592f DV |
95 | * This method is responsible for drawing everything on the chart, including |
96 | * lines, error bars, fills and axes. | |
97 | * It is called immediately after clear() on every frame, including during pans | |
98 | * and zooms. | |
99 | * @private | |
6a1aa64f | 100 | */ |
285a6bda | 101 | DygraphCanvasRenderer.prototype.render = function() { |
38e3d209 DV |
102 | // attaches point.canvas{x,y} |
103 | this._updatePoints(); | |
104 | ||
105 | // actually draws the chart. | |
2ce09b19 | 106 | this._renderLineChart(); |
fbe31dc8 DV |
107 | }; |
108 | ||
ccb0001c | 109 | /** |
8722284b RK |
110 | * Returns a predicate to be used with an iterator, which will |
111 | * iterate over points appropriately, depending on whether | |
112 | * connectSeparatedPoints is true. When it's false, the predicate will | |
113 | * skip over points with missing yVals. | |
ccb0001c | 114 | */ |
8722284b | 115 | DygraphCanvasRenderer._getIteratorPredicate = function(connectSeparatedPoints) { |
42a9ebb8 DV |
116 | return connectSeparatedPoints ? |
117 | DygraphCanvasRenderer._predicateThatSkipsEmptyPoints : | |
118 | null; | |
0f20de1c | 119 | }; |
8722284b RK |
120 | |
121 | DygraphCanvasRenderer._predicateThatSkipsEmptyPoints = | |
0f20de1c DV |
122 | function(array, idx) { |
123 | return array[idx].yval !== null; | |
124 | }; | |
04c104d7 | 125 | |
9f6db80e | 126 | /** |
38e3d209 DV |
127 | * Draws a line with the styles passed in and calls all the drawPointCallbacks. |
128 | * @param {Object} e The dictionary passed to the plotter function. | |
9f6db80e DV |
129 | * @private |
130 | */ | |
38e3d209 DV |
131 | DygraphCanvasRenderer._drawStyledLine = function(e, |
132 | color, strokeWidth, strokePattern, drawPoints, | |
5469113b | 133 | drawPointCallback, pointSize) { |
38e3d209 | 134 | var g = e.dygraph; |
99a77a04 | 135 | // TODO(konigsberg): Compute attributes outside this method call. |
0e85a437 | 136 | var stepPlot = g.getBooleanOption("stepPlot", e.setName); |
2f56cd46 | 137 | |
857a6931 KW |
138 | if (!Dygraph.isArrayLike(strokePattern)) { |
139 | strokePattern = null; | |
140 | } | |
141 | ||
0e85a437 | 142 | var drawGapPoints = g.getBooleanOption('drawGapEdgePoints', e.setName); |
38e3d209 DV |
143 | |
144 | var points = e.points; | |
b85358e2 | 145 | var setName = e.setName; |
a12a78ae | 146 | var iter = Dygraph.createIterator(points, 0, points.length, |
9f6db80e | 147 | DygraphCanvasRenderer._getIteratorPredicate( |
0e85a437 | 148 | g.getBooleanOption("connectSeparatedPoints", setName))); |
7d1afbb9 | 149 | |
fb63bf1b DV |
150 | var stroking = strokePattern && (strokePattern.length >= 2); |
151 | ||
38e3d209 | 152 | var ctx = e.drawingContext; |
0140347d | 153 | ctx.save(); |
fb63bf1b DV |
154 | if (stroking) { |
155 | ctx.installPattern(strokePattern); | |
b843b52c | 156 | } |
fb63bf1b | 157 | |
38e3d209 DV |
158 | var pointsOnLine = DygraphCanvasRenderer._drawSeries( |
159 | e, iter, strokeWidth, pointSize, drawPoints, drawGapPoints, stepPlot, color); | |
160 | DygraphCanvasRenderer._drawPointsOnLine( | |
161 | e, pointsOnLine, drawPointCallback, color, pointSize); | |
31f8e58b | 162 | |
fb63bf1b DV |
163 | if (stroking) { |
164 | ctx.uninstallPattern(); | |
165 | } | |
b843b52c | 166 | |
fb63bf1b | 167 | ctx.restore(); |
31f8e58b RK |
168 | }; |
169 | ||
38e3d209 DV |
170 | /** |
171 | * This does the actual drawing of lines on the canvas, for just one series. | |
172 | * Returns a list of [canvasx, canvasy] pairs for points for which a | |
173 | * drawPointCallback should be fired. These include isolated points, or all | |
174 | * points if drawPoints=true. | |
175 | * @param {Object} e The dictionary passed to the plotter function. | |
176 | * @private | |
177 | */ | |
178 | DygraphCanvasRenderer._drawSeries = function(e, | |
179 | iter, strokeWidth, pointSize, drawPoints, drawGapPoints, stepPlot, color) { | |
31f8e58b | 180 | |
31f8e58b RK |
181 | var prevCanvasX = null; |
182 | var prevCanvasY = null; | |
183 | var nextCanvasY = null; | |
184 | var isIsolated; // true if this point is isolated (no line segments) | |
185 | var point; // the point being processed in the while loop | |
b843b52c | 186 | var pointsOnLine = []; // Array of [canvasx, canvasy] pairs. |
31f8e58b RK |
187 | var first = true; // the first cycle through the while loop |
188 | ||
38e3d209 | 189 | var ctx = e.drawingContext; |
0140347d DV |
190 | ctx.beginPath(); |
191 | ctx.strokeStyle = color; | |
192 | ctx.lineWidth = strokeWidth; | |
31f8e58b | 193 | |
239454e2 | 194 | // NOTE: we break the iterator's encapsulation here for about a 25% speedup. |
c560c848 DV |
195 | var arr = iter.array_; |
196 | var limit = iter.end_; | |
197 | var predicate = iter.predicate_; | |
198 | ||
199 | for (var i = iter.start_; i < limit; i++) { | |
200 | point = arr[i]; | |
201 | if (predicate) { | |
202 | while (i < limit && !predicate(arr, i)) { | |
0f20de1c DV |
203 | i++; |
204 | } | |
c560c848 DV |
205 | if (i == limit) break; |
206 | point = arr[i]; | |
0f20de1c DV |
207 | } |
208 | ||
b7ec6c55 PH |
209 | // FIXME: The 'canvasy != canvasy' test here catches NaN values but the test |
210 | // doesn't catch Infinity values. Could change this to | |
211 | // !isFinite(point.canvasy), but I assume it avoids isNaN for performance? | |
a02978e2 | 212 | if (point.canvasy === null || point.canvasy != point.canvasy) { |
31f8e58b | 213 | if (stepPlot && prevCanvasX !== null) { |
857a6931 | 214 | // Draw a horizontal line to the start of the missing data |
42a9ebb8 DV |
215 | ctx.moveTo(prevCanvasX, prevCanvasY); |
216 | ctx.lineTo(point.canvasx, prevCanvasY); | |
857a6931 | 217 | } |
31f8e58b | 218 | prevCanvasX = prevCanvasY = null; |
857a6931 | 219 | } else { |
0f20de1c DV |
220 | isIsolated = false; |
221 | if (drawGapPoints || !prevCanvasX) { | |
0f20de1c | 222 | iter.nextIdx_ = i; |
0cd1ad15 | 223 | iter.next(); |
82f9b10f | 224 | nextCanvasY = iter.hasNext ? iter.peek.canvasy : null; |
0f20de1c | 225 | |
0f20de1c DV |
226 | var isNextCanvasYNullOrNaN = nextCanvasY === null || |
227 | nextCanvasY != nextCanvasY; | |
228 | isIsolated = (!prevCanvasX && isNextCanvasYNullOrNaN); | |
229 | if (drawGapPoints) { | |
230 | // Also consider a point to be "isolated" if it's adjacent to a | |
231 | // null point, excluding the graph edges. | |
232 | if ((!first && !prevCanvasX) || | |
233 | (iter.hasNext && isNextCanvasYNullOrNaN)) { | |
234 | isIsolated = true; | |
235 | } | |
19b84fe7 KW |
236 | } |
237 | } | |
0f20de1c | 238 | |
31f8e58b | 239 | if (prevCanvasX !== null) { |
857a6931 | 240 | if (strokeWidth) { |
857a6931 | 241 | if (stepPlot) { |
0140347d DV |
242 | ctx.moveTo(prevCanvasX, prevCanvasY); |
243 | ctx.lineTo(point.canvasx, prevCanvasY); | |
857a6931 | 244 | } |
239454e2 | 245 | |
0140347d | 246 | ctx.lineTo(point.canvasx, point.canvasy); |
b843b52c | 247 | } |
9f636500 DV |
248 | } else { |
249 | ctx.moveTo(point.canvasx, point.canvasy); | |
b843b52c | 250 | } |
b843b52c | 251 | if (drawPoints || isIsolated) { |
b616fad1 | 252 | pointsOnLine.push([point.canvasx, point.canvasy, point.idx]); |
b843b52c | 253 | } |
31f8e58b RK |
254 | prevCanvasX = point.canvasx; |
255 | prevCanvasY = point.canvasy; | |
b843b52c | 256 | } |
7d1afbb9 | 257 | first = false; |
b843b52c | 258 | } |
0140347d | 259 | ctx.stroke(); |
31f8e58b | 260 | return pointsOnLine; |
857a6931 KW |
261 | }; |
262 | ||
38e3d209 DV |
263 | /** |
264 | * This fires the drawPointCallback functions, which draw dots on the points by | |
265 | * default. This gets used when the "drawPoints" option is set, or when there | |
266 | * are isolated points. | |
267 | * @param {Object} e The dictionary passed to the plotter function. | |
268 | * @private | |
269 | */ | |
270 | DygraphCanvasRenderer._drawPointsOnLine = function( | |
271 | e, pointsOnLine, drawPointCallback, color, pointSize) { | |
272 | var ctx = e.drawingContext; | |
273 | for (var idx = 0; idx < pointsOnLine.length; idx++) { | |
274 | var cb = pointsOnLine[idx]; | |
275 | ctx.save(); | |
4ee251cb | 276 | drawPointCallback.call(e.dygraph, |
ba697462 | 277 | e.dygraph, e.setName, ctx, cb[0], cb[1], color, pointSize, cb[2]); |
38e3d209 | 278 | ctx.restore(); |
857a6931 | 279 | } |
42a9ebb8 | 280 | }; |
ce49c2fa | 281 | |
6a1aa64f | 282 | /** |
38e3d209 | 283 | * Attaches canvas coordinates to the points array. |
758a629f | 284 | * @private |
6a1aa64f | 285 | */ |
38e3d209 | 286 | DygraphCanvasRenderer.prototype._updatePoints = function() { |
ff00d3e2 DV |
287 | // Update Points |
288 | // TODO(danvk): here | |
b843b52c RK |
289 | // |
290 | // TODO(bhs): this loop is a hot-spot for high-point-count charts. These | |
291 | // transformations can be pushed into the canvas via linear transformation | |
292 | // matrices. | |
e60234cd DV |
293 | // NOTE(danvk): this is trickier than it sounds at first. The transformation |
294 | // needs to be done before the .moveTo() and .lineTo() calls, but must be | |
295 | // undone before the .stroke() call to ensure that the stroke width is | |
296 | // unaffected. An alternative is to reduce the stroke width in the | |
297 | // transformed coordinate space, but you can't specify different values for | |
298 | // each dimension (as you can with .scale()). The speedup here is ~12%. | |
a12a78ae | 299 | var sets = this.layout.points; |
38e3d209 | 300 | for (var i = sets.length; i--;) { |
a12a78ae DV |
301 | var points = sets[i]; |
302 | for (var j = points.length; j--;) { | |
303 | var point = points[j]; | |
304 | point.canvasx = this.area.w * point.x + this.area.x; | |
305 | point.canvasy = this.area.h * point.y + this.area.y; | |
306 | } | |
6a1aa64f | 307 | } |
38e3d209 | 308 | }; |
6a1aa64f | 309 | |
38e3d209 DV |
310 | /** |
311 | * Add canvas Actually draw the lines chart, including error bars. | |
38e3d209 DV |
312 | * |
313 | * This function can only be called if DygraphLayout's points array has been | |
314 | * updated with canvas{x,y} attributes, i.e. by | |
315 | * DygraphCanvasRenderer._updatePoints. | |
48fc4786 RK |
316 | * |
317 | * @param {string=} opt_seriesName when specified, only that series will | |
34655aba RK |
318 | * be drawn. (This is used for expedited redrawing with highlightSeriesOpts) |
319 | * @param {CanvasRenderingContext2D} opt_ctx when specified, the drawing | |
320 | * context. However, lines are typically drawn on the object's | |
321 | * elementContext. | |
38e3d209 DV |
322 | * @private |
323 | */ | |
324 | DygraphCanvasRenderer.prototype._renderLineChart = function(opt_seriesName, opt_ctx) { | |
325 | var ctx = opt_ctx || this.elementContext; | |
38e3d209 | 326 | var i; |
6a834bbb | 327 | |
38e3d209 DV |
328 | var sets = this.layout.points; |
329 | var setNames = this.layout.setNames; | |
42a9ebb8 | 330 | var setName; |
38e3d209 DV |
331 | |
332 | this.colors = this.dygraph_.colorsMap_; | |
333 | ||
334 | // Determine which series have specialized plotters. | |
0e85a437 | 335 | var plotter_attr = this.dygraph_.getOption("plotter"); |
38e3d209 DV |
336 | var plotters = plotter_attr; |
337 | if (!Dygraph.isArrayLike(plotters)) { | |
338 | plotters = [plotters]; | |
80aaae18 DV |
339 | } |
340 | ||
38e3d209 DV |
341 | var setPlotters = {}; // series name -> plotter fn. |
342 | for (i = 0; i < setNames.length; i++) { | |
42a9ebb8 | 343 | setName = setNames[i]; |
0e85a437 | 344 | var setPlotter = this.dygraph_.getOption("plotter", setName); |
38e3d209 DV |
345 | if (setPlotter == plotter_attr) continue; // not specialized. |
346 | ||
347 | setPlotters[setName] = setPlotter; | |
348 | } | |
349 | ||
350 | for (i = 0; i < plotters.length; i++) { | |
351 | var plotter = plotters[i]; | |
352 | var is_last = (i == plotters.length - 1); | |
353 | ||
354 | for (var j = 0; j < sets.length; j++) { | |
42a9ebb8 | 355 | setName = setNames[j]; |
4b2e41a4 | 356 | if (opt_seriesName && setName != opt_seriesName) continue; |
38e3d209 DV |
357 | |
358 | var points = sets[j]; | |
359 | ||
360 | // Only throw in the specialized plotters on the last iteration. | |
361 | var p = plotter; | |
362 | if (setName in setPlotters) { | |
363 | if (is_last) { | |
364 | p = setPlotters[setName]; | |
365 | } else { | |
366 | // Don't use the standard plotters in this case. | |
367 | continue; | |
368 | } | |
369 | } | |
370 | ||
371 | var color = this.colors[setName]; | |
372 | var strokeWidth = this.dygraph_.getOption("strokeWidth", setName); | |
373 | ||
374 | ctx.save(); | |
375 | ctx.strokeStyle = color; | |
376 | ctx.lineWidth = strokeWidth; | |
377 | p({ | |
378 | points: points, | |
379 | setName: setName, | |
380 | drawingContext: ctx, | |
381 | color: color, | |
382 | strokeWidth: strokeWidth, | |
383 | dygraph: this.dygraph_, | |
384 | axis: this.dygraph_.axisPropertiesForSeries(setName), | |
385 | plotArea: this.area, | |
386 | seriesIndex: j, | |
387 | seriesCount: sets.length, | |
3c080cd0 | 388 | singleSeriesName: opt_seriesName, |
38e3d209 DV |
389 | allSeriesPoints: sets |
390 | }); | |
391 | ctx.restore(); | |
392 | } | |
393 | } | |
394 | }; | |
395 | ||
396 | /** | |
397 | * Standard plotters. These may be used by clients via Dygraph.Plotters. | |
398 | * See comments there for more details. | |
399 | */ | |
400 | DygraphCanvasRenderer._Plotters = { | |
401 | linePlotter: function(e) { | |
402 | DygraphCanvasRenderer._linePlotter(e); | |
403 | }, | |
404 | ||
405 | fillPlotter: function(e) { | |
406 | DygraphCanvasRenderer._fillPlotter(e); | |
407 | }, | |
408 | ||
409 | errorPlotter: function(e) { | |
410 | DygraphCanvasRenderer._errorPlotter(e); | |
80aaae18 | 411 | } |
6a1aa64f | 412 | }; |
79253bd0 | 413 | |
01a14b85 | 414 | /** |
38e3d209 DV |
415 | * Plotter which draws the central lines for a series. |
416 | * @private | |
417 | */ | |
418 | DygraphCanvasRenderer._linePlotter = function(e) { | |
419 | var g = e.dygraph; | |
420 | var setName = e.setName; | |
421 | var strokeWidth = e.strokeWidth; | |
422 | ||
423 | // TODO(danvk): Check if there's any performance impact of just calling | |
424 | // getOption() inside of _drawStyledLine. Passing in so many parameters makes | |
425 | // this code a bit nasty. | |
0e85a437 | 426 | var borderWidth = g.getNumericOption("strokeBorderWidth", setName); |
38e3d209 DV |
427 | var drawPointCallback = g.getOption("drawPointCallback", setName) || |
428 | Dygraph.Circles.DEFAULT; | |
429 | var strokePattern = g.getOption("strokePattern", setName); | |
0e85a437 DV |
430 | var drawPoints = g.getBooleanOption("drawPoints", setName); |
431 | var pointSize = g.getNumericOption("pointSize", setName); | |
38e3d209 DV |
432 | |
433 | if (borderWidth && strokeWidth) { | |
434 | DygraphCanvasRenderer._drawStyledLine(e, | |
435 | g.getOption("strokeBorderColor", setName), | |
436 | strokeWidth + 2 * borderWidth, | |
437 | strokePattern, | |
438 | drawPoints, | |
439 | drawPointCallback, | |
440 | pointSize | |
441 | ); | |
442 | } | |
443 | ||
444 | DygraphCanvasRenderer._drawStyledLine(e, | |
445 | e.color, | |
446 | strokeWidth, | |
447 | strokePattern, | |
448 | drawPoints, | |
449 | drawPointCallback, | |
450 | pointSize | |
451 | ); | |
42a9ebb8 | 452 | }; |
38e3d209 DV |
453 | |
454 | /** | |
01a14b85 DV |
455 | * Draws the shaded error bars/confidence intervals for each series. |
456 | * This happens before the center lines are drawn, since the center lines | |
457 | * need to be drawn on top of the error bars for all series. | |
01a14b85 DV |
458 | * @private |
459 | */ | |
38e3d209 DV |
460 | DygraphCanvasRenderer._errorPlotter = function(e) { |
461 | var g = e.dygraph; | |
e2d8db3a | 462 | var setName = e.setName; |
0e85a437 DV |
463 | var errorBars = g.getBooleanOption("errorBars") || |
464 | g.getBooleanOption("customBars"); | |
38e3d209 DV |
465 | if (!errorBars) return; |
466 | ||
0e85a437 | 467 | var fillGraph = g.getBooleanOption("fillGraph", setName); |
38e3d209 | 468 | if (fillGraph) { |
8a68db7d | 469 | console.warn("Can't use fillGraph option with error bars"); |
38e3d209 | 470 | } |
6a6439da | 471 | |
38e3d209 DV |
472 | var ctx = e.drawingContext; |
473 | var color = e.color; | |
0e85a437 DV |
474 | var fillAlpha = g.getNumericOption('fillAlpha', setName); |
475 | var stepPlot = g.getBooleanOption("stepPlot", setName); | |
38e3d209 | 476 | var points = e.points; |
6a6439da | 477 | |
38e3d209 DV |
478 | var iter = Dygraph.createIterator(points, 0, points.length, |
479 | DygraphCanvasRenderer._getIteratorPredicate( | |
0e85a437 | 480 | g.getBooleanOption("connectSeparatedPoints", setName))); |
6a6439da | 481 | |
38e3d209 | 482 | var newYs; |
6a6439da | 483 | |
38e3d209 DV |
484 | // setup graphics context |
485 | var prevX = NaN; | |
486 | var prevY = NaN; | |
487 | var prevYs = [-1, -1]; | |
38e3d209 | 488 | // should be same color as the lines but only 15% opaque. |
464b5f50 | 489 | var rgb = Dygraph.toRGB_(color); |
38e3d209 DV |
490 | var err_color = |
491 | 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + fillAlpha + ')'; | |
492 | ctx.fillStyle = err_color; | |
493 | ctx.beginPath(); | |
cf89eeed DV |
494 | |
495 | var isNullUndefinedOrNaN = function(x) { | |
496 | return (x === null || | |
497 | x === undefined || | |
498 | isNaN(x)); | |
499 | }; | |
500 | ||
38e3d209 DV |
501 | while (iter.hasNext) { |
502 | var point = iter.next(); | |
cf89eeed DV |
503 | if ((!stepPlot && isNullUndefinedOrNaN(point.y)) || |
504 | (stepPlot && !isNaN(prevY) && isNullUndefinedOrNaN(prevY))) { | |
38e3d209 DV |
505 | prevX = NaN; |
506 | continue; | |
507 | } | |
6a6439da | 508 | |
87c5a64c | 509 | newYs = [ point.y_bottom, point.y_top ]; |
38e3d209 | 510 | if (stepPlot) { |
38e3d209 | 511 | prevY = point.y; |
38e3d209 | 512 | } |
87c5a64c DV |
513 | |
514 | // The documentation specifically disallows nulls inside the point arrays, | |
515 | // but in case it happens we should do something sensible. | |
516 | if (isNaN(newYs[0])) newYs[0] = point.y; | |
517 | if (isNaN(newYs[1])) newYs[1] = point.y; | |
518 | ||
38e3d209 DV |
519 | newYs[0] = e.plotArea.h * newYs[0] + e.plotArea.y; |
520 | newYs[1] = e.plotArea.h * newYs[1] + e.plotArea.y; | |
521 | if (!isNaN(prevX)) { | |
a5701188 | 522 | if (stepPlot) { |
38e3d209 | 523 | ctx.moveTo(prevX, prevYs[0]); |
82dd90c5 | 524 | ctx.lineTo(point.canvasx, prevYs[0]); |
525 | ctx.lineTo(point.canvasx, prevYs[1]); | |
38e3d209 | 526 | } else { |
82dd90c5 | 527 | ctx.moveTo(prevX, prevYs[0]); |
528 | ctx.lineTo(point.canvasx, newYs[0]); | |
529 | ctx.lineTo(point.canvasx, newYs[1]); | |
6a6439da | 530 | } |
82dd90c5 | 531 | ctx.lineTo(prevX, prevYs[1]); |
38e3d209 | 532 | ctx.closePath(); |
6a6439da | 533 | } |
38e3d209 DV |
534 | prevYs = newYs; |
535 | prevX = point.canvasx; | |
6a6439da | 536 | } |
38e3d209 | 537 | ctx.fill(); |
42a9ebb8 | 538 | }; |
6a6439da | 539 | |
20b87d28 DV |
540 | |
541 | /** | |
542 | * Proxy for CanvasRenderingContext2D which drops moveTo/lineTo calls which are | |
543 | * superfluous. It accumulates all movements which haven't changed the x-value | |
544 | * and only applies the two with the most extreme y-values. | |
545 | * | |
546 | * Calls to lineTo/moveTo must have non-decreasing x-values. | |
547 | */ | |
548 | DygraphCanvasRenderer._fastCanvasProxy = function(context) { | |
549 | var pendingActions = []; // array of [type, x, y] tuples | |
550 | var lastRoundedX = null; | |
c0ec1a37 | 551 | var lastFlushedX = null; |
20b87d28 DV |
552 | |
553 | var LINE_TO = 1, | |
554 | MOVE_TO = 2; | |
555 | ||
556 | var actionCount = 0; // number of moveTos and lineTos passed to context. | |
557 | ||
558 | // Drop superfluous motions | |
559 | // Assumes all pendingActions have the same (rounded) x-value. | |
560 | var compressActions = function(opt_losslessOnly) { | |
561 | if (pendingActions.length <= 1) return; | |
562 | ||
563 | // Lossless compression: drop inconsequential moveTos. | |
564 | for (var i = pendingActions.length - 1; i > 0; i--) { | |
565 | var action = pendingActions[i]; | |
566 | if (action[0] == MOVE_TO) { | |
567 | var prevAction = pendingActions[i - 1]; | |
568 | if (prevAction[1] == action[1] && prevAction[2] == action[2]) { | |
569 | pendingActions.splice(i, 1); | |
570 | } | |
571 | } | |
572 | } | |
573 | ||
574 | // Lossless compression: ... drop consecutive moveTos ... | |
575 | for (var i = 0; i < pendingActions.length - 1; /* incremented internally */) { | |
576 | var action = pendingActions[i]; | |
577 | if (action[0] == MOVE_TO && pendingActions[i + 1][0] == MOVE_TO) { | |
578 | pendingActions.splice(i, 1); | |
579 | } else { | |
580 | i++; | |
581 | } | |
582 | } | |
583 | ||
584 | // Lossy compression: ... drop all but the extreme y-values ... | |
585 | if (pendingActions.length > 2 && !opt_losslessOnly) { | |
586 | // keep an initial moveTo, but drop all others. | |
587 | var startIdx = 0; | |
588 | if (pendingActions[0][0] == MOVE_TO) startIdx++; | |
589 | var minIdx = null, maxIdx = null; | |
590 | for (var i = startIdx; i < pendingActions.length; i++) { | |
591 | var action = pendingActions[i]; | |
592 | if (action[0] != LINE_TO) continue; | |
593 | if (minIdx === null && maxIdx === null) { | |
594 | minIdx = i; | |
595 | maxIdx = i; | |
596 | } else { | |
597 | var y = action[2]; | |
598 | if (y < pendingActions[minIdx][2]) { | |
599 | minIdx = i; | |
600 | } else if (y > pendingActions[maxIdx][2]) { | |
601 | maxIdx = i; | |
602 | } | |
603 | } | |
604 | } | |
605 | var minAction = pendingActions[minIdx], | |
606 | maxAction = pendingActions[maxIdx]; | |
607 | pendingActions.splice(startIdx, pendingActions.length - startIdx); | |
608 | if (minIdx < maxIdx) { | |
609 | pendingActions.push(minAction); | |
610 | pendingActions.push(maxAction); | |
611 | } else if (minIdx > maxIdx) { | |
612 | pendingActions.push(maxAction); | |
613 | pendingActions.push(minAction); | |
614 | } else { | |
615 | pendingActions.push(minAction); | |
616 | } | |
617 | } | |
618 | }; | |
619 | ||
620 | var flushActions = function(opt_noLossyCompression) { | |
621 | compressActions(opt_noLossyCompression); | |
622 | for (var i = 0, len = pendingActions.length; i < len; i++) { | |
623 | var action = pendingActions[i]; | |
624 | if (action[0] == LINE_TO) { | |
625 | context.lineTo(action[1], action[2]); | |
626 | } else if (action[0] == MOVE_TO) { | |
627 | context.moveTo(action[1], action[2]); | |
628 | } | |
629 | } | |
c0ec1a37 DV |
630 | if (pendingActions.length) { |
631 | lastFlushedX = pendingActions[pendingActions.length - 1][1]; | |
632 | } | |
20b87d28 DV |
633 | actionCount += pendingActions.length; |
634 | pendingActions = []; | |
635 | }; | |
636 | ||
637 | var addAction = function(action, x, y) { | |
638 | var rx = Math.round(x); | |
639 | if (lastRoundedX === null || rx != lastRoundedX) { | |
c0ec1a37 DV |
640 | // if there are large gaps on the x-axis, it's essential to keep the |
641 | // first and last point as well. | |
642 | var hasGapOnLeft = (lastRoundedX - lastFlushedX > 1), | |
643 | hasGapOnRight = (rx - lastRoundedX > 1), | |
644 | hasGap = hasGapOnLeft || hasGapOnRight; | |
645 | flushActions(hasGap); | |
20b87d28 DV |
646 | lastRoundedX = rx; |
647 | } | |
648 | pendingActions.push([action, x, y]); | |
649 | }; | |
650 | ||
651 | return { | |
652 | moveTo: function(x, y) { | |
653 | addAction(MOVE_TO, x, y); | |
654 | }, | |
655 | lineTo: function(x, y) { | |
656 | addAction(LINE_TO, x, y); | |
657 | }, | |
658 | ||
659 | // for major operations like stroke/fill, we skip compression to ensure | |
660 | // that there are no artifacts at the right edge. | |
661 | stroke: function() { flushActions(true); context.stroke(); }, | |
662 | fill: function() { flushActions(true); context.fill(); }, | |
663 | beginPath: function() { flushActions(true); context.beginPath(); }, | |
664 | closePath: function() { flushActions(true); context.closePath(); }, | |
665 | ||
666 | _count: function() { return actionCount; } | |
667 | }; | |
46fd9089 | 668 | }; |
20b87d28 | 669 | |
79253bd0 | 670 | /** |
01a14b85 DV |
671 | * Draws the shaded regions when "fillGraph" is set. Not to be confused with |
672 | * error bars. | |
673 | * | |
38e3d209 DV |
674 | * For stacked charts, it's more convenient to handle all the series |
675 | * simultaneously. So this plotter plots all the points on the first series | |
676 | * it's asked to draw, then ignores all the other series. | |
677 | * | |
01a14b85 DV |
678 | * @private |
679 | */ | |
38e3d209 | 680 | DygraphCanvasRenderer._fillPlotter = function(e) { |
3c080cd0 KW |
681 | // Skip if we're drawing a single series for interactive highlight overlay. |
682 | if (e.singleSeriesName) return; | |
683 | ||
38e3d209 DV |
684 | // We'll handle all the series at once, not one-by-one. |
685 | if (e.seriesIndex !== 0) return; | |
686 | ||
e2d8db3a | 687 | var g = e.dygraph; |
38e3d209 | 688 | var setNames = g.getLabels().slice(1); // remove x-axis |
e2d8db3a | 689 | |
38e3d209 DV |
690 | // getLabels() includes names for invisible series, which are not included in |
691 | // allSeriesPoints. We remove those to make the two match. | |
692 | // TODO(danvk): provide a simpler way to get this information. | |
693 | for (var i = setNames.length; i >= 0; i--) { | |
694 | if (!g.visibility()[i]) setNames.splice(i, 1); | |
695 | } | |
696 | ||
e2d8db3a DV |
697 | var anySeriesFilled = (function() { |
698 | for (var i = 0; i < setNames.length; i++) { | |
0e85a437 | 699 | if (g.getBooleanOption("fillGraph", setNames[i])) return true; |
e2d8db3a DV |
700 | } |
701 | return false; | |
702 | })(); | |
703 | ||
704 | if (!anySeriesFilled) return; | |
705 | ||
e2d8db3a DV |
706 | var area = e.plotArea; |
707 | var sets = e.allSeriesPoints; | |
708 | var setCount = sets.length; | |
709 | ||
0e85a437 | 710 | var stackedGraph = g.getBooleanOption("stackedGraph"); |
38e3d209 | 711 | var colors = g.getColors(); |
01a14b85 | 712 | |
30a5cfc6 KW |
713 | // For stacked graphs, track the baseline for filling. |
714 | // | |
715 | // The filled areas below graph lines are trapezoids with two | |
716 | // vertical edges. The top edge is the line segment being drawn, and | |
717 | // the baseline is the bottom edge. Each baseline corresponds to the | |
718 | // top line segment from the previous stacked line. In the case of | |
719 | // step plots, the trapezoids are rectangles. | |
720 | var baseline = {}; | |
01a14b85 | 721 | var currBaseline; |
104d87c5 | 722 | var prevStepPlot; // for different line drawing modes (line/step) per series |
01a14b85 | 723 | |
46fd9089 DV |
724 | // Helper function to trace a line back along the baseline. |
725 | var traceBackPath = function(ctx, baselineX, baselineY, pathBack) { | |
726 | ctx.lineTo(baselineX, baselineY); | |
727 | if (stackedGraph) { | |
728 | for (var i = pathBack.length - 1; i >= 0; i--) { | |
729 | var pt = pathBack[i]; | |
730 | ctx.lineTo(pt[0], pt[1]); | |
731 | } | |
732 | } | |
733 | }; | |
734 | ||
01a14b85 | 735 | // process sets in reverse order (needed for stacked graphs) |
9e85a8f4 | 736 | for (var setIdx = setCount - 1; setIdx >= 0; setIdx--) { |
20b87d28 | 737 | var ctx = e.drawingContext; |
9e85a8f4 | 738 | var setName = setNames[setIdx]; |
0e85a437 | 739 | if (!g.getBooleanOption('fillGraph', setName)) continue; |
20b87d28 | 740 | |
1b464274 | 741 | var fillAlpha = g.getNumericOption('fillAlpha', setName); |
0e85a437 | 742 | var stepPlot = g.getBooleanOption('stepPlot', setName); |
38e3d209 DV |
743 | var color = colors[setIdx]; |
744 | var axis = g.axisPropertiesForSeries(setName); | |
01a14b85 DV |
745 | var axisY = 1.0 + axis.minyval * axis.yscale; |
746 | if (axisY < 0.0) axisY = 0.0; | |
747 | else if (axisY > 1.0) axisY = 1.0; | |
38e3d209 | 748 | axisY = area.h * axisY + area.y; |
01a14b85 | 749 | |
38e3d209 | 750 | var points = sets[setIdx]; |
9e85a8f4 | 751 | var iter = Dygraph.createIterator(points, 0, points.length, |
01a14b85 | 752 | DygraphCanvasRenderer._getIteratorPredicate( |
0e85a437 | 753 | g.getBooleanOption("connectSeparatedPoints", setName))); |
01a14b85 DV |
754 | |
755 | // setup graphics context | |
756 | var prevX = NaN; | |
757 | var prevYs = [-1, -1]; | |
758 | var newYs; | |
01a14b85 | 759 | // should be same color as the lines but only 15% opaque. |
464b5f50 | 760 | var rgb = Dygraph.toRGB_(color); |
01a14b85 DV |
761 | var err_color = |
762 | 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + fillAlpha + ')'; | |
763 | ctx.fillStyle = err_color; | |
764 | ctx.beginPath(); | |
12b879f4 | 765 | var last_x, is_first = true; |
20b87d28 DV |
766 | |
767 | // If the point density is high enough, dropping segments on their way to | |
768 | // the canvas justifies the overhead of doing so. | |
c0ec1a37 | 769 | if (points.length > 2 * g.width_ || Dygraph.FORCE_FAST_PROXY) { |
20b87d28 DV |
770 | ctx = DygraphCanvasRenderer._fastCanvasProxy(ctx); |
771 | } | |
772 | ||
773 | // For filled charts, we draw points from left to right, then back along | |
774 | // the x-axis to complete a shape for filling. | |
775 | // For stacked plots, this "back path" is a more complex shape. This array | |
776 | // stores the [x, y] values needed to trace that shape. | |
777 | var pathBack = []; | |
778 | ||
20b87d28 DV |
779 | // TODO(danvk): there are a lot of options at play in this loop. |
780 | // The logic would be much clearer if some (e.g. stackGraph and | |
781 | // stepPlot) were split off into separate sub-plotters. | |
46fd9089 | 782 | var point; |
12b879f4 | 783 | while (iter.hasNext) { |
46fd9089 | 784 | point = iter.next(); |
8c31c7db | 785 | if (!Dygraph.isOK(point.y) && !stepPlot) { |
46fd9089 DV |
786 | traceBackPath(ctx, prevX, prevYs[1], pathBack); |
787 | pathBack = []; | |
16febe6b | 788 | prevX = NaN; |
30a5cfc6 KW |
789 | if (point.y_stacked !== null && !isNaN(point.y_stacked)) { |
790 | baseline[point.canvasx] = area.h * point.y_stacked + area.y; | |
791 | } | |
16febe6b DV |
792 | continue; |
793 | } | |
794 | if (stackedGraph) { | |
12b879f4 DV |
795 | if (!is_first && last_x == point.xval) { |
796 | continue; | |
797 | } else { | |
798 | is_first = false; | |
799 | last_x = point.xval; | |
800 | } | |
801 | ||
16febe6b DV |
802 | currBaseline = baseline[point.canvasx]; |
803 | var lastY; | |
804 | if (currBaseline === undefined) { | |
805 | lastY = axisY; | |
806 | } else { | |
104d87c5 | 807 | if(prevStepPlot) { |
16febe6b | 808 | lastY = currBaseline[0]; |
01a14b85 | 809 | } else { |
16febe6b | 810 | lastY = currBaseline; |
01a14b85 | 811 | } |
16febe6b DV |
812 | } |
813 | newYs = [ point.canvasy, lastY ]; | |
01a14b85 | 814 | |
20b87d28 | 815 | if (stepPlot) { |
16febe6b DV |
816 | // Step plots must keep track of the top and bottom of |
817 | // the baseline at each point. | |
20b87d28 | 818 | if (prevYs[0] === -1) { |
16febe6b | 819 | baseline[point.canvasx] = [ point.canvasy, axisY ]; |
01a14b85 | 820 | } else { |
16febe6b | 821 | baseline[point.canvasx] = [ point.canvasy, prevYs[0] ]; |
01a14b85 | 822 | } |
01a14b85 | 823 | } else { |
16febe6b | 824 | baseline[point.canvasx] = point.canvasy; |
01a14b85 | 825 | } |
01a14b85 | 826 | |
16febe6b | 827 | } else { |
8c31c7db | 828 | if (isNaN(point.canvasy) && stepPlot) { |
e988d192 | 829 | newYs = [ area.y + area.h, axisY ]; |
8c31c7db | 830 | } else { |
e988d192 BB |
831 | newYs = [ point.canvasy, axisY ]; |
832 | } | |
16febe6b DV |
833 | } |
834 | if (!isNaN(prevX)) { | |
104d87c5 | 835 | // Move to top fill point |
16febe6b DV |
836 | if (stepPlot) { |
837 | ctx.lineTo(point.canvasx, prevYs[0]); | |
16febe6b | 838 | ctx.lineTo(point.canvasx, newYs[0]); |
104d87c5 | 839 | } else { |
20b87d28 | 840 | ctx.lineTo(point.canvasx, newYs[0]); |
01a14b85 | 841 | } |
16febe6b | 842 | |
20b87d28 DV |
843 | // Record the baseline for the reverse path. |
844 | if (stackedGraph) { | |
845 | pathBack.push([prevX, prevYs[1]]); | |
846 | if (prevStepPlot && currBaseline) { | |
847 | // Draw to the bottom of the baseline | |
848 | pathBack.push([point.canvasx, currBaseline[1]]); | |
849 | } else { | |
850 | pathBack.push([point.canvasx, newYs[1]]); | |
851 | } | |
852 | } | |
853 | } else { | |
854 | ctx.moveTo(point.canvasx, newYs[1]); | |
855 | ctx.lineTo(point.canvasx, newYs[0]); | |
01a14b85 | 856 | } |
16febe6b DV |
857 | prevYs = newYs; |
858 | prevX = point.canvasx; | |
01a14b85 | 859 | } |
104d87c5 | 860 | prevStepPlot = stepPlot; |
46fd9089 DV |
861 | if (newYs && point) { |
862 | traceBackPath(ctx, point.canvasx, newYs[1], pathBack); | |
863 | pathBack = []; | |
20b87d28 | 864 | } |
01a14b85 DV |
865 | ctx.fill(); |
866 | } | |
867 | }; | |
3ce712e6 DV |
868 | |
869 | return DygraphCanvasRenderer; | |
870 | ||
871 | })(); |