跳至主要內容

线条图标描边动画

望间代码HTML&CSS图标动画大约 1 分钟

CSS 世界之线条图标描边动画

无意中在网上看见一个图标描边动画效果,研究一下,写下博客方便以后回顾

效果展示

<div class="container">
  <svg
    class="icon"
    viewBox="0 0 1024 1024"
    version="1.1"
    xmlns="http://www.w3.org/2000/svg"
    p-id="6401"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    width="200"
    height="200"
  >
    <path
      class="icon-path"
      d="M512 832c-179.2 0-320-140.8-320-320s140.8-320 320-320 320 140.8 320 320S691.2 832 512 832M512 896c211.2 0 384-172.8 384-384s-172.8-384-384-384S128 300.8 128 512 300.8 896 512 896L512 896zM800 512c0-160-128-288-288-288l0 576C672 800 800 672 800 512zM480 608 243.2 608C249.6 620.8 256 640 262.4 652.8l217.6 0L480 608zM480 416 480 371.2 262.4 371.2C256 384 249.6 403.2 243.2 416L480 416zM480 300.8 480 256 384 256C358.4 268.8 339.2 281.6 320 300.8L480 300.8zM224 537.6l256 0L480 492.8l-256 0c0 6.4 0 12.8 0 19.2S224 524.8 224 537.6zM480 723.2 320 723.2c19.2 19.2 38.4 32 64 44.8l96 0L480 723.2z"
      fill="#272636"
      p-id="6402"
    ></path>
  </svg>
</div>
.container {
  position: relative;
  width: 100%;
  display: flex;
  justify-content: center;
}

@keyframes stroke {
  0% {
    /* 第一个值为线条长度,第二个值为线条间隔空隙 */
    stroke-dasharray: 0, 400px;
  }
  100% {
    stroke-dasharray: 400px, 0;
  }
}

.container .icon-path {
  /* 填充颜色 */
  fill: none;
  /* 轮廓颜色 */
  stroke: gray;
  /* 轮廓宽度 */
  stroke-width: 4;
  /* 轮廓两端形状 */
  stroke-linecap: round;
}

.container .icon:hover {
  animation: stroke 1s;
}

实现思路

线条图标描边效果主要使用的技术是 SVG 的轮廓描边功能,所以图标需要是 SVG 图标,字体图标是不行的

  1. 将 SVG 图标的代码粘贴在 HTML 代码中
  2. 为 SVG 代码中的 path 元素设置 class
  3. 使用 CSS 代码将图标以线条描出轮廓
  4. 设置描边动画
  5. 鼠标悬浮在图标上时触发动画

参考

MDN-strokeopen in new window
MDN-stroke-dasharrayopen in new window

上次编辑于:
贡献者: ViewRoom