Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crop and scale an image in SVG

Tags:

css

svg

I have an SVG element in my HTML which includes two external files, another SVG and a Bitmap.

<svg xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    width="1024" height="768">
        <image xlink:href="bitmap.png" />
        <image xlink:href="outline.svg" />
</svg>

My aim is that I can swap out the Bitmap for another (of any size) and have the Bitmap:

  1. Scale down to a specific width (maintaining ratio aspect)
  2. Crop off the bottom part of the bitmap

I've tried using clipPath, viewBox on sub SVG elements encapsulating the bitmap image, and I can't nail the problem. I'm trying to do this without JavaScript (if I can help it).

Any thoughts?

like image 534
bashaus Avatar asked Jul 27 '14 23:07

bashaus


Video Answer


1 Answers

Use the preserveAspectRatio attribute:

<svg xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    width="200" height="45">

    <image id="img" x="0" y="0"
        width="100%" height="100%"
        xlink:href="http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png"
        preserveAspectRatio="xMinYMin slice"/>
</svg>

Fiddle here

like image 83
Robby Cornelissen Avatar answered Sep 30 '22 19:09

Robby Cornelissen