svg2marker.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { __read } from "tslib";
  2. /**
  3. * from: https://github.com/zqlu/svg2marker
  4. * translate svg string to G.Marker
  5. */
  6. import svgPathParser from 'svg-path-parser';
  7. /**
  8. * Return function to register a Marker Symbol for give SVG Path
  9. *
  10. * @param svgPath SVG Path string
  11. * @param viewBoxWidth SVG view box width, default to 1024
  12. * @param viewBoxHeight SVG view box height, default to 1024
  13. */
  14. export function path2marker(svgPath, viewBoxWidth, viewBoxHeight) {
  15. if (viewBoxWidth === void 0) { viewBoxWidth = 1024; }
  16. if (viewBoxHeight === void 0) { viewBoxHeight = 1014; }
  17. return function (x, y, r) {
  18. // @ts-ignore
  19. var paths = svgPathParser(svgPath);
  20. return paths.map(function (path) {
  21. var arr = [];
  22. arr.push(path.relative === true ? path.code.toLowerCase() : path.code.toUpperCase());
  23. var pairs = [
  24. [path.x1, path.y1],
  25. [path.x2, path.y2],
  26. [path.x, path.y],
  27. ];
  28. pairs.forEach(function (pair) {
  29. var _a = __read(pair, 2), px = _a[0], py = _a[1];
  30. if (px !== undefined) {
  31. arr.push(path.relative === true ? (px / viewBoxWidth) * 2 * r : x - r + r * 2 * (px / viewBoxWidth));
  32. }
  33. if (py !== undefined) {
  34. arr.push(path.relative === true ? (py / viewBoxHeight) * 2 * r : y - r + r * 2 * (py / viewBoxHeight));
  35. }
  36. });
  37. return arr;
  38. });
  39. };
  40. }
  41. /**
  42. * Return function to register a Marker symbol for give svg file
  43. *
  44. * @param icon SVG file content
  45. */
  46. export function svg2marker(icon) {
  47. var pathMatch = /<path\s+d="(.*?)"/i.exec(icon);
  48. var viewBoxMatch = /viewBox="\d+\s+\d+\s+(\d+)\s+(\d+)"/i.exec(icon);
  49. if (pathMatch === null || pathMatch.length < 2) {
  50. return function () { return []; };
  51. }
  52. var width = 1024;
  53. var height = 1024;
  54. if (viewBoxMatch !== null && viewBoxMatch.length >= 3) {
  55. if (!Number.isNaN(parseInt(viewBoxMatch[1], 10))) {
  56. width = parseInt(viewBoxMatch[1], 10);
  57. }
  58. if (!Number.isNaN(parseInt(viewBoxMatch[2], 10))) {
  59. height = parseInt(viewBoxMatch[2], 10);
  60. }
  61. }
  62. return path2marker(pathMatch[1], width, height);
  63. }
  64. //# sourceMappingURL=svg2marker.js.map