5

OBJECTIVE I have an svg that I would like to scale with the browser window.

Parameters

a) It is to keep it's proportions (here a square)

b)to fit the bowser/device window to 80%

c)But to a maximum of 800px.

d) I'm not interested in javascript solutions

Code so far (although I've tried many combinations) SVG root element, the preserve aspect ratio has been left to default

svg viewBox="0 0 800 800"

and with regards to html & viewport HTML (embedding with object)

object type="image/svg+xml"  id="svgobject" data="question0final.svg"

CSS, things tried, amongst others...

#svgobject{ position:absolute; top:0; left:0; height:100%; width:100%}

(From; How to scale SVG image to fill browser window?)

#svgobject{width:80%; max-width:800px; margin-right: auto; margin-left: auto;}

I've read a number of good resources, but I can't work out my errors

FYI here are some of the better links I've found on SVG positiioning

Do I use <img>, <object>, or <embed> for SVG files?

http://tavmjong.free.fr/INKSCAPE/MANUAL/html/Web-SVG-Positioning.html

http://www.alistapart.com/articles/using-svg-for-flexible-scalable-and-fun-backgrounds-part-ii

http://www.w3.org/TR/SVG/coords.html

http://coding.smashingmagazine.com/2012/01/16/resolution-independence-with-svg/

https://developer.mozilla.org/en/CSS/Scaling_of_SVG_backgrounds

(I find that SVGs as CSS backgound seem to pixelate)

Community
  • 1
  • 1
EnglishAdam
  • 1,380
  • 1
  • 19
  • 42
  • Resolved by itself (so it was something I was doing...) – EnglishAdam Mar 15 '12 at 15:21
  • 1
    The procedure I was using was fine, settled on #svgobject{width:80%; max-width:800px; margin-right: auto; margin-left: auto;} for my css. Apologies. At least I put up some good links! – EnglishAdam Mar 15 '12 at 15:23
  • This isn't working for me. It seems that the SVG element is respecting the width/max-width attributes, but the elements inside the SVG are just being cut off, rather than scaling up/down. – Jo Sprague Jun 13 '12 at 14:10
  • @josiah sprague Check your viewBox is big enough for the image. – EnglishAdam Jun 13 '12 at 19:36

1 Answers1

3

Scaling the object won't work. You have to get reference of the svg element.

var svgs1 = $('object[id ^="svgobject"]');                            
var svgDoc = document.getElementById(svgs1[0].id).contentDocument;
var svgRoot = svgDoc.documentElement;

Now you have svg element in the variable svgRoot. So, calculate your scale value like this:

var desiredWidth=500; //this is your desired width 
var scaleVal=desiredWidth/$(window).width(); //now you have scale value

$(svgRoot).css("-webkit-transform","scale("+scaleVal+")");

Like this, you can scale the svg component with respect to the screen size.

Sujan Shrestha
  • 191
  • 1
  • 4