html - 获取像 SVG 动画路径一样的 CSS 动画

标签 html css animation svg

是否可以仅使用 CSS 获得我使用 SVG 路径创建的以下动画?

CSS

html, body {
    margin: 0;
    height: 100%;
}
svg {
    display: block;
    position: absolute;
    width: 90%;
    height: 90%;
    top: 5%;
    left: 5%;
}
.path {
    animation: dash 10s linear infinite;
}
@-webkit-keyframes dash {
    to {
        stroke-dashoffset: 0;
    }
}

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" 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" vector-effect="non-scaling-stroke" />
</svg>

这是 fiddle

最佳答案

我很确定 SVG 是实现此目的的方式,我认为将 css 用于像这样的动画会比使用 SVG 有更多的陷阱。

尽管如此,您是否能够使用 CSS 实现类似的动画,但主要的缺点是这需要蛇盘旋的元素具有固定的纵横比。否则动画的速度会有所不同。另一个主要缺点是它要求周围元素的背景颜色是静态的。

此解决方案使用沿外边缘移动的正方形,给人以移动边界的印象。

.div-wrapper {
  padding: 20px;
  width: 150px;
  height: 150px;
  margin: 50px;
}
.snake {
  border: 2px solid lime;
  display: inline-block;
  position: relative;
  padding: 1vw;
  height: 100%;
  width: 100%;
}
.snake:before {
  width: 8vw;
  height: 8vw;
  content: '';
  position: absolute;
  display: block;
  background-color: white;
  animation: around linear 10s infinite;
  transform: rotate(45deg);
  z-index: 1
}
.snake.red:before {
  background-color: red;
}
@keyframes around {
  0% {
    top: calc(-4vw - 1px);
    left: calc(100% - 4vw + 1px);
  }
  25% {
    top: calc(100% - 4vw + 1px);
    left: calc(100% - 4vw + 1px);
  }
  50% {
    top: calc(100% - 4vw + 1px);
    left: calc(-4vw - 1px);
  }
  75% {
    top: calc(-4vw - 1px);
    left: calc(-4vw - 1px);
  }
  100% {
    top: calc(-4vw - 1px);
    left: calc(100% - 4vw + 1px);
  }
}
<div class="div-wrapper">
  <div class="snake">
    <div class="content">
    </div>
  </div>
</div>

<div class="div-wrapper">
  <div class="snake red">
    <div class="content">
    </div>
  </div>
</div>

老实说,我会坚持使用 SVG。

关于html - 获取像 SVG 动画路径一样的 CSS 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32628033/

相关文章:

css - 在居中的 div 旁边放置一个 div 侧边栏

php - DOMDocument::loadXML 与 HTML 实体

twitter-bootstrap - 如何使用 Bootstrap 4 在 div 中居中对齐图像?

html - 如何在 "auto"属性中同时使用 "contain"和 "background-size"这两个值?

html - 具有固定和可变宽度的复杂布局,使用可见性的选项卡等

javascript - 如何使用 html 将 Google map url 嵌入网站?

jquery - 为什么我用 $ ('#leftquota' ).val() 什么也得不到?

ios - UISegmentedControl 的动画栏按钮没有移动?

qt - 如何获取Qt widget的位置?

css - 使用 CSS3 的动画立方体(只有两个面)效果