LoginSignup
16
16

More than 5 years have passed since last update.

jQueryで数値をイージング変化させる方法

Last updated at Posted at 2015-03-31

下記のコード使うとコンソールに r の値が swing の動きで 50 から 90 まで変化しながら数値で書き出されます。

また、jQueryUI や jquery.easing のプラグインを入れて easing に easeOutBounce などを指定すると数値がバウンスします。
SVG の値をイージングをかけて変化させたい時などに使います。

やりかた

jQuery

var rFrom = 50, rTo = 90;    //rFrom は開始時の値、rTo は終了時の値。

$({ratio: 0})
    .animate({ratio: 1}, {
    duration:1000,
    easing:"swing",
        progress: function(){
            var r = (rTo - rFrom) * this.ratio + rFrom;
            console.log('r ' + r );    //イージング変化した値が出力される。
        }
    });

 

jQuery1.4.x以前のバージョンを使う場合は以下の書き方になります

jQuery1.7.x以前

var rFrom = 50, rTo = 90;    //rFrom は開始時の値、rTo は終了時の値。

$({ratio: 0})
    .animate({ratio: 1}, {
    duration:1000,
    easing:"swing",
        step: function(){
            var rNow = (rTo - rFrom) * this.ratio + rFrom;
            someAnimation(rNow);
        }
        complete: function(){
            someAnimation(rTo);
        }
    });

function someAnimation(r){
    console.log('r ' + r );    //イージング変化した値が出力される。
}

 

作例 SVGの円をボヨンとさせる

jQuery
var rFrom = 50, rTo = 90;

$({ratio: 0})
    .animate({ratio: 1}, {
    duration:2000,
    easing:"easeOutBounce",
        progress: function(){
            var r = (rTo - rFrom) * this.ratio + rFrom;
            $("circle").attr("r",r);
        }
    });
html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"></script>

<h1>SVGの円をボヨンとさせる</h1>

<svg width="200" height="200"
    xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink">
    <circle cx="100" cy="100" r="50" stroke="#0172be" fill="#0172be" stroke-width="5"/>
</svg>

※ jQuery1.4.x 以前で step を使うとこの場合不具合があったのと、良い方法を教えていただいたのでスクリプトを修正しました。

16
16
2

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
16
16