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