Stretch <svg> inside <embed> to window size

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

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 does not work ... What am I doing wrong?

+6
source share
2 answers

All browsers should be able to handle this simply:

  • add viewBox to svg element (s17.svg in your example) without using script if possible
  • remove the width and height attributes for the svg element, if specified
  • add the preserveAspectRatio="none" attribute to the svg element so that it stretches even if the css-viewport aspect ratio does not match the viewBox format.
  • set the width / height of the object embed / iframe / object to whatever you want and svg will automatically stretch to fit

If you do not want to stretch, you can also do preserveAspectRatio="xMidYMid slice" (fill the entire viewport, cut off the parts if necessary) or preserveAspectRatio="xMidYMid meet" (this is the default value, center svg in the viewport and maintain aspect ratio )

+9
source

All browsers support SVG in completely different ways. I believe that the best thing is to use the object tag instead of embed , and you still have to hack a bit to make it look right in every browser. This link and this link contain some useful information to get it to work with multiple browsers.

0
source

Source: https://habr.com/ru/post/889159/


All Articles