Merge pull request #161 from klausw-g/is-series-locked
[dygraphs.git] / dashed-canvas.js
1 /**
2 * @license
3 * Copyright 2012 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
5 */
6
7 /**
8 * @fileoverview Adds support for dashed lines to the HTML5 canvas.
9 *
10 * Usage:
11 * var ctx = canvas.getContext("2d");
12 * ctx.installPattern([10, 5]) // draw 10 pixels, skip 5 pixels, repeat.
13 * ctx.beginPath();
14 * ctx.moveTo(100, 100); // start the first line segment.
15 * ctx.lineTo(150, 200);
16 * ctx.lineTo(200, 100);
17 * ctx.moveTo(300, 150); // start a second, unconnected line
18 * ctx.lineTo(400, 250);
19 * ...
20 * ctx.stroke(); // draw the dashed line.
21 * ctx.uninstallPattern();
22 *
23 * This is designed to leave the canvas untouched when it's not used.
24 * If you never install a pattern, or call uninstallPattern(), then the canvas
25 * will be exactly as it would have if you'd never used this library. The only
26 * difference from the standard canvas will be the "installPattern" method of
27 * the drawing context.
28 */
29
30 /**
31 * Change the stroking style of the canvas drawing context from a solid line to
32 * a pattern (e.g. dashes, dash-dot-dash, etc.)
33 *
34 * Once you've installed the pattern, you can draw with it by using the
35 * beginPath(), moveTo(), lineTo() and stroke() method calls. Note that some
36 * more advanced methods (e.g. quadraticCurveTo() and bezierCurveTo()) are not
37 * supported. See file overview for a working example.
38 *
39 * Side effects of calling this method include adding an "isPatternInstalled"
40 * property and "uninstallPattern" method to this particular canvas context.
41 * You must call uninstallPattern() before calling installPattern() again.
42 *
43 * @param {pattern | Array<Number>} A description of the stroke pattern. Even
44 * indices indicate a draw and odd indices indicate a gap (in pixels). The
45 * array should have a even length as any odd lengthed array could be expressed
46 * as a smaller even length array.
47 */
48 CanvasRenderingContext2D.prototype.installPattern = function(pattern) {
49 "use strict";
50
51 if (typeof(this.isPatternInstalled) !== 'undefined') {
52 throw "Must un-install old line pattern before installing a new one.";
53 }
54 this.isPatternInstalled = true;
55
56 var dashedLineToHistory = [0, 0];
57
58 // list of connected line segements:
59 // [ [x1, y1], ..., [xn, yn] ], [ [x1, y1], ..., [xn, yn] ]
60 var segments = [];
61
62 // Stash away copies of the unmodified line-drawing functions.
63 var realBeginPath = this.beginPath;
64 var realLineTo = this.lineTo;
65 var realMoveTo = this.moveTo;
66 var realStroke = this.stroke;
67
68 this.uninstallPattern = function() {
69 this.beginPath = realBeginPath;
70 this.lineTo = realLineTo;
71 this.moveTo = realMoveTo;
72 this.stroke = realStroke;
73 this.uninstallPattern = undefined;
74 this.isPatternInstalled = undefined;
75 };
76
77 // Keep our own copies of the line segments as they're drawn.
78 this.beginPath = function() {
79 segments = [];
80 realBeginPath.call(this);
81 };
82 this.moveTo = function(x, y) {
83 segments.push([[x, y]]);
84 realMoveTo.call(this, x, y);
85 };
86 this.lineTo = function(x, y) {
87 var last = segments[segments.length - 1];
88 last.push([x, y]);
89 };
90
91 this.stroke = function() {
92 if (segments.length === 0) {
93 // Maybe the user is drawing something other than a line.
94 // TODO(danvk): test this case.
95 realStroke.call(this);
96 return;
97 }
98
99 for (var i = 0; i < segments.length; i++) {
100 var seg = segments[i];
101 var x1 = seg[0][0], y1 = seg[0][1];
102 for (var j = 1; j < seg.length; j++) {
103 // Draw a dashed line from (x1, y1) - (x2, y2)
104 var x2 = seg[j][0], y2 = seg[j][1];
105 this.save();
106
107 // Calculate transformation parameters
108 var dx = (x2-x1);
109 var dy = (y2-y1);
110 var len = Math.sqrt(dx*dx + dy*dy);
111 var rot = Math.atan2(dy, dx);
112
113 // Set transformation
114 this.translate(x1, y1);
115 realMoveTo.call(this, 0, 0);
116 this.rotate(rot);
117
118 // Set last pattern index we used for this pattern.
119 var patternIndex = dashedLineToHistory[0];
120 var x = 0;
121 while (len > x) {
122 // Get the length of the pattern segment we are dealing with.
123 var segment = pattern[patternIndex];
124 // If our last draw didn't complete the pattern segment all the way
125 // we will try to finish it. Otherwise we will try to do the whole
126 // segment.
127 if (dashedLineToHistory[1]) {
128 x += dashedLineToHistory[1];
129 } else {
130 x += segment;
131 }
132
133 if (x > len) {
134 // We were unable to complete this pattern index all the way, keep
135 // where we are the history so our next draw continues where we
136 // left off in the pattern.
137 dashedLineToHistory = [patternIndex, x-len];
138 x = len;
139 } else {
140 // We completed this patternIndex, we put in the history that we
141 // are on the beginning of the next segment.
142 dashedLineToHistory = [(patternIndex+1)%pattern.length, 0];
143 }
144
145 // We do a line on a even pattern index and just move on a odd
146 // pattern index. The move is the empty space in the dash.
147 if (patternIndex % 2 === 0) {
148 realLineTo.call(this, x, 0);
149 } else {
150 realMoveTo.call(this, x, 0);
151 }
152
153 // If we are not done, next loop process the next pattern segment, or
154 // the first segment again if we are at the end of the pattern.
155 patternIndex = (patternIndex+1) % pattern.length;
156 }
157
158 this.restore();
159 x1 = x2, y1 = y2;
160 }
161 }
162 realStroke.call(this);
163 segments = [];
164 };
165 };
166
167 /**
168 * Removes the previously-installed pattern.
169 * You must call installPattern() before calling this. You can install at most
170 * one pattern at a time--there is no pattern stack.
171 */
172 CanvasRenderingContext2D.prototype.uninstallPattern = function() {
173 // This will be replaced by a non-error version when a pattern is installed.
174 throw "Must install a line pattern before uninstalling it.";
175 }