SVGフィルターを使ってボタンにオリジナリティのある動きを実装するチュートリアル

サンプル

CordropsにSVGフィルターを使ってボタンにオリジナリティのある動きを実装するチュートリアルが掲載されていました。

素敵なエフェクトなので、実装方法とあわせて紹介します。

まずは、公式サイトのデモをご覧ください。

公式サイトのデモ

ボタンをクリックすると、ボタンが伸びて、独特の動きをします。

ボタンの動作にインパクトをつけたいときに活用できます。

GitHubにソースが公開されているので、実装方法を紹介したいと思います。

実装方法

今回実装する完成版のサンプルを用意しました。

まずは、GitHubの右上にある「Download Zip」からzipファイルをダウンロードします。

zipファイルのjsフォルダに入っている、「TweenMax.min.js」と「main.js」を、</body>閉じタグの直前に読み込みます。

<script src="js/TweenMax.min.js"></script>
<script src="js/main.js"></script>

スタイルシートとして、zipファイルのcssフォルダに入っている、「main.css」を読み込みます。

<link href="css/main.css"/ rel="stylesheet">

HTMLでボタンを用意します。

<button id="component-1" class="button button--1">
  Click me
  <span class="button__container">
  <span class="circle top-left"></span>
  <span class="circle top-left"></span>
  <span class="circle top-left"></span>
  <span class="button__bg"></span>
  <span class="circle bottom-right"></span>
  <span class="circle bottom-right"></span>
  <span class="circle bottom-right"></span>
  </span>
</button>

さらに、SVGフィルタをHTML内に記述します。<body>タグの中なら、どこでも大丈夫です。

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" class="svg-filters">
  <defs>
  <filter id="filter-goo-1">
  <feGaussianBlur in="SourceGraphic" stdDeviation="7" result="blur" />
  <feColorMatrix in="blur" mode="matrix" values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 19 -9" result="goo" />
  <feComposite in="SourceGraphic" in2="goo" />
  </filter>
  </defs>
</svg>

SVGで作成したフィルタのスタイルをボタンに適用します。

<style>
.button {
  /* other styles */
  -webkit-filter: url("#filter");
  filter: url("/#filter");
}
</style>

以上で、サンプルの実装は完了です。

サンプル

公式サイトのデモにある、他のエフェクトについても、ダウンロードしたzipフォルダに入っているindex.htmlのソースコードを参考にして、同様の方法で実装できます。HTML内のボタン<button>とSVGフィルタ<svg>の部分を変更するだけでOKです。

参考情報