| 1 | /** |
| 2 | * @license |
| 3 | * Copyright 2006 Dan Vanderkam (danvdk@gmail.com) |
| 4 | * MIT-licensed (http://opensource.org/licenses/MIT) |
| 5 | */ |
| 6 | |
| 7 | /** |
| 8 | * @fileoverview Based on PlotKit.CanvasRenderer, but modified to meet the |
| 9 | * needs of dygraphs. |
| 10 | * |
| 11 | * In particular, support for: |
| 12 | * - grid overlays |
| 13 | * - error bars |
| 14 | * - dygraphs attribute system |
| 15 | */ |
| 16 | |
| 17 | /** |
| 18 | * The DygraphCanvasRenderer class does the actual rendering of the chart onto |
| 19 | * a canvas. It's based on PlotKit.CanvasRenderer. |
| 20 | * @param {Object} element The canvas to attach to |
| 21 | * @param {Object} elementContext The 2d context of the canvas (injected so it |
| 22 | * can be mocked for testing.) |
| 23 | * @param {Layout} layout The DygraphLayout object for this graph. |
| 24 | * @constructor |
| 25 | */ |
| 26 | |
| 27 | /*jshint globalstrict: true */ |
| 28 | /*global Dygraph:false,RGBColor:false */ |
| 29 | "use strict"; |
| 30 | |
| 31 | |
| 32 | /** |
| 33 | * @constructor |
| 34 | * |
| 35 | * This gets called when there are "new points" to chart. This is generally the |
| 36 | * case when the underlying data being charted has changed. It is _not_ called |
| 37 | * in the common case that the user has zoomed or is panning the view. |
| 38 | * |
| 39 | * The chart canvas has already been created by the Dygraph object. The |
| 40 | * renderer simply gets a drawing context. |
| 41 | * |
| 42 | * @param {Dyraph} dygraph The chart to which this renderer belongs. |
| 43 | * @param {Canvas} element The <canvas> DOM element on which to draw. |
| 44 | * @param {CanvasRenderingContext2D} elementContext The drawing context. |
| 45 | * @param {DygraphLayout} layout The chart's DygraphLayout object. |
| 46 | * |
| 47 | * TODO(danvk): remove the elementContext property. |
| 48 | */ |
| 49 | var DygraphCanvasRenderer = function(dygraph, element, elementContext, layout) { |
| 50 | this.dygraph_ = dygraph; |
| 51 | |
| 52 | this.layout = layout; |
| 53 | this.element = element; |
| 54 | this.elementContext = elementContext; |
| 55 | this.container = this.element.parentNode; |
| 56 | |
| 57 | this.height = this.element.height; |
| 58 | this.width = this.element.width; |
| 59 | |
| 60 | // --- check whether everything is ok before we return |
| 61 | if (!this.isIE && !(DygraphCanvasRenderer.isSupported(this.element))) |
| 62 | throw "Canvas is not supported."; |
| 63 | |
| 64 | // internal state |
| 65 | this.area = layout.getPlotArea(); |
| 66 | this.container.style.position = "relative"; |
| 67 | this.container.style.width = this.width + "px"; |
| 68 | |
| 69 | // Set up a clipping area for the canvas (and the interaction canvas). |
| 70 | // This ensures that we don't overdraw. |
| 71 | if (this.dygraph_.isUsingExcanvas_) { |
| 72 | this._createIEClipArea(); |
| 73 | } else { |
| 74 | // on Android 3 and 4, setting a clipping area on a canvas prevents it from |
| 75 | // displaying anything. |
| 76 | if (!Dygraph.isAndroid()) { |
| 77 | var ctx = this.dygraph_.canvas_ctx_; |
| 78 | ctx.beginPath(); |
| 79 | ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h); |
| 80 | ctx.clip(); |
| 81 | |
| 82 | ctx = this.dygraph_.hidden_ctx_; |
| 83 | ctx.beginPath(); |
| 84 | ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h); |
| 85 | ctx.clip(); |
| 86 | } |
| 87 | } |
| 88 | }; |
| 89 | |
| 90 | DygraphCanvasRenderer.prototype.attr_ = function(x) { |
| 91 | return this.dygraph_.attr_(x); |
| 92 | }; |
| 93 | |
| 94 | /** |
| 95 | * Clears out all chart content and DOM elements. |
| 96 | * This is called immediately before render() on every frame, including |
| 97 | * during zooms and pans. |
| 98 | * @private |
| 99 | */ |
| 100 | DygraphCanvasRenderer.prototype.clear = function() { |
| 101 | var context; |
| 102 | if (this.isIE) { |
| 103 | // VML takes a while to start up, so we just poll every this.IEDelay |
| 104 | try { |
| 105 | if (this.clearDelay) { |
| 106 | this.clearDelay.cancel(); |
| 107 | this.clearDelay = null; |
| 108 | } |
| 109 | context = this.elementContext; |
| 110 | } |
| 111 | catch (e) { |
| 112 | // TODO(danvk): this is broken, since MochiKit.Async is gone. |
| 113 | // this.clearDelay = MochiKit.Async.wait(this.IEDelay); |
| 114 | // this.clearDelay.addCallback(bind(this.clear, this)); |
| 115 | return; |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | context = this.elementContext; |
| 120 | context.clearRect(0, 0, this.width, this.height); |
| 121 | }; |
| 122 | |
| 123 | /** |
| 124 | * Checks whether the browser supports the <canvas> tag. |
| 125 | * @private |
| 126 | */ |
| 127 | DygraphCanvasRenderer.isSupported = function(canvasName) { |
| 128 | var canvas = null; |
| 129 | try { |
| 130 | if (typeof(canvasName) == 'undefined' || canvasName === null) { |
| 131 | canvas = document.createElement("canvas"); |
| 132 | } else { |
| 133 | canvas = canvasName; |
| 134 | } |
| 135 | canvas.getContext("2d"); |
| 136 | } |
| 137 | catch (e) { |
| 138 | var ie = navigator.appVersion.match(/MSIE (\d\.\d)/); |
| 139 | var opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1); |
| 140 | if ((!ie) || (ie[1] < 6) || (opera)) |
| 141 | return false; |
| 142 | return true; |
| 143 | } |
| 144 | return true; |
| 145 | }; |
| 146 | |
| 147 | /** |
| 148 | * @param { [String] } colors Array of color strings. Should have one entry for |
| 149 | * each series to be rendered. |
| 150 | */ |
| 151 | DygraphCanvasRenderer.prototype.setColors = function(colors) { |
| 152 | this.colorScheme_ = colors; |
| 153 | }; |
| 154 | |
| 155 | /** |
| 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 |
| 161 | */ |
| 162 | DygraphCanvasRenderer.prototype.render = function() { |
| 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. |
| 165 | var ctx = this.elementContext; |
| 166 | function halfUp(x) { return Math.round(x) + 0.5; } |
| 167 | function halfDown(y){ return Math.round(y) - 0.5; } |
| 168 | |
| 169 | if (this.attr_('underlayCallback')) { |
| 170 | // NOTE: we pass the dygraph object to this callback twice to avoid breaking |
| 171 | // users who expect a deprecated form of this callback. |
| 172 | this.attr_('underlayCallback')(ctx, this.area, this.dygraph_, this.dygraph_); |
| 173 | } |
| 174 | |
| 175 | // Do the ordinary rendering, as before |
| 176 | this._renderLineChart(); |
| 177 | }; |
| 178 | |
| 179 | DygraphCanvasRenderer.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) { |
| 203 | if (area.w === 0 || area.h === 0) { |
| 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 |
| 219 | createClipDiv({ |
| 220 | x:0, y:0, |
| 221 | w:plotArea.x, |
| 222 | h:this.height |
| 223 | }); |
| 224 | |
| 225 | // Top |
| 226 | createClipDiv({ |
| 227 | x: plotArea.x, y: 0, |
| 228 | w: this.width - plotArea.x, |
| 229 | h: plotArea.y |
| 230 | }); |
| 231 | |
| 232 | // Right side |
| 233 | createClipDiv({ |
| 234 | x: plotArea.x + plotArea.w, y: 0, |
| 235 | w: this.width-plotArea.x - plotArea.w, |
| 236 | h: this.height |
| 237 | }); |
| 238 | |
| 239 | // Bottom |
| 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 | }; |
| 247 | |
| 248 | |
| 249 | /** |
| 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. |
| 254 | */ |
| 255 | DygraphCanvasRenderer._getIteratorPredicate = function(connectSeparatedPoints) { |
| 256 | return connectSeparatedPoints ? DygraphCanvasRenderer._predicateThatSkipsEmptyPoints : null; |
| 257 | } |
| 258 | |
| 259 | DygraphCanvasRenderer._predicateThatSkipsEmptyPoints = |
| 260 | function(array, idx) { return array[idx].yval !== null; } |
| 261 | |
| 262 | DygraphCanvasRenderer.prototype._drawStyledLine = function( |
| 263 | ctx, i, setName, color, strokeWidth, strokePattern, drawPoints, |
| 264 | drawPointCallback, pointSize) { |
| 265 | // TODO(konigsberg): Compute attributes outside this method call. |
| 266 | var stepPlot = this.attr_("stepPlot"); |
| 267 | var firstIndexInSet = this.layout.setPointsOffsets[i]; |
| 268 | var setLength = this.layout.setPointsLengths[i]; |
| 269 | var points = this.layout.points; |
| 270 | if (!Dygraph.isArrayLike(strokePattern)) { |
| 271 | strokePattern = null; |
| 272 | } |
| 273 | var drawGapPoints = this.dygraph_.attr_('drawGapEdgePoints', setName); |
| 274 | |
| 275 | ctx.save(); |
| 276 | |
| 277 | var iter = Dygraph.createIterator(points, firstIndexInSet, setLength, |
| 278 | DygraphCanvasRenderer._getIteratorPredicate(this.attr_("connectSeparatedPoints"))); |
| 279 | |
| 280 | var pointsOnLine; |
| 281 | var strategy; |
| 282 | if (!strokePattern || strokePattern.length <= 1) { |
| 283 | strategy = trivialStrategy(ctx, color, strokeWidth); |
| 284 | } else { |
| 285 | strategy = nonTrivialStrategy(this, ctx, color, strokeWidth, strokePattern); |
| 286 | } |
| 287 | pointsOnLine = this._drawSeries(ctx, iter, strokeWidth, pointSize, drawPoints, drawGapPoints, stepPlot, strategy); |
| 288 | this._drawPointsOnLine(ctx, pointsOnLine, drawPointCallback, setName, color, pointSize); |
| 289 | |
| 290 | ctx.restore(); |
| 291 | }; |
| 292 | |
| 293 | var 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 | |
| 316 | var 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 | |
| 339 | DygraphCanvasRenderer.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 | |
| 349 | DygraphCanvasRenderer.prototype._drawSeries = function( |
| 350 | ctx, iter, strokeWidth, pointSize, drawPoints, drawGapPoints, |
| 351 | stepPlot, strategy) { |
| 352 | |
| 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 |
| 358 | var pointsOnLine = []; // Array of [canvasx, canvasy] pairs. |
| 359 | var first = true; // the first cycle through the while loop |
| 360 | |
| 361 | strategy.init(); |
| 362 | |
| 363 | while(iter.hasNext()) { |
| 364 | point = iter.next(); |
| 365 | if (point.canvasy === null || point.canvasy != point.canvasy) { |
| 366 | if (stepPlot && prevCanvasX !== null) { |
| 367 | // Draw a horizontal line to the start of the missing data |
| 368 | strategy.startSegment(); |
| 369 | strategy.drawLine(prevX, prevY, point.canvasx, prevY); |
| 370 | strategy.endSegment(); |
| 371 | } |
| 372 | prevCanvasX = prevCanvasY = null; |
| 373 | } else { |
| 374 | nextCanvasY = iter.hasNext() ? iter.peek().canvasy : null; |
| 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); |
| 379 | if (drawGapPoints) { |
| 380 | // Also consider a point to be "isolated" if it's adjacent to a |
| 381 | // null point, excluding the graph edges. |
| 382 | if ((!first && !prevCanvasX) || |
| 383 | (iter.hasNext() && isNextCanvasYNullOrNaN)) { |
| 384 | isIsolated = true; |
| 385 | } |
| 386 | } |
| 387 | if (prevCanvasX !== null) { |
| 388 | if (strategy.skipPixel(prevCanvasX, prevCanvasY, point.canvasx, point.canvasy)) { |
| 389 | continue; |
| 390 | } |
| 391 | if (strokeWidth) { |
| 392 | strategy.startSegment(); |
| 393 | if (stepPlot) { |
| 394 | strategy.drawLine(prevCanvasX, prevCanvasY, point.canvasx, prevCanvasY); |
| 395 | prevCanvasX = point.canvasx; |
| 396 | } |
| 397 | strategy.drawLine(prevCanvasX, prevCanvasY, point.canvasx, point.canvasy); |
| 398 | strategy.endSegment(); |
| 399 | } |
| 400 | } |
| 401 | if (drawPoints || isIsolated) { |
| 402 | pointsOnLine.push([point.canvasx, point.canvasy]); |
| 403 | } |
| 404 | prevCanvasX = point.canvasx; |
| 405 | prevCanvasY = point.canvasy; |
| 406 | } |
| 407 | first = false; |
| 408 | } |
| 409 | strategy.finish(); |
| 410 | return pointsOnLine; |
| 411 | }; |
| 412 | |
| 413 | DygraphCanvasRenderer.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); |
| 419 | var drawPointCallback = this.dygraph_.attr_("drawPointCallback", setName) || |
| 420 | Dygraph.Circles.DEFAULT; |
| 421 | |
| 422 | if (borderWidth && strokeWidth) { |
| 423 | this._drawStyledLine(ctx, i, setName, |
| 424 | this.dygraph_.attr_("strokeBorderColor", setName), |
| 425 | strokeWidth + 2 * borderWidth, |
| 426 | this.dygraph_.attr_("strokePattern", setName), |
| 427 | this.dygraph_.attr_("drawPoints", setName), |
| 428 | drawPointCallback, |
| 429 | this.dygraph_.attr_("pointSize", setName)); |
| 430 | } |
| 431 | |
| 432 | this._drawStyledLine(ctx, i, setName, |
| 433 | this.colors[setName], |
| 434 | strokeWidth, |
| 435 | this.dygraph_.attr_("strokePattern", setName), |
| 436 | this.dygraph_.attr_("drawPoints", setName), |
| 437 | drawPointCallback, |
| 438 | this.dygraph_.attr_("pointSize", setName)); |
| 439 | }; |
| 440 | |
| 441 | /** |
| 442 | * Actually draw the lines chart, including error bars. |
| 443 | * TODO(danvk): split this into several smaller functions. |
| 444 | * @private |
| 445 | */ |
| 446 | DygraphCanvasRenderer.prototype._renderLineChart = function() { |
| 447 | // TODO(danvk): use this.attr_ for many of these. |
| 448 | var ctx = this.elementContext; |
| 449 | var fillAlpha = this.attr_('fillAlpha'); |
| 450 | var errorBars = this.attr_("errorBars") || this.attr_("customBars"); |
| 451 | var fillGraph = this.attr_("fillGraph"); |
| 452 | var stackedGraph = this.attr_("stackedGraph"); |
| 453 | var stepPlot = this.attr_("stepPlot"); |
| 454 | var points = this.layout.points; |
| 455 | var pointsLength = points.length; |
| 456 | var point, i, prevX, prevY, prevYs, color, setName, newYs, err_color, rgb, yscale, axis; |
| 457 | |
| 458 | var setNames = this.layout.setNames; |
| 459 | var setCount = setNames.length; |
| 460 | |
| 461 | this.colors = this.dygraph_.colorsMap_; |
| 462 | |
| 463 | // Update Points |
| 464 | // TODO(danvk): here |
| 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. |
| 469 | for (i = pointsLength; i--;) { |
| 470 | point = points[i]; |
| 471 | point.canvasx = this.area.w * point.x + this.area.x; |
| 472 | point.canvasy = this.area.h * point.y + this.area.y; |
| 473 | } |
| 474 | |
| 475 | // create paths |
| 476 | if (errorBars) { |
| 477 | ctx.save(); |
| 478 | if (fillGraph) { |
| 479 | this.dygraph_.warn("Can't use fillGraph option with error bars"); |
| 480 | } |
| 481 | |
| 482 | for (i = 0; i < setCount; i++) { |
| 483 | setName = setNames[i]; |
| 484 | axis = this.dygraph_.axisPropertiesForSeries(setName); |
| 485 | color = this.colors[setName]; |
| 486 | |
| 487 | var firstIndexInSet = this.layout.setPointsOffsets[i]; |
| 488 | var setLength = this.layout.setPointsLengths[i]; |
| 489 | |
| 490 | var iter = Dygraph.createIterator(points, firstIndexInSet, setLength, |
| 491 | DygraphCanvasRenderer._getIteratorPredicate(this.attr_("connectSeparatedPoints"))); |
| 492 | |
| 493 | // setup graphics context |
| 494 | prevX = NaN; |
| 495 | prevY = NaN; |
| 496 | prevYs = [-1, -1]; |
| 497 | yscale = axis.yscale; |
| 498 | // should be same color as the lines but only 15% opaque. |
| 499 | rgb = new RGBColor(color); |
| 500 | err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + |
| 501 | fillAlpha + ')'; |
| 502 | ctx.fillStyle = err_color; |
| 503 | ctx.beginPath(); |
| 504 | while (iter.hasNext()) { |
| 505 | point = iter.next(); |
| 506 | if (point.name == setName) { // TODO(klausw): this is always true |
| 507 | if (!Dygraph.isOK(point.y)) { |
| 508 | prevX = NaN; |
| 509 | continue; |
| 510 | } |
| 511 | |
| 512 | // TODO(danvk): here |
| 513 | if (stepPlot) { |
| 514 | newYs = [ point.y_bottom, point.y_top ]; |
| 515 | prevY = point.y; |
| 516 | } else { |
| 517 | newYs = [ point.y_bottom, point.y_top ]; |
| 518 | } |
| 519 | newYs[0] = this.area.h * newYs[0] + this.area.y; |
| 520 | newYs[1] = this.area.h * newYs[1] + this.area.y; |
| 521 | if (!isNaN(prevX)) { |
| 522 | if (stepPlot) { |
| 523 | ctx.moveTo(prevX, newYs[0]); |
| 524 | } else { |
| 525 | ctx.moveTo(prevX, prevYs[0]); |
| 526 | } |
| 527 | ctx.lineTo(point.canvasx, newYs[0]); |
| 528 | ctx.lineTo(point.canvasx, newYs[1]); |
| 529 | if (stepPlot) { |
| 530 | ctx.lineTo(prevX, newYs[1]); |
| 531 | } else { |
| 532 | ctx.lineTo(prevX, prevYs[1]); |
| 533 | } |
| 534 | ctx.closePath(); |
| 535 | } |
| 536 | prevYs = newYs; |
| 537 | prevX = point.canvasx; |
| 538 | } |
| 539 | } |
| 540 | ctx.fill(); |
| 541 | } |
| 542 | ctx.restore(); |
| 543 | } else if (fillGraph) { |
| 544 | ctx.save(); |
| 545 | var baseline = {}; // for stacked graphs: baseline for filling |
| 546 | var currBaseline; |
| 547 | |
| 548 | // process sets in reverse order (needed for stacked graphs) |
| 549 | for (i = setCount - 1; i >= 0; i--) { |
| 550 | setName = setNames[i]; |
| 551 | color = this.colors[setName]; |
| 552 | axis = this.dygraph_.axisPropertiesForSeries(setName); |
| 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; |
| 557 | var firstIndexInSet = this.layout.setPointsOffsets[i]; |
| 558 | var setLength = this.layout.setPointsLengths[i]; |
| 559 | |
| 560 | var iter = Dygraph.createIterator(points, firstIndexInSet, setLength, |
| 561 | DygraphCanvasRenderer._getIteratorPredicate(this.attr_("connectSeparatedPoints"))); |
| 562 | |
| 563 | // setup graphics context |
| 564 | prevX = NaN; |
| 565 | prevYs = [-1, -1]; |
| 566 | yscale = axis.yscale; |
| 567 | // should be same color as the lines but only 15% opaque. |
| 568 | rgb = new RGBColor(color); |
| 569 | err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + |
| 570 | fillAlpha + ')'; |
| 571 | ctx.fillStyle = err_color; |
| 572 | ctx.beginPath(); |
| 573 | while(iter.hasNext()) { |
| 574 | point = iter.next(); |
| 575 | if (point.name == setName) { // TODO(klausw): this is always true |
| 576 | if (!Dygraph.isOK(point.y)) { |
| 577 | prevX = NaN; |
| 578 | continue; |
| 579 | } |
| 580 | if (stackedGraph) { |
| 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 | } |
| 592 | newYs = [ point.canvasy, lastY ]; |
| 593 | |
| 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 | } |
| 605 | |
| 606 | } else { |
| 607 | newYs = [ point.canvasy, axisY ]; |
| 608 | } |
| 609 | if (!isNaN(prevX)) { |
| 610 | ctx.moveTo(prevX, prevYs[0]); |
| 611 | |
| 612 | if (stepPlot) { |
| 613 | ctx.lineTo(point.canvasx, prevYs[0]); |
| 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 | } |
| 620 | } else { |
| 621 | ctx.lineTo(point.canvasx, newYs[0]); |
| 622 | ctx.lineTo(point.canvasx, newYs[1]); |
| 623 | } |
| 624 | |
| 625 | ctx.lineTo(prevX, prevYs[1]); |
| 626 | ctx.closePath(); |
| 627 | } |
| 628 | prevYs = newYs; |
| 629 | prevX = point.canvasx; |
| 630 | } |
| 631 | } |
| 632 | ctx.fill(); |
| 633 | } |
| 634 | ctx.restore(); |
| 635 | } |
| 636 | |
| 637 | // Drawing the lines. |
| 638 | for (i = 0; i < setCount; i += 1) { |
| 639 | this._drawLine(ctx, i); |
| 640 | } |
| 641 | }; |
| 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 | */ |
| 661 | DygraphCanvasRenderer.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 | }; |