畫線動畫——SVG版和純CSS版

概述

咱們經常在網站中看到一些畫線的動畫效果,很是炫酷,大多數這種畫線動畫效果是經過SVG實現的,也有很多是用純css實現的,下面我總結了一下這2種方法,供之後開發時參考,相信對其餘人也有用。css

參考資料: 移動端網頁 PC端網頁html

SVG實現畫線效果

在svg裏面,能夠用stroke-dashoffset屬性來實現畫線效果,示例以下:svg

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>svg</title>
  <style>
  path{
      stroke-dasharray: 1000;
      stroke-dashoffset: 1000;
      animation: draw 5s ease 3;
  }
  @keyframes draw{
      0%{
          stroke-dashoffset: 1000;
      }
      100%{
          stroke-dashoffset: 0;
      }
  }
  </style>
</head>
<body>
<svg width="400px" height="400px" viewBox="100 250 400 400" version="1.1" xmlns="http://www.w3.org/2000/svg">
  <path d="M153 334
  C153 334 151 334 151 334
  C151 339 153 344 156 344
  C164 344 171 339 171 334
  C171 322 164 314 156 314
  C142 314 131 322 131 334
  C131 350 142 364 156 364
  C175 364 191 350 191 334
  C191 311 175 294 156 294
  C131 294 111 311 111 334
  C111 361 131 384 156 384
  C186 384 211 361 211 334
  C211 300 186 274 156 274"
  style="fill:white;stroke:red;stroke-width:2"/>
</svg>
</body>
</html>

須要注意的是,必需要設置stroke-dasharray屬性,而且和stroke-dashoffset同樣長;其中1000是個自定義的值,只要比畫線的總長度長就好了。動畫

純css畫線

對於長方形或者正方形這些規則的圖形,用css的transition效果便可,代碼以下:網站

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>svg</title>
  <style>
    #border {
      position: relative;
      width: 300px;
      height: 300px;
    }
    .border-top {
      position: absolute;
      top: 50px;
      left: 50px;
      width: 0;
      height: 8px;
      background-color: #333;
      transition: all .5s 1s;
    }
    .border-bottom {
      position: absolute;
      bottom: 50px;
      right: 50px;
      width: 0;
      height: 8px;
      background-color: #333;
      transition: all .5s 2s;
    }
    .border-right {
      position: absolute;
      top: 50px;
      left: 250px;
      width: 8px;
      height: 0;
      background-color: #333;
      transition: all .5s 1.5s;
    }
    .border-left {
      position: absolute;
      bottom: 50px;
      left: 50px;
      width: 8px;
      height: 0;
      background-color: #333;
      transition: all .5s 2.5s;
    }
    .animate .border-top, .animate .border-bottom {
      width: 200px;
    }
    .animate .border-right, .animate .border-left {
      height: 200px;
    }
  </style>
</head>
<body>
  <div id="border">
    <i class="border-top"></i>
    <i class="border-right"></i>
    <i class="border-bottom"></i>
    <i class="border-left"></i>
  </div>
  <script>
    setTimeout(function() {
      document.getElementById('border').className += ' animate';
    }, 500);
  </script>
</body>
</html>
相關文章
相關標籤/搜索