Farid Stark
Farid Stark

Reputation: 39

Problems with keeping aspect-ratio of background image inside fluid SVG

I have an SVG with full page width/height, so the SVG and the polygons inside the SVG change shape and size according to the window, which I achieved by setting preserveAspectRatio on the SVG element to "none". The polygons have a background image, which are supposed to keep their aspect ratio, because I set preserveAspectRatio to "xMinYMin slice". But sadly the preserveAspectRatio on the SVG element seems to be causing a conflict and now the background image changes aspect ratio when I change window size. What I want is basically the SVG equivalent of "background-size: cover".

<!DOCTYPE html>
<html>
<head>
<title>SVG Test</title>
<style type="text/css">
html, body {
    height: 100%;
    margin: 0px;
    padding: 0;
}
svg {
    float: left;
}
</style>
</head>
<body>
<svg version="1.1" id="gallery_overview" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100%" height="100%" x="0px" y="0px" viewBox="0 0 400 400" enable-background="new 0 0 400 400" preserveAspectRatio="none">
    <defs>
        <pattern id='image1' width="1" height="1" viewBox="0 0 100 100" preserveAspectRatio="none">
            <image xlink:href='http://upload.wikimedia.org/wikipedia/commons/d/d3/Statue_of_Liberty%2C_NY.jpg' width="100" height="100" preserveAspectRatio="xMinYMin slice"></image>
        </pattern>
        <pattern id='image2' width="1" height="1" viewBox="0 0 100 100" preserveAspectRatio="none">
            <image xlink:href='http://upload.wikimedia.org/wikipedia/commons/9/94/Top_of_Rock_Cropped.jpg' width="100" height="100" preserveAspectRatio="xMinYMin slice"></image>
        </pattern>
        <pattern id='image3' width="1" height="1" viewBox="0 0 100 100" preserveAspectRatio="none">
            <image xlink:href='http://upload.wikimedia.org/wikipedia/commons/thumb/f/f5/Chinatown_manhattan_2009.JPG/1920px-Chinatown_manhattan_2009.JPG' width="100" height="100" preserveAspectRatio="xMinYMin slice"></image>
        </pattern>
    </defs>
    <polygon fill="url(#image1)" points="0 0, 400 0, 200,200"/>
    <polygon fill="url(#image2)" points="0 0, 400 400, 0 400"/>
    <polygon fill="url(#image3)" points="400 0, 400 400, 200 200"/>
</svg>
</body>
</html>

Click here for demo

Upvotes: 3

Views: 584

Answers (1)

Paul LeBeau
Paul LeBeau

Reputation: 101820

With preserveAspectRatio set to "none", you are basically telling the browser to stretch a 400x400 image to fill the screen. There is no conflict or error there. It is doing exactly what you tell it.

If your SVG is being stretched, all the contents will be affected. There is no way around that - other than using JS to adjust the SVG contents.

You could use an alternative like CSS masks. But those are not supported by IE.

Upvotes: 1

Related Questions