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.

971 lines
30 KiB

4 years ago
  1. 'use strict';
  2. exports.type = 'perItem';
  3. exports.active = true;
  4. exports.description = 'optimizes path data: writes in shorter form, applies transformations';
  5. exports.params = {
  6. applyTransforms: true,
  7. applyTransformsStroked: true,
  8. makeArcs: {
  9. threshold: 2.5, // coefficient of rounding error
  10. tolerance: 0.5 // percentage of radius
  11. },
  12. straightCurves: true,
  13. lineShorthands: true,
  14. curveSmoothShorthands: true,
  15. floatPrecision: 3,
  16. transformPrecision: 5,
  17. removeUseless: true,
  18. collapseRepeated: true,
  19. utilizeAbsolute: true,
  20. leadingZero: true,
  21. negativeExtraSpace: true,
  22. noSpaceAfterFlags: true,
  23. forceAbsolutePath: false
  24. };
  25. var pathElems = require('./_collections.js').pathElems,
  26. path2js = require('./_path.js').path2js,
  27. js2path = require('./_path.js').js2path,
  28. applyTransforms = require('./_path.js').applyTransforms,
  29. cleanupOutData = require('../lib/svgo/tools').cleanupOutData,
  30. roundData,
  31. precision,
  32. error,
  33. arcThreshold,
  34. arcTolerance,
  35. hasMarkerMid,
  36. hasStrokeLinecap;
  37. /**
  38. * Convert absolute Path to relative,
  39. * collapse repeated instructions,
  40. * detect and convert Lineto shorthands,
  41. * remove useless instructions like "l0,0",
  42. * trim useless delimiters and leading zeros,
  43. * decrease accuracy of floating-point numbers.
  44. *
  45. * @see http://www.w3.org/TR/SVG/paths.html#PathData
  46. *
  47. * @param {Object} item current iteration item
  48. * @param {Object} params plugin params
  49. * @return {Boolean} if false, item will be filtered out
  50. *
  51. * @author Kir Belevich
  52. */
  53. exports.fn = function(item, params) {
  54. if (item.isElem(pathElems) && item.hasAttr('d')) {
  55. precision = params.floatPrecision;
  56. error = precision !== false ? +Math.pow(.1, precision).toFixed(precision) : 1e-2;
  57. roundData = precision > 0 && precision < 20 ? strongRound : round;
  58. if (params.makeArcs) {
  59. arcThreshold = params.makeArcs.threshold;
  60. arcTolerance = params.makeArcs.tolerance;
  61. }
  62. hasMarkerMid = item.hasAttr('marker-mid');
  63. var stroke = item.computedAttr('stroke'),
  64. strokeLinecap = item.computedAttr('stroke');
  65. hasStrokeLinecap = stroke && stroke != 'none' && strokeLinecap && strokeLinecap != 'butt';
  66. var data = path2js(item);
  67. // TODO: get rid of functions returns
  68. if (data.length) {
  69. convertToRelative(data);
  70. if (params.applyTransforms) {
  71. data = applyTransforms(item, data, params);
  72. }
  73. data = filters(data, params);
  74. if (params.utilizeAbsolute) {
  75. data = convertToMixed(data, params);
  76. }
  77. js2path(item, data, params);
  78. }
  79. }
  80. };
  81. /**
  82. * Convert absolute path data coordinates to relative.
  83. *
  84. * @param {Array} path input path data
  85. * @param {Object} params plugin params
  86. * @return {Array} output path data
  87. */
  88. function convertToRelative(path) {
  89. var point = [0, 0],
  90. subpathPoint = [0, 0],
  91. baseItem;
  92. path.forEach(function(item, index) {
  93. var instruction = item.instruction,
  94. data = item.data;
  95. // data !== !z
  96. if (data) {
  97. // already relative
  98. // recalculate current point
  99. if ('mcslqta'.indexOf(instruction) > -1) {
  100. point[0] += data[data.length - 2];
  101. point[1] += data[data.length - 1];
  102. if (instruction === 'm') {
  103. subpathPoint[0] = point[0];
  104. subpathPoint[1] = point[1];
  105. baseItem = item;
  106. }
  107. } else if (instruction === 'h') {
  108. point[0] += data[0];
  109. } else if (instruction === 'v') {
  110. point[1] += data[0];
  111. }
  112. // convert absolute path data coordinates to relative
  113. // if "M" was not transformed from "m"
  114. // M → m
  115. if (instruction === 'M') {
  116. if (index > 0) instruction = 'm';
  117. data[0] -= point[0];
  118. data[1] -= point[1];
  119. subpathPoint[0] = point[0] += data[0];
  120. subpathPoint[1] = point[1] += data[1];
  121. baseItem = item;
  122. }
  123. // L → l
  124. // T → t
  125. else if ('LT'.indexOf(instruction) > -1) {
  126. instruction = instruction.toLowerCase();
  127. // x y
  128. // 0 1
  129. data[0] -= point[0];
  130. data[1] -= point[1];
  131. point[0] += data[0];
  132. point[1] += data[1];
  133. // C → c
  134. } else if (instruction === 'C') {
  135. instruction = 'c';
  136. // x1 y1 x2 y2 x y
  137. // 0 1 2 3 4 5
  138. data[0] -= point[0];
  139. data[1] -= point[1];
  140. data[2] -= point[0];
  141. data[3] -= point[1];
  142. data[4] -= point[0];
  143. data[5] -= point[1];
  144. point[0] += data[4];
  145. point[1] += data[5];
  146. // S → s
  147. // Q → q
  148. } else if ('SQ'.indexOf(instruction) > -1) {
  149. instruction = instruction.toLowerCase();
  150. // x1 y1 x y
  151. // 0 1 2 3
  152. data[0] -= point[0];
  153. data[1] -= point[1];
  154. data[2] -= point[0];
  155. data[3] -= point[1];
  156. point[0] += data[2];
  157. point[1] += data[3];
  158. // A → a
  159. } else if (instruction === 'A') {
  160. instruction = 'a';
  161. // rx ry x-axis-rotation large-arc-flag sweep-flag x y
  162. // 0 1 2 3 4 5 6
  163. data[5] -= point[0];
  164. data[6] -= point[1];
  165. point[0] += data[5];
  166. point[1] += data[6];
  167. // H → h
  168. } else if (instruction === 'H') {
  169. instruction = 'h';
  170. data[0] -= point[0];
  171. point[0] += data[0];
  172. // V → v
  173. } else if (instruction === 'V') {
  174. instruction = 'v';
  175. data[0] -= point[1];
  176. point[1] += data[0];
  177. }
  178. item.instruction = instruction;
  179. item.data = data;
  180. // store absolute coordinates for later use
  181. item.coords = point.slice(-2);
  182. }
  183. // !data === z, reset current point
  184. else if (instruction == 'z') {
  185. if (baseItem) {
  186. item.coords = baseItem.coords;
  187. }
  188. point[0] = subpathPoint[0];
  189. point[1] = subpathPoint[1];
  190. }
  191. item.base = index > 0 ? path[index - 1].coords : [0, 0];
  192. });
  193. return path;
  194. }
  195. /**
  196. * Main filters loop.
  197. *
  198. * @param {Array} path input path data
  199. * @param {Object} params plugin params
  200. * @return {Array} output path data
  201. */
  202. function filters(path, params) {
  203. var stringify = data2Path.bind(null, params),
  204. relSubpoint = [0, 0],
  205. pathBase = [0, 0],
  206. prev = {};
  207. path = path.filter(function(item, index, path) {
  208. var instruction = item.instruction,
  209. data = item.data,
  210. next = path[index + 1];
  211. if (data) {
  212. var sdata = data,
  213. circle;
  214. if (instruction === 's') {
  215. sdata = [0, 0].concat(data);
  216. if ('cs'.indexOf(prev.instruction) > -1) {
  217. var pdata = prev.data,
  218. n = pdata.length;
  219. // (-x, -y) of the prev tangent point relative to the current point
  220. sdata[0] = pdata[n - 2] - pdata[n - 4];
  221. sdata[1] = pdata[n - 1] - pdata[n - 3];
  222. }
  223. }
  224. // convert curves to arcs if possible
  225. if (
  226. params.makeArcs &&
  227. (instruction == 'c' || instruction == 's') &&
  228. isConvex(sdata) &&
  229. (circle = findCircle(sdata))
  230. ) {
  231. var r = roundData([circle.radius])[0],
  232. angle = findArcAngle(sdata, circle),
  233. sweep = sdata[5] * sdata[0] - sdata[4] * sdata[1] > 0 ? 1 : 0,
  234. arc = {
  235. instruction: 'a',
  236. data: [r, r, 0, 0, sweep, sdata[4], sdata[5]],
  237. coords: item.coords.slice(),
  238. base: item.base
  239. },
  240. output = [arc],
  241. // relative coordinates to adjust the found circle
  242. relCenter = [circle.center[0] - sdata[4], circle.center[1] - sdata[5]],
  243. relCircle = { center: relCenter, radius: circle.radius },
  244. arcCurves = [item],
  245. hasPrev = 0,
  246. suffix = '',
  247. nextLonghand;
  248. if (
  249. prev.instruction == 'c' && isConvex(prev.data) && isArcPrev(prev.data, circle) ||
  250. prev.instruction == 'a' && prev.sdata && isArcPrev(prev.sdata, circle)
  251. ) {
  252. arcCurves.unshift(prev);
  253. arc.base = prev.base;
  254. arc.data[5] = arc.coords[0] - arc.base[0];
  255. arc.data[6] = arc.coords[1] - arc.base[1];
  256. var prevData = prev.instruction == 'a' ? prev.sdata : prev.data;
  257. var prevAngle = findArcAngle(prevData,
  258. {
  259. center: [prevData[4] + circle.center[0], prevData[5] + circle.center[1]],
  260. radius: circle.radius
  261. }
  262. );
  263. angle += prevAngle;
  264. if (angle > Math.PI) arc.data[3] = 1;
  265. hasPrev = 1;
  266. }
  267. // check if next curves are fitting the arc
  268. for (var j = index; (next = path[++j]) && ~'cs'.indexOf(next.instruction);) {
  269. var nextData = next.data;
  270. if (next.instruction == 's') {
  271. nextLonghand = makeLonghand({instruction: 's', data: next.data.slice() },
  272. path[j - 1].data);
  273. nextData = nextLonghand.data;
  274. nextLonghand.data = nextData.slice(0, 2);
  275. suffix = stringify([nextLonghand]);
  276. }
  277. if (isConvex(nextData) && isArc(nextData, relCircle)) {
  278. angle += findArcAngle(nextData, relCircle);
  279. if (angle - 2 * Math.PI > 1e-3) break; // more than 360°
  280. if (angle > Math.PI) arc.data[3] = 1;
  281. arcCurves.push(next);
  282. if (2 * Math.PI - angle > 1e-3) { // less than 360°
  283. arc.coords = next.coords;
  284. arc.data[5] = arc.coords[0] - arc.base[0];
  285. arc.data[6] = arc.coords[1] - arc.base[1];
  286. } else {
  287. // full circle, make a half-circle arc and add a second one
  288. arc.data[5] = 2 * (relCircle.center[0] - nextData[4]);
  289. arc.data[6] = 2 * (relCircle.center[1] - nextData[5]);
  290. arc.coords = [arc.base[0] + arc.data[5], arc.base[1] + arc.data[6]];
  291. arc = {
  292. instruction: 'a',
  293. data: [r, r, 0, 0, sweep,
  294. next.coords[0] - arc.coords[0], next.coords[1] - arc.coords[1]],
  295. coords: next.coords,
  296. base: arc.coords
  297. };
  298. output.push(arc);
  299. j++;
  300. break;
  301. }
  302. relCenter[0] -= nextData[4];
  303. relCenter[1] -= nextData[5];
  304. } else break;
  305. }
  306. if ((stringify(output) + suffix).length < stringify(arcCurves).length) {
  307. if (path[j] && path[j].instruction == 's') {
  308. makeLonghand(path[j], path[j - 1].data);
  309. }
  310. if (hasPrev) {
  311. var prevArc = output.shift();
  312. roundData(prevArc.data);
  313. relSubpoint[0] += prevArc.data[5] - prev.data[prev.data.length - 2];
  314. relSubpoint[1] += prevArc.data[6] - prev.data[prev.data.length - 1];
  315. prev.instruction = 'a';
  316. prev.data = prevArc.data;
  317. item.base = prev.coords = prevArc.coords;
  318. }
  319. arc = output.shift();
  320. if (arcCurves.length == 1) {
  321. item.sdata = sdata.slice(); // preserve curve data for future checks
  322. } else if (arcCurves.length - 1 - hasPrev > 0) {
  323. // filter out consumed next items
  324. path.splice.apply(path, [index + 1, arcCurves.length - 1 - hasPrev].concat(output));
  325. }
  326. if (!arc) return false;
  327. instruction = 'a';
  328. data = arc.data;
  329. item.coords = arc.coords;
  330. }
  331. }
  332. // Rounding relative coordinates, taking in account accummulating error
  333. // to get closer to absolute coordinates. Sum of rounded value remains same:
  334. // l .25 3 .25 2 .25 3 .25 2 -> l .3 3 .2 2 .3 3 .2 2
  335. if (precision !== false) {
  336. if ('mltqsc'.indexOf(instruction) > -1) {
  337. for (var i = data.length; i--;) {
  338. data[i] += item.base[i % 2] - relSubpoint[i % 2];
  339. }
  340. } else if (instruction == 'h') {
  341. data[0] += item.base[0] - relSubpoint[0];
  342. } else if (instruction == 'v') {
  343. data[0] += item.base[1] - relSubpoint[1];
  344. } else if (instruction == 'a') {
  345. data[5] += item.base[0] - relSubpoint[0];
  346. data[6] += item.base[1] - relSubpoint[1];
  347. }
  348. roundData(data);
  349. if (instruction == 'h') relSubpoint[0] += data[0];
  350. else if (instruction == 'v') relSubpoint[1] += data[0];
  351. else {
  352. relSubpoint[0] += data[data.length - 2];
  353. relSubpoint[1] += data[data.length - 1];
  354. }
  355. roundData(relSubpoint);
  356. if (instruction.toLowerCase() == 'm') {
  357. pathBase[0] = relSubpoint[0];
  358. pathBase[1] = relSubpoint[1];
  359. }
  360. }
  361. // convert straight curves into lines segments
  362. if (params.straightCurves) {
  363. if (
  364. instruction === 'c' &&
  365. isCurveStraightLine(data) ||
  366. instruction === 's' &&
  367. isCurveStraightLine(sdata)
  368. ) {
  369. if (next && next.instruction == 's')
  370. makeLonghand(next, data); // fix up next curve
  371. instruction = 'l';
  372. data = data.slice(-2);
  373. }
  374. else if (
  375. instruction === 'q' &&
  376. isCurveStraightLine(data)
  377. ) {
  378. if (next && next.instruction == 't')
  379. makeLonghand(next, data); // fix up next curve
  380. instruction = 'l';
  381. data = data.slice(-2);
  382. }
  383. else if (
  384. instruction === 't' &&
  385. prev.instruction !== 'q' &&
  386. prev.instruction !== 't'
  387. ) {
  388. instruction = 'l';
  389. data = data.slice(-2);
  390. }
  391. else if (
  392. instruction === 'a' &&
  393. (data[0] === 0 || data[1] === 0)
  394. ) {
  395. instruction = 'l';
  396. data = data.slice(-2);
  397. }
  398. }
  399. // horizontal and vertical line shorthands
  400. // l 50 0 → h 50
  401. // l 0 50 → v 50
  402. if (
  403. params.lineShorthands &&
  404. instruction === 'l'
  405. ) {
  406. if (data[1] === 0) {
  407. instruction = 'h';
  408. data.pop();
  409. } else if (data[0] === 0) {
  410. instruction = 'v';
  411. data.shift();
  412. }
  413. }
  414. // collapse repeated commands
  415. // h 20 h 30 -> h 50
  416. if (
  417. params.collapseRepeated &&
  418. !hasMarkerMid &&
  419. ('mhv'.indexOf(instruction) > -1) &&
  420. prev.instruction &&
  421. instruction == prev.instruction.toLowerCase() &&
  422. (
  423. (instruction != 'h' && instruction != 'v') ||
  424. (prev.data[0] >= 0) == (item.data[0] >= 0)
  425. )) {
  426. prev.data[0] += data[0];
  427. if (instruction != 'h' && instruction != 'v') {
  428. prev.data[1] += data[1];
  429. }
  430. prev.coords = item.coords;
  431. path[index] = prev;
  432. return false;
  433. }
  434. // convert curves into smooth shorthands
  435. if (params.curveSmoothShorthands && prev.instruction) {
  436. // curveto
  437. if (instruction === 'c') {
  438. // c + c → c + s
  439. if (
  440. prev.instruction === 'c' &&
  441. data[0] === -(prev.data[2] - prev.data[4]) &&
  442. data[1] === -(prev.data[3] - prev.data[5])
  443. ) {
  444. instruction = 's';
  445. data = data.slice(2);
  446. }
  447. // s + c → s + s
  448. else if (
  449. prev.instruction === 's' &&
  450. data[0] === -(prev.data[0] - prev.data[2]) &&
  451. data[1] === -(prev.data[1] - prev.data[3])
  452. ) {
  453. instruction = 's';
  454. data = data.slice(2);
  455. }
  456. // [^cs] + c → [^cs] + s
  457. else if (
  458. 'cs'.indexOf(prev.instruction) === -1 &&
  459. data[0] === 0 &&
  460. data[1] === 0
  461. ) {
  462. instruction = 's';
  463. data = data.slice(2);
  464. }
  465. }
  466. // quadratic Bézier curveto
  467. else if (instruction === 'q') {
  468. // q + q → q + t
  469. if (
  470. prev.instruction === 'q' &&
  471. data[0] === (prev.data[2] - prev.data[0]) &&
  472. data[1] === (prev.data[3] - prev.data[1])
  473. ) {
  474. instruction = 't';
  475. data = data.slice(2);
  476. }
  477. // t + q → t + t
  478. else if (
  479. prev.instruction === 't' &&
  480. data[2] === prev.data[0] &&
  481. data[3] === prev.data[1]
  482. ) {
  483. instruction = 't';
  484. data = data.slice(2);
  485. }
  486. }
  487. }
  488. // remove useless non-first path segments
  489. if (params.removeUseless && !hasStrokeLinecap) {
  490. // l 0,0 / h 0 / v 0 / q 0,0 0,0 / t 0,0 / c 0,0 0,0 0,0 / s 0,0 0,0
  491. if (
  492. (
  493. 'lhvqtcs'.indexOf(instruction) > -1
  494. ) &&
  495. data.every(function(i) { return i === 0; })
  496. ) {
  497. path[index] = prev;
  498. return false;
  499. }
  500. // a 25,25 -30 0,1 0,0
  501. if (
  502. instruction === 'a' &&
  503. data[5] === 0 &&
  504. data[6] === 0
  505. ) {
  506. path[index] = prev;
  507. return false;
  508. }
  509. }
  510. item.instruction = instruction;
  511. item.data = data;
  512. prev = item;
  513. } else {
  514. // z resets coordinates
  515. relSubpoint[0] = pathBase[0];
  516. relSubpoint[1] = pathBase[1];
  517. if (prev.instruction == 'z') return false;
  518. prev = item;
  519. }
  520. return true;
  521. });
  522. return path;
  523. }
  524. /**
  525. * Writes data in shortest form using absolute or relative coordinates.
  526. *
  527. * @param {Array} data input path data
  528. * @return {Boolean} output
  529. */
  530. function convertToMixed(path, params) {
  531. var prev = path[0];
  532. path = path.filter(function(item, index) {
  533. if (index == 0) return true;
  534. if (!item.data) {
  535. prev = item;
  536. return true;
  537. }
  538. var instruction = item.instruction,
  539. data = item.data,
  540. adata = data && data.slice(0);
  541. if ('mltqsc'.indexOf(instruction) > -1) {
  542. for (var i = adata.length; i--;) {
  543. adata[i] += item.base[i % 2];
  544. }
  545. } else if (instruction == 'h') {
  546. adata[0] += item.base[0];
  547. } else if (instruction == 'v') {
  548. adata[0] += item.base[1];
  549. } else if (instruction == 'a') {
  550. adata[5] += item.base[0];
  551. adata[6] += item.base[1];
  552. }
  553. roundData(adata);
  554. var absoluteDataStr = cleanupOutData(adata, params),
  555. relativeDataStr = cleanupOutData(data, params);
  556. // Convert to absolute coordinates if it's shorter or forceAbsolutePath is true.
  557. // v-20 -> V0
  558. // Don't convert if it fits following previous instruction.
  559. // l20 30-10-50 instead of l20 30L20 30
  560. if (
  561. params.forceAbsolutePath || (
  562. absoluteDataStr.length < relativeDataStr.length &&
  563. !(
  564. params.negativeExtraSpace &&
  565. instruction == prev.instruction &&
  566. prev.instruction.charCodeAt(0) > 96 &&
  567. absoluteDataStr.length == relativeDataStr.length - 1 &&
  568. (data[0] < 0 || /^0\./.test(data[0]) && prev.data[prev.data.length - 1] % 1)
  569. ))
  570. ) {
  571. item.instruction = instruction.toUpperCase();
  572. item.data = adata;
  573. }
  574. prev = item;
  575. return true;
  576. });
  577. return path;
  578. }
  579. /**
  580. * Checks if curve is convex. Control points of such a curve must form
  581. * a convex quadrilateral with diagonals crosspoint inside of it.
  582. *
  583. * @param {Array} data input path data
  584. * @return {Boolean} output
  585. */
  586. function isConvex(data) {
  587. var center = getIntersection([0, 0, data[2], data[3], data[0], data[1], data[4], data[5]]);
  588. return center &&
  589. (data[2] < center[0] == center[0] < 0) &&
  590. (data[3] < center[1] == center[1] < 0) &&
  591. (data[4] < center[0] == center[0] < data[0]) &&
  592. (data[5] < center[1] == center[1] < data[1]);
  593. }
  594. /**
  595. * Computes lines equations by two points and returns their intersection point.
  596. *
  597. * @param {Array} coords 8 numbers for 4 pairs of coordinates (x,y)
  598. * @return {Array|undefined} output coordinate of lines' crosspoint
  599. */
  600. function getIntersection(coords) {
  601. // Prev line equation parameters.
  602. var a1 = coords[1] - coords[3], // y1 - y2
  603. b1 = coords[2] - coords[0], // x2 - x1
  604. c1 = coords[0] * coords[3] - coords[2] * coords[1], // x1 * y2 - x2 * y1
  605. // Next line equation parameters
  606. a2 = coords[5] - coords[7], // y1 - y2
  607. b2 = coords[6] - coords[4], // x2 - x1
  608. c2 = coords[4] * coords[7] - coords[5] * coords[6], // x1 * y2 - x2 * y1
  609. denom = (a1 * b2 - a2 * b1);
  610. if (!denom) return; // parallel lines havn't an intersection
  611. var cross = [
  612. (b1 * c2 - b2 * c1) / denom,
  613. (a1 * c2 - a2 * c1) / -denom
  614. ];
  615. if (
  616. !isNaN(cross[0]) && !isNaN(cross[1]) &&
  617. isFinite(cross[0]) && isFinite(cross[1])
  618. ) {
  619. return cross;
  620. }
  621. }
  622. /**
  623. * Decrease accuracy of floating-point numbers
  624. * in path data keeping a specified number of decimals.
  625. * Smart rounds values like 2.3491 to 2.35 instead of 2.349.
  626. * Doesn't apply "smartness" if the number precision fits already.
  627. *
  628. * @param {Array} data input data array
  629. * @return {Array} output data array
  630. */
  631. function strongRound(data) {
  632. for (var i = data.length; i-- > 0;) {
  633. if (data[i].toFixed(precision) != data[i]) {
  634. var rounded = +data[i].toFixed(precision - 1);
  635. data[i] = +Math.abs(rounded - data[i]).toFixed(precision + 1) >= error ?
  636. +data[i].toFixed(precision) :
  637. rounded;
  638. }
  639. }
  640. return data;
  641. }
  642. /**
  643. * Simple rounding function if precision is 0.
  644. *
  645. * @param {Array} data input data array
  646. * @return {Array} output data array
  647. */
  648. function round(data) {
  649. for (var i = data.length; i-- > 0;) {
  650. data[i] = Math.round(data[i]);
  651. }
  652. return data;
  653. }
  654. /**
  655. * Checks if a curve is a straight line by measuring distance
  656. * from middle points to the line formed by end points.
  657. *
  658. * @param {Array} xs array of curve points x-coordinates
  659. * @param {Array} ys array of curve points y-coordinates
  660. * @return {Boolean}
  661. */
  662. function isCurveStraightLine(data) {
  663. // Get line equation a·x + b·y + c = 0 coefficients a, b (c = 0) by start and end points.
  664. var i = data.length - 2,
  665. a = -data[i + 1], // y1 − y2 (y1 = 0)
  666. b = data[i], // x2 − x1 (x1 = 0)
  667. d = 1 / (a * a + b * b); // same part for all points
  668. if (i <= 1 || !isFinite(d)) return false; // curve that ends at start point isn't the case
  669. // Distance from point (x0, y0) to the line is sqrt((c − a·x0 − b·y0)² / (a² + b²))
  670. while ((i -= 2) >= 0) {
  671. if (Math.sqrt(Math.pow(a * data[i] + b * data[i + 1], 2) * d) > error)
  672. return false;
  673. }
  674. return true;
  675. }
  676. /**
  677. * Converts next curve from shorthand to full form using the current curve data.
  678. *
  679. * @param {Object} item curve to convert
  680. * @param {Array} data current curve data
  681. */
  682. function makeLonghand(item, data) {
  683. switch (item.instruction) {
  684. case 's': item.instruction = 'c'; break;
  685. case 't': item.instruction = 'q'; break;
  686. }
  687. item.data.unshift(data[data.length - 2] - data[data.length - 4], data[data.length - 1] - data[data.length - 3]);
  688. return item;
  689. }
  690. /**
  691. * Returns distance between two points
  692. *
  693. * @param {Array} point1 first point coordinates
  694. * @param {Array} point2 second point coordinates
  695. * @return {Number} distance
  696. */
  697. function getDistance(point1, point2) {
  698. return Math.hypot(point1[0] - point2[0], point1[1] - point2[1]);
  699. }
  700. /**
  701. * Returns coordinates of the curve point corresponding to the certain t
  702. * a·(1 - t)³·p1 + b·(1 - t)²·t·p2 + c·(1 - t)·t²·p3 + d·t³·p4,
  703. * where pN are control points and p1 is zero due to relative coordinates.
  704. *
  705. * @param {Array} curve array of curve points coordinates
  706. * @param {Number} t parametric position from 0 to 1
  707. * @return {Array} Point coordinates
  708. */
  709. function getCubicBezierPoint(curve, t) {
  710. var sqrT = t * t,
  711. cubT = sqrT * t,
  712. mt = 1 - t,
  713. sqrMt = mt * mt;
  714. return [
  715. 3 * sqrMt * t * curve[0] + 3 * mt * sqrT * curve[2] + cubT * curve[4],
  716. 3 * sqrMt * t * curve[1] + 3 * mt * sqrT * curve[3] + cubT * curve[5]
  717. ];
  718. }
  719. /**
  720. * Finds circle by 3 points of the curve and checks if the curve fits the found circle.
  721. *
  722. * @param {Array} curve
  723. * @return {Object|undefined} circle
  724. */
  725. function findCircle(curve) {
  726. var midPoint = getCubicBezierPoint(curve, 1/2),
  727. m1 = [midPoint[0] / 2, midPoint[1] / 2],
  728. m2 = [(midPoint[0] + curve[4]) / 2, (midPoint[1] + curve[5]) / 2],
  729. center = getIntersection([
  730. m1[0], m1[1],
  731. m1[0] + m1[1], m1[1] - m1[0],
  732. m2[0], m2[1],
  733. m2[0] + (m2[1] - midPoint[1]), m2[1] - (m2[0] - midPoint[0])
  734. ]),
  735. radius = center && getDistance([0, 0], center),
  736. tolerance = Math.min(arcThreshold * error, arcTolerance * radius / 100);
  737. if (center && radius < 1e15 &&
  738. [1/4, 3/4].every(function(point) {
  739. return Math.abs(getDistance(getCubicBezierPoint(curve, point), center) - radius) <= tolerance;
  740. }))
  741. return { center: center, radius: radius};
  742. }
  743. /**
  744. * Checks if a curve fits the given circle.
  745. *
  746. * @param {Object} circle
  747. * @param {Array} curve
  748. * @return {Boolean}
  749. */
  750. function isArc(curve, circle) {
  751. var tolerance = Math.min(arcThreshold * error, arcTolerance * circle.radius / 100);
  752. return [0, 1/4, 1/2, 3/4, 1].every(function(point) {
  753. return Math.abs(getDistance(getCubicBezierPoint(curve, point), circle.center) - circle.radius) <= tolerance;
  754. });
  755. }
  756. /**
  757. * Checks if a previous curve fits the given circle.
  758. *
  759. * @param {Object} circle
  760. * @param {Array} curve
  761. * @return {Boolean}
  762. */
  763. function isArcPrev(curve, circle) {
  764. return isArc(curve, {
  765. center: [circle.center[0] + curve[4], circle.center[1] + curve[5]],
  766. radius: circle.radius
  767. });
  768. }
  769. /**
  770. * Finds angle of a curve fitting the given arc.
  771. * @param {Array} curve
  772. * @param {Object} relCircle
  773. * @return {Number} angle
  774. */
  775. function findArcAngle(curve, relCircle) {
  776. var x1 = -relCircle.center[0],
  777. y1 = -relCircle.center[1],
  778. x2 = curve[4] - relCircle.center[0],
  779. y2 = curve[5] - relCircle.center[1];
  780. return Math.acos(
  781. (x1 * x2 + y1 * y2) /
  782. Math.sqrt((x1 * x1 + y1 * y1) * (x2 * x2 + y2 * y2))
  783. );
  784. }
  785. /**
  786. * Converts given path data to string.
  787. *
  788. * @param {Object} params
  789. * @param {Array} pathData
  790. * @return {String}
  791. */
  792. function data2Path(params, pathData) {
  793. return pathData.reduce(function(pathString, item) {
  794. var strData = '';
  795. if (item.data) {
  796. strData = cleanupOutData(roundData(item.data.slice()), params);
  797. }
  798. return pathString + item.instruction + strData;
  799. }, '');
  800. }