svg-helper.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /**
  2. * Parse the d property of an SVG path into an array of drawing commands.
  3. * @param {String} d SvgPath d attribute.]
  4. * @return {Array} an array of drawing commands.
  5. */
  6. export function parseSvgPath(d) { //jshint ignore:line
  7. 'use strict';
  8. var commands = [];
  9. var commandTokens = ['M','L','I','H','V','C','S','Q','T','A'];
  10. var command;
  11. var in_x = false;
  12. var in_y = false;
  13. var x = '';
  14. var y = '';
  15. for(var i = 0; i <= d.length; i++) {
  16. if (commandTokens.indexOf(d[i]) !== -1) {
  17. if (in_x || in_y) {
  18. commands.push({command: command, x: x, y: y});
  19. x = '';
  20. y = '';
  21. }
  22. command = d[i];
  23. in_x = true;
  24. in_y = false;
  25. }
  26. else {
  27. if (d[i] === ',') {
  28. if (in_y) {
  29. commands.push({command: command, x: x, y: y});
  30. x = '';
  31. y = '';
  32. }
  33. in_x = !in_x;
  34. in_y = !in_y;
  35. }
  36. else if (in_x) {
  37. x += d[i];
  38. }
  39. else if (in_y) {
  40. y += d[i];
  41. }
  42. }
  43. }
  44. if (d[i] !== ',' && in_y) {
  45. commands.push({command: command, x: x, y: y});
  46. }
  47. return commands;
  48. }