首页 文章

保持流体SVG内背景图像宽高比的问题

提问于
浏览
3

我有一个具有整页宽度/高度的SVG,因此SVG和SVG内的多边形根据窗口改变形状和大小,我通过将SVG元素上的preserveAspectRatio设置为“none”来实现 . 多边形有一个背景图像,它应该保持它们的宽高比,因为我将preserveAspectRatio设置为“xMinYMin slice” . 但遗憾的是SVG元素上的preserveAspectRatio似乎引起了冲突,现在当我改变窗口大小时,背景图像会改变宽高比 . 我想要的基本上是SVG相当于“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

1 回答

  • 1

    preserveAspectRatio 设置为 "none" ,您基本上是告诉浏览器拉伸400x400图像以填充屏幕 . 那里没有冲突或错误 . 这正是你所说的 .

    如果您的SVG被拉伸,所有内容都将受到影响 . 没有办法解决这个问题 - 除了使用JS来调整SVG内容 .

    您可以使用CSS掩码之类的替代方法 . 但IE不支持这些 .

相关问题