21

I have the following div inside <body>.

<div style="width:320px; height:480px;">
    <svg id="svg1"></svg>            
</div>

I want to fit a 640X480 svg inside this div. I have tried this:

var paper=Snap("#svg1");
Snap.load("somesvg.svg",function(f){ 
 paper.append(f);
 }); 
 paper.attr({ 
 width:320, height:480
 }) 

But the svg is cut off from the right size.

Phlume
  • 3,075
  • 2
  • 19
  • 38
naheed
  • 495
  • 1
  • 4
  • 9
  • 1
    Can you post a [jsFiddle](http://jsfiddle.net/)? Also tell us about Snap.load(), it looks like it is async? – Kyle Weller Jan 14 '14 at 05:02
  • 1
    http://jsfiddle.net/nahid/9zRR8/3/ – naheed Jan 14 '14 at 06:12
  • Here is an old post discussing the problems with loading an svg in a div with Snap. http://stackoverflow.com/questions/20110422/load-svg-into-a-specific-div-with-snap-svg – TimSPQR Jan 14 '14 at 07:32

2 Answers2

34

I was wondering about adjusting the viewBox for this, so something like...

<div style="width:320px; height:480px;">
    <svg id="svg1" width="100%" height="100%" viewBox="0 0 640 480" preserveAspectRatio="xMaxYMax"></svg>
</div>

jsfiddle http://jsfiddle.net/9zRR8/5/

The Demz
  • 7,066
  • 5
  • 39
  • 43
Ian
  • 13,724
  • 4
  • 52
  • 75
  • strange, but I get Error: Invalid value for attribute preserveAspectRatio="xMaxYmax" – john k Oct 24 '14 at 21:56
  • 1
    I think the case is wrong actually, so wonder if something has changed slightly with how the browsers uses case sensitivity and how its dealt with. https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/preserveAspectRatio has the valid values. – Ian Oct 25 '14 at 09:24
  • Doesn't seem to work? If I change div width/height the size of the image that appears is unaffected. – Andy Smith Oct 20 '16 at 18:10
  • It depends what you are changing, the title of the question is a little ambiguous (as the question specified an inner width/height). Are you trying to make it responsive, if so try setting the papers width/height to 100%, e.g http://jsfiddle.net/9zRR8/543/ if you mean something else it may be worth posting up a new question. – Ian Oct 20 '16 at 19:20
  • @johnktejik It is a long time since you asked the question but since no one answered. The value must be in camel-case, so the 'm' after 'Y' must be uppercase like 'xMaxYMax'. – Justin Jan 06 '17 at 13:21
6

The SVG will not scale because it does not have a viewBox defined. The viewBox tells the browser what the dimensions of the content are. Without it, there is no way to determine how much it should be scaled up or down to fit.

This is kind of a failing of svg-edit. It really should be adding one, ideally.

What you could try is loading the SVG into Inkscape or another SVG editor which should add a viewBox. Alternatively, you could add one manually, as per Ian's answer.

Paul LeBeau
  • 97,474
  • 9
  • 154
  • 181