LoginSignup
14
6

More than 5 years have passed since last update.

CSS animation で遊び倒す -SVG Line -

Last updated at Posted at 2019-02-08

CSS animation day18 となりました。
本日は、SVG を使って、Line でアニメーションを設定します。

1. 完成版

ダウンロード (44).gif

2. なぜか?

モニター心電図って病棟管理ではめちゃくちゃ大事ですが、なかなか難しいです。特に看護師さんたちが教科書で勉強するのに、適した教材は少なく、現場で苦労している姿をよく目にします。教科書のような静止画を、座学で見て勉強しても、臨場感がないため実戦に活かしづらく、苦手意識を持つ人々は多いと一循環器内科医として、感じております。
そこで、近い将来、SVG animation を使って、モニター心電図のweb siteを作りますが、この技術をふんだんに使えればと思いました。

3. 参考文献

CSS trick
SVG line drawing animation | SVG Stroke Animation With Html and CSS

4. 分解してみる

❶.

まず、Figma で適当に、ラインを書きます。

スクリーンショット 2019-02-08 13.01.34.png

では、コードを書いていきましょう。

index.html
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="UTF-8" />
    <link rel="stylesheet" href="css/styles.css" />

  </head>
  <body>
    <svg
      width="288"
      height="175"
      viewBox="0 0 288 175"
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
    >
      <path
        d="M1 143.5C28.6 143.1 42.5 143.333 46 143.5C52.3333 128.834 70.2 108.3 91 143.5H109L113.5 174.5L133.5 1L159.5 174.5L167 143.5H201C208.167 134.5 227.5 121.9 247.5 143.5H287.5"
        stroke="black"
      />
    </svg>
  </body>
</html>
styles.css
body {
  margin: 0;
  padding: 0;
}

svg {
  width: 500px;
  height: 500px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

スクリーンショット 2019-02-08 15.13.24.png

❷.
では、どうしたら、Line のアニメーションができるでしょうか?

答えは、stroke-dasharray と stroke-dashoffset を使います。
順に説明します。


. stroke-dasharray
破線の間隔をつけるプロパティです。
値が大きけれ大きいほど、間隔が広くなります。 

stroke-dashoffset
SVG pathが始まる場所を指定します。


この2つをどう使うかというと、

1. 破線の間隔が、SVG の線の長さと同じ値を探し、stroke-dasharrayに設定して、全てを隠します。
2. SVG のpathが始まる場所を、全てが隠れる位置になるよう設定します。つまり、stroke_dasharray と、stroke-dashoffset に同じ値を設定します。
3. stroke_dashoffset をアニメーションで動かします。

実際のコードで見て見ましょう。

styles.scss
svg {
  width: 500px;
  height: 500px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);

  .line {
    stroke-width: 4px;
    stroke-dasharray: 700px;
    stroke-dashoffset: 700px;
    animation: draw 2s linear infinite;
  }
}

@keyframes draw {
  to {
    stroke-dashoffset: 0px;
  }
}

ダウンロード (44).gif

こんな簡単なコードで、心電図波形が出来上がりました。
本日は以上です、また明日〜

14
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
6