convertShapeToPath.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. 'use strict';
  2. exports.type = 'perItem';
  3. exports.active = true;
  4. exports.description = 'converts basic shapes to more compact path form';
  5. var none = { value: 0 },
  6. regNumber = /[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?/g;
  7. /**
  8. * Converts basic shape to more compact path.
  9. * It also allows further optimizations like
  10. * combining paths with similar attributes.
  11. *
  12. * @see http://www.w3.org/TR/SVG/shapes.html
  13. *
  14. * @param {Object} item current iteration item
  15. * @param {Object} params plugin params
  16. * @return {Boolean} if false, item will be filtered out
  17. *
  18. * @author Lev Solntsev
  19. */
  20. exports.fn = function(item) {
  21. if (
  22. item.isElem('rect') &&
  23. item.hasAttr('width') &&
  24. item.hasAttr('height') &&
  25. !item.hasAttr('rx') &&
  26. !item.hasAttr('ry')
  27. ) {
  28. var x = +(item.attr('x') || none).value,
  29. y = +(item.attr('y') || none).value,
  30. width = +item.attr('width').value,
  31. height = +item.attr('height').value;
  32. // Values like '100%' compute to NaN, thus running after
  33. // cleanupNumericValues when 'px' units has already been removed.
  34. // TODO: Calculate sizes from % and non-px units if possible.
  35. if (isNaN(x - y + width - height)) return;
  36. var pathData =
  37. 'M' + x + ' ' + y +
  38. 'H' + (x + width) +
  39. 'V' + (y + height) +
  40. 'H' + x +
  41. 'z';
  42. item.addAttr({
  43. name: 'd',
  44. value: pathData,
  45. prefix: '',
  46. local: 'd'
  47. });
  48. item.renameElem('path')
  49. .removeAttr(['x', 'y', 'width', 'height']);
  50. } else if (item.isElem('line')) {
  51. var x1 = +(item.attr('x1') || none).value,
  52. y1 = +(item.attr('y1') || none).value,
  53. x2 = +(item.attr('x2') || none).value,
  54. y2 = +(item.attr('y2') || none).value;
  55. if (isNaN(x1 - y1 + x2 - y2)) return;
  56. item.addAttr({
  57. name: 'd',
  58. value: 'M' + x1 + ' ' + y1 + 'L' + x2 + ' ' + y2,
  59. prefix: '',
  60. local: 'd'
  61. });
  62. item.renameElem('path')
  63. .removeAttr(['x1', 'y1', 'x2', 'y2']);
  64. } else if ((
  65. item.isElem('polyline') ||
  66. item.isElem('polygon')
  67. ) &&
  68. item.hasAttr('points')
  69. ) {
  70. var coords = (item.attr('points').value.match(regNumber) || []).map(Number);
  71. if (coords.length < 4) return false;
  72. item.addAttr({
  73. name: 'd',
  74. value: 'M' + coords.slice(0,2).join(' ') +
  75. 'L' + coords.slice(2).join(' ') +
  76. (item.isElem('polygon') ? 'z' : ''),
  77. prefix: '',
  78. local: 'd'
  79. });
  80. item.renameElem('path')
  81. .removeAttr('points');
  82. }
  83. };