6

So I just recently got into SVG and I'm having a couple problems related to the fact that instead of being resized to fit the container, my SVG image gets cropped out instead.

HTML:

<!DOCTYPE html>
<html>
  <head>
    <title>Eye</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="js/snap.svg.js"></script>
    <script src="js/eye.js"></script>
  </head>
  <body>
    <svg id="svg"></svg>
  </body>
</html>

JS:

window.onload = function() {
   var s = Snap("#svg");

   var circle = s.circle(90,120,80);
   var square = s.rect(210,40,160,160);
   var ellipse = s.ellipse(460,120,50,80);
}

JSFiddle

Now, with that CSS code it surely isn't cropped anymore since the user agent stylesheet on Google Chrome contains "overflow:hidden" regarding SVGs. But is that really the right way to resolve the matter? Also, why does it get cropped instead of scaled? Should I "draw" my svgs using percentages instead of pixels?

CoderPi
  • 12,985
  • 4
  • 34
  • 62
Hissvard
  • 488
  • 7
  • 24

2 Answers2

4

You currently have not set an intrinsic dimension of the SVG. You should add a viewBox attribute to specify the part of the SVG, you actually want to show. (The "complete" SVG plain is almost endless)

Additionally you can set the extrinsic dimension of the SVG container. That is the size of the box, in which the SVG will appear.

Together it could look like this:

<svg id="svg" 
   version="1.1" xmlns="http://www.w3.org/2000/svg"
   viewBox="0 0 550 300"></svg>

 

#svg {
  overflow: visible;
  width: 100%;
}

Fiddle

Sirko
  • 72,589
  • 19
  • 149
  • 183
1

The SVG has a default width and height (300px x 150px). If you have Elements bigger than the SVG-frame they wont be visible. Set the SVG's width and height to your convenience:

For example: https://jsfiddle.net/4yjtbun9/

<svg id="svg" width="520" height="210" ...
CoderPi
  • 12,985
  • 4
  • 34
  • 62
  • I tried so but it only changes the dimension of the container, whatever's in it remains the same without setting the viewBox like Sirko said. Thanks anyway for the answer! – Hissvard Jan 28 '16 at 13:17
  • I think the problem here is that you are resizing the container to fit the shapes, rather than making svg resized to fit the container, which one would do with the viewBox. – Ian Jan 28 '16 at 16:29