convertPathData.js 30 KB

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