Question

I have a div element which contains a svg graph (bunch of circles and edges), and I also set viewBox attribute on the svg element. The coordinates of the nodes and edges in the graph are hardcoded for a specified screen size (hence for a specified div size too) in px. With the desired div size, the graph loads nicely, and also scales up and down while the browser window is being resized.

However, my problem arises whenever the page is loaded under a different screen/div size, as the svg image remains the same for the specified div size before. This creates an image that is too large for smaller browser/screen sizes.

I set the following for the svg element:

<svg id="mygraph" preserveAspectRatio="xMidYMid meet">

and set its viewBox attribute using Javascript, immediately after the div element:

<script type="text/javascript">
    document.getElementById("mygraph").setAttribute("viewBox", "0 0 " + $("#graphdiv").width() + " " + $("#graphdiv").height());
</script>

This does not resolve the problem. So what else can I try?

Was it helpful?

Solution

The viewBox defines the coordinate system used inside the svg, it doesn't change the size of the svg. If you have a viewBox you only need to set the width and height of the svg (using CSS for example) and it will render to that size.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top