Problems keeping the aspect ratio of the background image inside the SVG fluid

I have an SVG with full page width / height, so the SVG and polygons inside the SVG change shape and size to fit the window, which I achieved by setting the SVG element's preserveAspectRatio to "none". The polygons have a background image that should preserve their aspect ratio because I set the preserveAspectRatio to "xMinYMin slice". Unfortunately, storing the AspectRatio in the SVG element causes a conflict, and now the background image resizes when the window is resized. I want basically the SVG equivalent "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 a demo

+3


source to share


1 answer


If preserveAspectRatio

set to "none"

, you are basically telling the browser to stretch the 400x400 image to fill the screen. There are no conflicts or mistakes. It does exactly what you say.

If your SVG is stretched, all content will be affected. There is no way around this - other than using JS to customize the SVG content.



You can use an alternative like CSS masks. But IE is not supported.

+1


source







All Articles