You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

310 lines
10 KiB

4 years ago
  1. 'use strict';
  2. var regTransformTypes = /matrix|translate|scale|rotate|skewX|skewY/,
  3. regTransformSplit = /\s*(matrix|translate|scale|rotate|skewX|skewY)\s*\(\s*(.+?)\s*\)[\s,]*/,
  4. regNumericValues = /[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?/g;
  5. /**
  6. * Convert transform string to JS representation.
  7. *
  8. * @param {String} transformString input string
  9. * @param {Object} params plugin params
  10. * @return {Array} output array
  11. */
  12. exports.transform2js = function(transformString) {
  13. // JS representation of the transform data
  14. var transforms = [],
  15. // current transform context
  16. current;
  17. // split value into ['', 'translate', '10 50', '', 'scale', '2', '', 'rotate', '-45', '']
  18. transformString.split(regTransformSplit).forEach(function(item) {
  19. /*jshint -W084 */
  20. var num;
  21. if (item) {
  22. // if item is a translate function
  23. if (regTransformTypes.test(item)) {
  24. // then collect it and change current context
  25. transforms.push(current = { name: item });
  26. // else if item is data
  27. } else {
  28. // then split it into [10, 50] and collect as context.data
  29. while (num = regNumericValues.exec(item)) {
  30. num = Number(num);
  31. if (current.data)
  32. current.data.push(num);
  33. else
  34. current.data = [num];
  35. }
  36. }
  37. }
  38. });
  39. // return empty array if broken transform (no data)
  40. return current && current.data ? transforms : [];
  41. };
  42. /**
  43. * Multiply transforms into one.
  44. *
  45. * @param {Array} input transforms array
  46. * @return {Array} output matrix array
  47. */
  48. exports.transformsMultiply = function(transforms) {
  49. // convert transforms objects to the matrices
  50. transforms = transforms.map(function(transform) {
  51. if (transform.name === 'matrix') {
  52. return transform.data;
  53. }
  54. return transformToMatrix(transform);
  55. });
  56. // multiply all matrices into one
  57. transforms = {
  58. name: 'matrix',
  59. data: transforms.length > 0 ? transforms.reduce(multiplyTransformMatrices) : []
  60. };
  61. return transforms;
  62. };
  63. /**
  64. * Do math like a schoolgirl.
  65. *
  66. * @type {Object}
  67. */
  68. var mth = exports.mth = {
  69. rad: function(deg) {
  70. return deg * Math.PI / 180;
  71. },
  72. deg: function(rad) {
  73. return rad * 180 / Math.PI;
  74. },
  75. cos: function(deg) {
  76. return Math.cos(this.rad(deg));
  77. },
  78. acos: function(val, floatPrecision) {
  79. return +(this.deg(Math.acos(val)).toFixed(floatPrecision));
  80. },
  81. sin: function(deg) {
  82. return Math.sin(this.rad(deg));
  83. },
  84. asin: function(val, floatPrecision) {
  85. return +(this.deg(Math.asin(val)).toFixed(floatPrecision));
  86. },
  87. tan: function(deg) {
  88. return Math.tan(this.rad(deg));
  89. },
  90. atan: function(val, floatPrecision) {
  91. return +(this.deg(Math.atan(val)).toFixed(floatPrecision));
  92. }
  93. };
  94. /**
  95. * Decompose matrix into simple transforms. See
  96. * http://frederic-wang.fr/decomposition-of-2d-transform-matrices.html
  97. *
  98. * @param {Object} data matrix transform object
  99. * @return {Object|Array} transforms array or original transform object
  100. */
  101. exports.matrixToTransform = function(transform, params) {
  102. var floatPrecision = params.floatPrecision,
  103. data = transform.data,
  104. transforms = [],
  105. sx = +Math.hypot(data[0], data[1]).toFixed(params.transformPrecision),
  106. sy = +((data[0] * data[3] - data[1] * data[2]) / sx).toFixed(params.transformPrecision),
  107. colsSum = data[0] * data[2] + data[1] * data[3],
  108. rowsSum = data[0] * data[1] + data[2] * data[3],
  109. scaleBefore = rowsSum != 0 || sx == sy;
  110. // [..., ..., ..., ..., tx, ty] → translate(tx, ty)
  111. if (data[4] || data[5]) {
  112. transforms.push({ name: 'translate', data: data.slice(4, data[5] ? 6 : 5) });
  113. }
  114. // [sx, 0, tan(a)·sy, sy, 0, 0] → skewX(a)·scale(sx, sy)
  115. if (!data[1] && data[2]) {
  116. transforms.push({ name: 'skewX', data: [mth.atan(data[2] / sy, floatPrecision)] });
  117. // [sx, sx·tan(a), 0, sy, 0, 0] → skewY(a)·scale(sx, sy)
  118. } else if (data[1] && !data[2]) {
  119. transforms.push({ name: 'skewY', data: [mth.atan(data[1] / data[0], floatPrecision)] });
  120. sx = data[0];
  121. sy = data[3];
  122. // [sx·cos(a), sx·sin(a), sy·-sin(a), sy·cos(a), x, y] → rotate(a[, cx, cy])·(scale or skewX) or
  123. // [sx·cos(a), sy·sin(a), sx·-sin(a), sy·cos(a), x, y] → scale(sx, sy)·rotate(a[, cx, cy]) (if !scaleBefore)
  124. } else if (!colsSum || (sx == 1 && sy == 1) || !scaleBefore) {
  125. if (!scaleBefore) {
  126. sx = (data[0] < 0 ? -1 : 1) * Math.hypot(data[0], data[2]);
  127. sy = (data[3] < 0 ? -1 : 1) * Math.hypot(data[1], data[3]);
  128. transforms.push({ name: 'scale', data: [sx, sy] });
  129. }
  130. var angle = Math.min(Math.max(-1, data[0] / sx), 1),
  131. rotate = [mth.acos(angle, floatPrecision) * ((scaleBefore ? 1 : sy) * data[1] < 0 ? -1 : 1)];
  132. if (rotate[0]) transforms.push({ name: 'rotate', data: rotate });
  133. if (rowsSum && colsSum) transforms.push({
  134. name: 'skewX',
  135. data: [mth.atan(colsSum / (sx * sx), floatPrecision)]
  136. });
  137. // rotate(a, cx, cy) can consume translate() within optional arguments cx, cy (rotation point)
  138. if (rotate[0] && (data[4] || data[5])) {
  139. transforms.shift();
  140. var cos = data[0] / sx,
  141. sin = data[1] / (scaleBefore ? sx : sy),
  142. x = data[4] * (scaleBefore || sy),
  143. y = data[5] * (scaleBefore || sx),
  144. denom = (Math.pow(1 - cos, 2) + Math.pow(sin, 2)) * (scaleBefore || sx * sy);
  145. rotate.push(((1 - cos) * x - sin * y) / denom);
  146. rotate.push(((1 - cos) * y + sin * x) / denom);
  147. }
  148. // Too many transformations, return original matrix if it isn't just a scale/translate
  149. } else if (data[1] || data[2]) {
  150. return transform;
  151. }
  152. if (scaleBefore && (sx != 1 || sy != 1) || !transforms.length) transforms.push({
  153. name: 'scale',
  154. data: sx == sy ? [sx] : [sx, sy]
  155. });
  156. return transforms;
  157. };
  158. /**
  159. * Convert transform to the matrix data.
  160. *
  161. * @param {Object} transform transform object
  162. * @return {Array} matrix data
  163. */
  164. function transformToMatrix(transform) {
  165. if (transform.name === 'matrix') return transform.data;
  166. var matrix;
  167. switch (transform.name) {
  168. case 'translate':
  169. // [1, 0, 0, 1, tx, ty]
  170. matrix = [1, 0, 0, 1, transform.data[0], transform.data[1] || 0];
  171. break;
  172. case 'scale':
  173. // [sx, 0, 0, sy, 0, 0]
  174. matrix = [transform.data[0], 0, 0, transform.data[1] || transform.data[0], 0, 0];
  175. break;
  176. case 'rotate':
  177. // [cos(a), sin(a), -sin(a), cos(a), x, y]
  178. var cos = mth.cos(transform.data[0]),
  179. sin = mth.sin(transform.data[0]),
  180. cx = transform.data[1] || 0,
  181. cy = transform.data[2] || 0;
  182. matrix = [cos, sin, -sin, cos, (1 - cos) * cx + sin * cy, (1 - cos) * cy - sin * cx];
  183. break;
  184. case 'skewX':
  185. // [1, 0, tan(a), 1, 0, 0]
  186. matrix = [1, 0, mth.tan(transform.data[0]), 1, 0, 0];
  187. break;
  188. case 'skewY':
  189. // [1, tan(a), 0, 1, 0, 0]
  190. matrix = [1, mth.tan(transform.data[0]), 0, 1, 0, 0];
  191. break;
  192. }
  193. return matrix;
  194. }
  195. /**
  196. * Applies transformation to an arc. To do so, we represent ellipse as a matrix, multiply it
  197. * by the transformation matrix and use a singular value decomposition to represent in a form
  198. * rotate(θ)·scale(a b)·rotate(φ). This gives us new ellipse params a, b and θ.
  199. * SVD is being done with the formulae provided by Wolffram|Alpha (svd {{m0, m2}, {m1, m3}})
  200. *
  201. * @param {Array} arc [a, b, rotation in deg]
  202. * @param {Array} transform transformation matrix
  203. * @return {Array} arc transformed input arc
  204. */
  205. exports.transformArc = function(arc, transform) {
  206. var a = arc[0],
  207. b = arc[1],
  208. rot = arc[2] * Math.PI / 180,
  209. cos = Math.cos(rot),
  210. sin = Math.sin(rot),
  211. h = Math.pow(arc[5] * cos + arc[6] * sin, 2) / (4 * a * a) +
  212. Math.pow(arc[6] * cos - arc[5] * sin, 2) / (4 * b * b);
  213. if (h > 1) {
  214. h = Math.sqrt(h);
  215. a *= h;
  216. b *= h;
  217. }
  218. var ellipse = [a * cos, a * sin, -b * sin, b * cos, 0, 0],
  219. m = multiplyTransformMatrices(transform, ellipse),
  220. // Decompose the new ellipse matrix
  221. lastCol = m[2] * m[2] + m[3] * m[3],
  222. squareSum = m[0] * m[0] + m[1] * m[1] + lastCol,
  223. root = Math.hypot(m[0] - m[3], m[1] + m[2]) * Math.hypot(m[0] + m[3], m[1] - m[2]);
  224. if (!root) { // circle
  225. arc[0] = arc[1] = Math.sqrt(squareSum / 2);
  226. arc[2] = 0;
  227. } else {
  228. var majorAxisSqr = (squareSum + root) / 2,
  229. minorAxisSqr = (squareSum - root) / 2,
  230. major = Math.abs(majorAxisSqr - lastCol) > 1e-6,
  231. sub = (major ? majorAxisSqr : minorAxisSqr) - lastCol,
  232. rowsSum = m[0] * m[2] + m[1] * m[3],
  233. term1 = m[0] * sub + m[2] * rowsSum,
  234. term2 = m[1] * sub + m[3] * rowsSum;
  235. arc[0] = Math.sqrt(majorAxisSqr);
  236. arc[1] = Math.sqrt(minorAxisSqr);
  237. arc[2] = ((major ? term2 < 0 : term1 > 0) ? -1 : 1) *
  238. Math.acos((major ? term1 : term2) / Math.hypot(term1, term2)) * 180 / Math.PI;
  239. }
  240. if ((transform[0] < 0) !== (transform[3] < 0)) {
  241. // Flip the sweep flag if coordinates are being flipped horizontally XOR vertically
  242. arc[4] = 1 - arc[4];
  243. }
  244. return arc;
  245. };
  246. /**
  247. * Multiply transformation matrices.
  248. *
  249. * @param {Array} a matrix A data
  250. * @param {Array} b matrix B data
  251. * @return {Array} result
  252. */
  253. function multiplyTransformMatrices(a, b) {
  254. return [
  255. a[0] * b[0] + a[2] * b[1],
  256. a[1] * b[0] + a[3] * b[1],
  257. a[0] * b[2] + a[2] * b[3],
  258. a[1] * b[2] + a[3] * b[3],
  259. a[0] * b[4] + a[2] * b[5] + a[4],
  260. a[1] * b[4] + a[3] * b[5] + a[5]
  261. ];
  262. }