JS: access unrounded width of user loaded svg

I am programming a JS applet. The user chooses an SVG file to load. The SVG file has a widht and height attribute and they are not necessarily integers. If I put the file content into an img element these values are rounded to integers. I need to access the unrounded values.

  • load the SVG yourself, parse it (it’s XML), extract the values you need.

    – 

  • @RobertLongson Is there a JS command to parse?

    – 

  • 1

    @RobertLongson found it: new DOMParser().parseFromString(…)

    – 

  • Why load it in an IMG and not in a shadowDOM; where you can then do .shadowRoot.querySelector("svg").getAttribute("width")

    – 

Robert Longson suggested a way, here is my implementation but it might not be the best.

let svg = new DOMParser().parseFromString(fileContent,"image/svg+xml");
let width = svg.rootElement.width.baseVal.value;
let height = svg.rootElement.height.baseVal.value;

Leave a Comment