Search code examples
htmlsvgcropscaling

SVG viewBox scaling and cropping


How can I output a certain place from SVG and zoom it?

E. g., I have the following HTML with SVG (the copy of the code and its render are located at http://jsfiddle.net/5e0pas9m/ ).

<div style="border: 1px solid black;">1
<svg width="100" height="100" viewBox="0 0 200 200" style="border: 1px solid red; transform: scale(1);" preserveAspectRatio="xMidYMid none">
  <rect width="100%" height="100%" style="fill:rgb(200,200,255);stroke-width:4;stroke:rgb(100,100,255)" />
  <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
  <circle cx="150" cy="150" r="40" stroke="red" stroke-width="4" fill="yellow" />
</svg>
</div>

<div style="border: 1px solid black;">2
<svg width="100" height="100" viewBox="0 0 100 100" style="border: 1px solid red; transform: scale(1);" preserveAspectRatio="xMidYMid none">
  <rect width="100%" height="100%" style="fill:rgb(200,200,255);stroke-width:4;stroke:rgb(100,100,255)" />
  <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
  <circle cx="150" cy="150" r="40" stroke="red" stroke-width="4" fill="yellow" />
</svg>
</div>

<div style="border: 1px solid black;">3
<svg width="100" height="100" viewBox="100 100 200 200" style="border: 1px solid red; transform: scale(1);" preserveAspectRatio="xMidYMid none">
  <rect width="100%" height="100%" style="fill:rgb(200,200,255);stroke-width:4;stroke:rgb(100,100,255)" />
  <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
  <circle cx="150" cy="150" r="40" stroke="red" stroke-width="4" fill="yellow" />
</svg>
</div>

<div style="border: 1px solid black;">4
<svg width="100" height="100" style="border: 1px solid red; transform: scale(1);" preserveAspectRatio="xMidYMid none">
  <g transform="scale(1), translate(-100 -100)">
  <rect width="100%" height="100%" style="fill:rgb(200,200,255);stroke-width:4;stroke:rgb(100,100,255)" />
  <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
  <circle cx="150" cy="150" r="40" stroke="red" stroke-width="4" fill="yellow" />
  </g>
</svg>
</div>

The div-1 shows my full image.

If I like to show only the top-left corner in the same window I make viewBox="0 0 100 100" (div-2) and it gives approximately what I want: the part of the image fitted to the window.

But when I do the same thing with the right-bottom corner (div-3 represents viewBox="100 100 200 200") the image is only translated but is not fitted/zoomed/scaled.

The div-4 nealry shows an example of my target achieved via another technique.


Solution

  • The third and fourth arguments of the viewBox are width and height, not maxX and maxY. So the viewBox for your bottom-right example should be "100 100 100 100".