LoginSignup
63
64

More than 5 years have passed since last update.

velocity.jsでぐにゃぐにゃSVGを描く

Last updated at Posted at 2015-04-03

はじめに

ロゴやキャッチなどでたまに見かける、ぐにゃぐにゃと動くSVGをvelocity.jsを使って実装してみました。
<こんな感じのやつ (何て言ったらいいのでしょうか。ラインアニメーション、ストロークアニメーション、とか?)>

svg-anim01.gif

なおオンライン上で簡単に作成できるサービスもあるようです
http://lazylinepainter.info/

用意するもの

  • jQuery
  • velocity.js
  • svgファイル(今回はIllustratorで書き出し)

velocity.js とは
- アニメーションを実現するJSライブラリ
- 他ライブラリやcssアニメーションより高速
- jQueryアニメーションと同じような記述ができる
- jQueryを使わなくても動作はする

実装

index.html
<!-- SVGファイルの読み込み -->
<object id="logo" data="./logo.svg" type="image/svg+xml">
script.js
$(function() {
    $(window).load(function() {
        var doc   = document.getElementById('logo').contentDocument;
        var $path = $(doc).find("path");

        // pathの長さをcssにセットする関数
        function setPathLengthToStyle($obj) {
            var len;
            var arr = [];
            Array.prototype.slice.call($obj).forEach(function(path, i) {
                arr.push(path);
                len = arr[i].getTotalLength() + 30 + 1 | 0; // +30は、Firefox対策。+1 | 0 は小数点切り上げ
                arr[i].style.strokeDasharray  = len;
                arr[i].style.strokeDashoffset = len;
            });
        }

        // CSSの設定
        $path.css({
            stroke      : "#4aa3df",
            fill        : "none",
            strokeWidth : 1
            // strokeDasharray, strokeDashoffsetは setPathLengthToStyle()で設定
        });
        setPathLengthToStyle($path);

        // アニメーション描画
        $path
             .velocity({ strokeDashoffset : 0 }, 3000 , "swing")
             .velocity({ fill: "#4aa3df" }, 1000 , "swing");
    });
});

pathの描画の仕方には少しクセがありますが、velocity.jsのおかげでアニメーション自体は非常に単純で分かりやすくできました。

また例えばアニメーション描画を以下のように変えると、順番になぞっていくような表現ができます。
<こんな感じ>

svg-anim02.gif

var pathLength = $path.length;
// アニメーション描画
$path.each(function(i) {
    $(this).velocity({
        strokeDashoffset: 0
    }, {
        delay    : 300 * i,
        duration : 1000,
        complete : function() {
            // ifを外して$(this)にすると、それぞれ終わった直後に塗りつぶしされていく
            if (i === (pathLength - 1)) {
                $path.velocity({
                    fill: "#4aa3df"
                }, 1000, "swing");
            }
        }
    });
});

参考

63
64
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
63
64