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

前端之家收集整理的这篇文章主要介绍了HTML – 你能为svg“background-image”制作动画吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想把一个svg-image中心和垂直中心响应我的窗口.所以我决定将图像整合到div背景中.现在,当我想将stroke-dasharray和动画与stroke-dashoffset添加到我的svg时它不起作用.

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

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

  1. <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">
  2. <g id="Layer_1">
  3.  
  4. <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"/>
  5.  
  6. </g>
  7. </svg>

在这里我的Html和Css文件

  1. html,body {
  2. padding: 0;
  3. margin: 0;
  4. height: 100%;
  5. width: 100%;
  6. background-color: red;
  7. }
  8.  
  9. .Container {
  10. position: relative;
  11. left: 50%;
  12. top: 50%;
  13. transform: translate(-50%,-50%);
  14. width: 100%;
  15. height: 100%;
  16. background-image: url(Space.svg);
  17. background-size: cover;
  18. background-position: center;
  19. }
  20.  
  21.  
  22. .path {
  23. stroke-dasharray: 20;
  24. }
  1. <body>
  2. <div class="Container">
  3. </div>
  4. </body>

解决方法

你可以动画…但只使用CSS,只在支持它的浏览器中 – 你去IE和其他一些浏览器(编辑,截至2018年Edge现在支持这个).
  1. .svg {
  2. 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");
  3. background-repeat: no-repeat;
  4. min-height: 200px;
  5. }
  1. <div class="svg">Look at my background</div>

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

  1. <svg width="300" height="70" viewBox="0 0 300 70" xmlns="http://www.w3.org/2000/svg">
  2. <style type="text/css">
  3. #a { animation: x .5s ease alternate 14; }
  4.  
  5. @keyframes x {
  6. from { fill: #000; }
  7. to { fill: #fff; }
  8. }
  9. </style>
  10. <rect id="a" x="14" y="23" width="28" height="28" fill="#000" />
  11. <rect x="52" y="33" width="100" height="11" fill="#000" />
  12. </svg>

猜你在找的HTML相关文章