Inspired by Thomas's answer, here's how I did it:
if (true) { let svg = document.getElementById("bleh"); let bb = svg.getBBox(); svg.setAttribute("width", bb.width); svg.setAttribute("height", bb.height); svg.setAttribute("transform", "translate(-" + bb.width / 2 + ",-" + bb.height / 2 + ") \ scale(" + 600 / bb.width + "," + 250 / bb.height + ") \ translate(" + bb.width / 2 + "," + bb.height / 2 + ")"); }
<!DOCTYPE html> <html> <head> </head> <body> <div style="width: 600px; height: 250px; border: 1px solid blue;"> <svg id="bleh"> <path d="M0 0 T100 400 T500 500 T800 200 T0 0" fill="purple" opacity="0.8" /> <path d="M0 0 L100 400 L500 500 L800 200 L0 0" fill="none" stroke="black" stroke-width="2" /> </svg> </div> </body> </html>
Purpose: try to automatically fit the entire SVG-graph in the size of div 600 * 250.
Essentially, I got the width and height of the SVG after it was formed, translated it 50% left and up, scaled according to the ratio of the width and the difference between 600 * 250 division and the size of the SVG graph, and then translate it back to 50% to the right and down. That way, he stayed in the center while I scaled it. (It seems that such percentages do not like real interest ...)
Andrew
source share