微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

HTML – 你能为svg“background-image”制作动画吗?

我想把一个svg-image中心和垂直中心响应我的窗口.所以我决定将图像整合到div背景中.现在,当我想将stroke-dasharray和动画与stroke-dashoffset添加到我的svg时它不起作用.

这个posibble是否可以为svg背景图像设置动画?

svg-image只包含许多行.
这里是我的svg文件(还有更多的行只有不同的x和y值):

<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 1920 1200"  xml:space="preserve">
<g id="Layer_1">

<line class="path" stroke-linecap="round" fill="none" stroke="#FFFFFF" stroke-width="3" stroke-miterlimit="10" x1="960" y1="600" x2="2346.139" y2="-42.064"/>

</g>
</svg>

在这里我的Html和Css文件

html,body {
  padding: 0;
  margin: 0;
  height: 100%;
  width: 100%;
  background-color: red;
}

.Container {
  position: relative;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
  width: 100%;
  height: 100%;
  background-image: url(Space.svg);
  background-size: cover;
  background-position: center;
}


.path {
  stroke-dasharray: 20;
}
<body>
    <div class="Container">
    </div>
  </body>

解决方法

你可以动画…但只使用CSS,只在支持它的浏览器中 – 你去IE和其他一些浏览器(编辑,截至2018年Edge现在支持这个).
.svg {
  background-image: url("data:image/svg+xml;charset=UTF-8,%3Csvg width='300' height='70' viewBox='0 0 300 70' xmlns='http://www.w3.org/2000/svg'%3E%3Cstyle type='text/css'%3E %23a%7Banimation:x .5s ease alternate 14%7D%40keyframes x%7Bfrom%7Bfill:%23c2c2c2%7Dto%7Bfill:%23fff%7D%7D%3C/style%3E%3Crect id='a' x='14' y='23' width='28' height='28' fill='%23c2c2c2' /%3E%3Crect x='52' y='33' width='100' height='11' fill='%23c2c2c2' /%3E%3C/svg%3E");
  background-repeat: no-repeat;
  min-height: 200px;
}
<div class="svg">Look at my background</div>

请注意上面使用的实际编码SVG(我在生产中用于缓慢加载google recaptcha iframe的内联UX改进)是:

<svg width="300" height="70" viewBox="0 0 300 70" xmlns="http://www.w3.org/2000/svg">
    <style type="text/css">
        #a { animation: x .5s ease alternate 14; }

        @keyframes x {
           from { fill: #000; }
             to { fill: #fff; }
        }
    </style>
    <rect id="a" x="14" y="23" width="28" height="28" fill="#000" />
    <rect x="52" y="33" width="100" height="11" fill="#000" />
</svg>

原文地址:https://www.jb51.cc/html/227830.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐