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