Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2025
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const imageDoc = parser.parseFromString(imageSvgContent, "image/svg+xml");
  2. const imageRoot = imageDoc.documentElement;
  3.  
  4. let scaleX = 1;
  5. let scaleY = 1;
  6. let origWidth = 0;
  7. let origHeight = 0;
  8. let viewBoxX = 0;
  9. let viewBoxY = 0;
  10.  
  11. if (img.width && img.height) {
  12.     const origWidthAttr = imageRoot.getAttribute("width");
  13.     const origHeightAttr = imageRoot.getAttribute("height");
  14.     if (origWidthAttr && origHeightAttr) {
  15.         origWidth = parseFloat(origWidthAttr);
  16.         origHeight = parseFloat(origHeightAttr);
  17.     }
  18.     if (!origWidth || !origHeight) {
  19.         const viewBox = imageRoot.getAttribute("viewBox");
  20.         if (viewBox) {
  21.             const parts = viewBox.split(/\s+|,/);
  22.             if (parts.length === 4) {
  23.                 viewBoxX = parseFloat(parts[0]);
  24.                 viewBoxY = parseFloat(parts[1]);
  25.                 origWidth = parseFloat(parts[2]);
  26.                 origHeight = parseFloat(parts[3]);
  27.             }
  28.         }
  29.     }
  30.     if (origWidth && origHeight) {
  31.         scaleX = img.width / origWidth;
  32.         scaleY = img.height / origHeight;
  33.     }
  34.  
  35.     const translateX = (img.x ?? 0) - viewBoxX * scaleX;
  36.     const translateY = (img.y ?? 0) - viewBoxY * scaleY;
  37.     console.log(viewBoxX, viewBoxY)
  38.  
  39.     const g = doc.createElementNS("http://www.w3.org/2000/svg", "g");
  40.     g.setAttribute(
  41.         "transform",
  42.         `translate(${translateX}, ${translateY}) scale(${scaleX}, ${scaleY})`
  43.     );
  44.  
  45.     Array.from(imageRoot.childNodes).forEach((child) => {
  46.         g.appendChild(doc.importNode(child, true));
  47.     });
  48.  
  49.     additionalGroup.appendChild(g);
  50. }
  51.  
  52. doc.documentElement.appendChild(additionalGroup);
  53.  
  54. ...
  55.  
  56.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement