Question

I have a huge svg 3200*1800. I only want to show a part of that image something like 400*1000, ensuring that the width is the dominant attribute and having a scroll bar for the height but when I set viewbox it increase the width to display the added height.

   viewBox="900 550 400 1000"

Is their a way to stop this happening?

Was it helpful?

Solution

I worked it out you need to increase the height relative to the viewbox for example I ended up with something like this:

width="1400"
height="4000"
viewBox="966 555 350 1000"

Compared to what I used to have:

width="350"
height="1000"
viewBox="966 555 350 1000"

OTHER TIPS

You just set 'preserveAspectRatio' to "none" along with your 'viewBox' attribute, then your problem is solved.

This answer builds on Shane's answer (which does not cater to variable window sizes)...

To have width-dominant overflows:

  1. Let the 'viewbox' define the portion of the graphic to display (any known aspect ratio)
  2. Let the svg element have default width and height (100%)
  3. With javascript, dynamically set the height of the svg element every time the window resizes

The code below works for my learning project and is NOT production code.

In the head element:

<script type="application/javascript">
    var svgRatio = ${viewboxRatio}; // ratio must be known

    // From http://stackoverflow.com/a/13651455
    if(window.attachEvent) {
        window.attachEvent('onresize', resizeSvg);
    }
    else if(window.addEventListener) {
        window.addEventListener('resize', resizeSvg, true);
    }
    else {
        //The browser does not support Javascript event binding
    }

    function resizeSvg() {
        var height = window.innerWidth * svgRatio;
        var svg  = document.getElementsByTagName('svg')[0];
        svg.setAttribute("height", height.toString());
    }
</script>

At the end of the body:

<script type="application/javascript">
    resizeSvg();
</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top