Я надеюсь, что все ваши элементы svg построены одинаково.
В этом случае все рисунки внутри элемента svg заключены в группу <g>
. Это очень полезно, потому что вы можете получить ограничивающую рамку группы и использовать ее для построения значения атрибута viewBox
// get the svg element. In this case I am using querySelector but if you have several svg elements you may need to use `querySelectorAll` and then loop
let svg = document.querySelector("svg");
// remove the attributes width and height of the svg element because I want to avoid a different aspect ratio
svg.removeAttribute("width");
svg.removeAttribute("height");
// get the wrapping group. This is assuming that there is a group wrapping everighing in the svg element
let g = document.querySelector("g");
// remove the transform attribute that is translating the group. This is assuming that the transform is not rotating or skewing the group
g.removeAttribute("transform");
// get the position (x,y) and the size (width,height) of the bounding box of the group
let bb = g.getBBox();
// use the bounding box of the group to build the viewBox attribute of the svg element
svg.setAttributeNS(null, `viewBox`, `${bb.x} ${bb.y} ${bb.width} ${bb.height}`)