6

I am trying to stretch an svg document inside an DOM in order to fit the window size.

like so:

<div id="y">
    <div id="button"> click to zoom</div>
    <embed id="x" src="s17.svg" >
    <script>
        var btn= document.getElementById("button");
        btn.addEventListener('click',function(){
        var z= document.getElementsByTagName("embed")[0];
        var y = z.getSVGDocument();
        y.lastChild.setAttribute("viewBox","0 0 "+window.innerWidth+" "+window.innerHeight);
                                               },false);

    </script>
</div>

css:

#x{
    height:100%;
    width:100%;
    overflow:hidden;
}
#y{
    position:absolute;
    top:0;
    bottom:0;
    left:0;
    right:0;
    overflow:hidden;
}

This isn't working... What am I doing wrong?

fogy
  • 61
  • 1
  • 3
  • Which browser are you using? Unfortunately, IE9, Firefox, Chrome, and Opera all handle this scenario in very different ways. – Dan May 26 '11 at 22:54
  • Well I was hoping that it would work on all browsers... Should I just manually go through each element in the SVG and scale them? – fogy May 26 '11 at 22:57

2 Answers2

10

All browsers should be able to handle this just fine:

  • add a viewBox to the svg element (s17.svg in your example) without using script if possible
  • remove the width and height attributes on the svg element if they are specified
  • add an attribute preserveAspectRatio="none" to the svg element to make it stretch even if the css-viewport aspect ratio doesn't match the viewBox aspect ratio.
  • set the width/height of the embed/iframe/object to whatever you want and the svg will automatically stretch to fit

If you don't want stretching then you can also do preserveAspectRatio="xMidYMid slice" (fill whole viewport, slicing away parts if necessary) or preserveAspectRatio="xMidYMid meet" (this is the default, center the svg in the viewport and maintain the aspect ratio).

Erik Dahlström
  • 59,452
  • 12
  • 120
  • 139
0

All browsers handle SVG support completely differently. I think your best bet is to use an object tag instead of embed, and you still have to do some hacking to get it to look right on each browser. This link and this link have some useful information for getting it to work cross-browser.

Dan
  • 2,157
  • 20
  • 24