让SVG路径占据整个屏幕的宽度和高度

7
我有一个内联SVG路径,它通过动画来模拟贪吃蛇游戏。现在我的问题是如何使这个路径占据整个屏幕的宽度和高度,并在屏幕变小或变大时自适应。
HTML
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 659 522" enable-background="new 0 0 659 522" xml:space="preserve">
    <path class="path" width="100%" height="100%" fill="none" stroke="#00ff00" stroke-width="5" stroke-miterlimit="10" d="M656.5,2.5v517H2.5V2.5H656.5z"
    stroke-dasharray="2042 300"
    stroke-dashoffset="2342" />
</svg>

CSS

.path {
    animation: dash 10s linear infinite;
}

@-webkit-keyframes dash {
    to {
        stroke-dashoffset: 0;
    }
}

这里有一个我现在所拥有的代码的示例。

http://jsfiddle.net/c3ar6e5o/

1个回答

11

你需要在SVG代码中使用preserveAspectRatio="none"来告诉SVG不要保持其宽高比,然后就只需使用CSS。

JSfiddle演示

html,
body {
  margin: 0;
  height: 100%;
}
svg {
  display: block;
}
.path {
  animation: dash 10s linear infinite;
}
@-webkit-keyframes dash {
  to {
    stroke-dashoffset: 0;
  }
}
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 659 522" enable-background="new 0 0 659 522" xml:space="preserve" preserveAspectRatio="none">
  <path class="path" width="100%" height="100%" fill="none" stroke="#00ff00" stroke-width="5" stroke-miterlimit="10" d="M656.5,2.5v517H2.5V2.5H656.5z" stroke-dasharray="2042 300" stroke-dashoffset="2342" />
</svg>


谢谢,这似乎有所帮助,唯一的问题是笔画似乎被拉伸了。 - AC3
1
在代码片段中是可以的...但请检查JSfiddle(现已更正链接) - Paulie_D
在这个fiddle中,对我来说它似乎也被拉伸了。 - AC3
在我的 Chrome 浏览器中看起来没问题。 - Paulie_D
有没有解决方法可以不拉伸笔画? - Jacob Raccuia

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接