【Anime.js】—JavaScriptアニメーションライブラリ: Anime.js—研究ノート

目次

1.開発環境を構築する

 2. 基本機能と使い方

アニメーションを開始

アニメーション プロパティ

3、anime.stagger - インターレース アニメーション

四、タイムライン - 時間軸

 5、コントロール、コールバック、アシスタント

1. コントロール

 2.コールバック

3.アシスタント

6、イージング - アニメーション モーション カーブ

セブン、SVGアニメーション


公式ウェブサイトの定義:

anime.js はシンプルな JS アニメーション ライブラリで、使いやすく幅広いアプリケーションがあり、CSS、DOM、SVG、および JS オブジェクトをカバーし、数値属性を持つあらゆる種類のものをアニメーション化できます。

1.開発環境を構築する

1. 新しいフォルダーを作成し、vs コードで開き、ワークスペースに追加します。

2.ターミナルを開く

ターミナルに次のように入力します。

npm i animejs --save

 3. フォルダーを作成し、anime.js パッケージを使用します

場所は図の通りです。

4. シンプルなアニメーション スタイルを実装する

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div{
            width: 100px;
            height: 100px;
            background-color: brown;
        }
    </style>
</head>
<body>
    <div></div>
    <script src="node_modules/animejs/lib/anime.min.js"></script>
    <script>
        anime({
            targets:'div',
            translateX:'400px',
            easing:'linear',
            duration:2000
        })
    </script>
</body>
</html>

 ブロックの均一な動きの効果を得ることができます。

 2. 基本機能と使い方

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div{
            width: 100px;
            height: 100px;
            background-color: blueviolet;
        }
    </style>
</head>
<body>
    <div id = 'first'></div>
    <div class = 'second'></div>
    <div class = 'second'></div>
    <div class = 'second'></div>
    <script src="../node_modules/animejs/lib//anime.min.js"></script>
    <script>
        anime({
            targets:'#first',
            translateX:'400px'
        })
    </script>
</body>
</html>

 最初の div が移動します。

 コードを次のように変更した場合:

 <script>
        anime({
            targets:'.second',
            translateX:'400px'
        })
 </script>

 ご覧のとおり、ターゲットはモバイル要素を選択するためのセレクターとして使用されます。 

アニメーションを開始

anime({
targets: 'div',
translateX: [
    { value: 100, duration: 1200 },
    { value: 0, duration: 800 }
],
rotate: '1turn',
backgroundColor: '#FFF',
duration: 2000,
loop: true
});

targets属性は、アニメーション化する要素または js オブジェクトを定義します。

  • css セレクター: 'div'、'#el path';
  • 次のような DOM 要素: document.querySelector('.item')
  • 次のようなノードのリスト: document.querySelectorAll('.item')
  • 物体
  • ['div', '.item', domNode] のような配列

アニメーション プロパティ

1、CSS:

  • opacity 透明度 0~1
  • 背景色
  • フォントサイズ
  • ボーダー半径
  • 背景色

2、変換変換:

  • translateX x 軸の値
  • translateY y 軸の値
  • 回転する
  • 縮尺変換例:scale:2 scale:0.5   
  • 回転例:rotate:'1turn'(1回転)

3. オブジェクトのプロパティ

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            width: 100px;
            height: 100px;
            background-color: cadetblue;
        }
    </style>
</head>

<body>
    <div id="JSobjectProp">
        <span>{"myProperty":"0"}</span>
    </div>
    <script src="../node_modules/animejs/lib//anime.min.js"></script>
    <script>
        var myObject = {
            prop1: 0,
            prop2: '0%'
        }
        var JSobjectProp = anime({
            targets: myObject,
            prop1: 50,
            prop2: '100%',
            easing: 'linear',
            round: 1,
            update: function () {
                var el = document.querySelector('#JSobjectProp span');
                el.innerHTML = JSON.stringify(myObject);
            }
        });
    </script>
</body>

</html>

始める: 

 

 になります:

4. DOM 属性

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
    </style>
</head>

<body>
    <input class="text-output" value="0">
    <script src="../node_modules/animejs/lib//anime.min.js"></script>
    <script>
        var domAttributes = anime({
            targets: 'input',
            value: 1000, // value变化为1000
            round: 100, //表示小数,把1分成了100份,也就是展示两位小数点
            easing: 'easeInOutExpo'
        });
    </script>
</body>

</html>

 5. 各属性を個別に設定する

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            width: 100px;
            height: 100px;
            background-color: cadetblue;
        }
    </style>
</head>
<body>
    <div></div>
    <script src="../node_modules/animejs/lib//anime.min.js"></script>
    <script>
        anime({
                targets: 'div',
                translateX: {
                    value: 250,//通过value来设置值
                    duration: 800 //表示延长动画效果的时间
                },
                rotate: {
                    value: 360,
                    duration: 1800,
                    easing: 'easeInOutSine'
                },
                scale: {
                    value: 2,
                    duration: 1600,
                    delay: 800,
                    easing: 'easeInOutQuart'
                },
                delay: 250 // All properties except 'scale' inherit 250ms delay
            });
    </script>
</body>
</html>

 6. 属性パラメータ

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            width: 100px;
            height: 100px;
            background-color: cadetblue;
        }
    </style>
</head>

<body>
    <div></div>
    <script src="../node_modules/animejs/lib//anime.min.js"></script>
    <script>
        anime({
            targets: 'div',
            translateX: 270,
            direction: 'alternate',
            loop: true,
            // 接收三个参数:
            // el:表示当前目标元素
            // i: 表示当前目标元素下标
            // l:表示目标元素的总长度
            delay: function (el, i, l) {
                return i * 100;
            },
            endDelay: function (el, i, l) {
                return (l - i) * 100;
            }

        });
    </script>
</body>

</html>

3、anime.stagger - インターレース アニメーション

1、

anime.stagger(value, options)
//它针对多个元素。
//第一个参数接收:Number, String, Array
//第二个参数接收:Object
anime({
  targets: '.basic-staggering-demo .el',
  translateX: 270,
  delay: anime.stagger(100) // increase delay by 100ms for each elements.
});

効果: 

 

2、 

anime.stagger(value, {start: startValue}) //在value后面添加对象属性

 

anime({
  targets: '.staggering-start-value-demo .el',
  translateX: 270,
  delay: anime.stagger(100, {start: 500}) // delay starts at 500ms then increase by 100ms for each elements.
});

3、

anime.stagger([startValue, endValue]) //作为rotate旋转的属性值
anime({
  targets: '.range-value-staggering-demo .el',
  translateX: 270,
  rotate: anime.stagger([-360, 360]), // rotation will be distributed from -360deg to 360deg evenly between all elements
  easing: 'easeInOutQuad'
});

 4、

anime.stagger(value, {from: startingPosition}) //从哪个位置依次延迟
anime({
  targets: '.staggering-from-demo .el',
  translateX: 270,
  delay: anime.stagger(100, {from: 'center'})
});

5、

anime.stagger(value, {direction: 'reverse'}) //反向延迟
anime({
  targets: '.staggering-direction-demo .el',
  translateX: 270,
  delay: anime.stagger(100, {direction: 'reverse'})
});

6、

anime.stagger(value, {grid: [rows, columns]})
anime({
  targets: '.staggering-grid-demo .el',
  scale: [
    {value: .1, easing: 'easeOutSine', duration: 500},
    {value: 1, easing: 'easeInOutQuad', duration: 1200}
  ],
    //grid: [14, 5]表示14行5列
    //from 表示从哪里开始
  delay: anime.stagger(200, {grid: [14, 5], from: 'center'})
});

7、

anime.stagger(value, {grid: [rows, columns], axis: 'x'})
//axis设置为x,表示将一整行设置为整体
//设为y,会将一整列设置为整体
anime({
  targets: '.staggering-axis-grid-demo .el',
  translateX: anime.stagger(10, {grid: [14, 5], axis: 'x'})
})

 

四、タイムライン - 時間軸

次に、公式ウェブサイトのタイムライン モジュールを学習します。

 このモジュールは、複数のアニメーションを作成できるタイムラインを作成できること、およびタイムラインに追加された各アニメーションは、前のアニメーションが終了した後実行を開始することを示しています。

1. タイムラインを作成する

タイムラインを作成します。

//调用该方法:
var myTimeline = anime.timeline(parameters);

このタイムラインからオブジェクトを呼び出す方法:

myTimeline.add(parameters, offset);
//parameters 动画相关的参数
//offset 时间偏移量

例: 

// 创建了一个时间轴对象
var tl = anime.timeline({
  easing: 'easeOutExpo',
  duration: 750  // 持续时间是750ms
});

// 时间轴上分别创建了三个动画
tl
.add({
  targets: '.basic-timeline-demo .el.square', //方形
  translateX: 250,   // 平移250px
})
.add({
  targets: '.basic-timeline-demo .el.circle', //圆形
  translateX: 250,
})
.add({
  targets: '.basic-timeline-demo .el.triangle', //三角形
  translateX: 250,
});

 円は、前のブロックが実行されるまで実行されません。

2.タイムオフセット

 時間オフセットは、時間軸を作成するために使用する 2 番目のパラメーターです。

デフォルトでは、各アニメーションは前のアニメーションが終了した後に実行を開始します。各アニメーションの実行を開始する時間は、時間オフセットによって変更できます。

次の図に示すように、時間オフセットには、文字列と数値の 2 つのデータ型があります。

 文字列は、前のアニメーションに対して相対的に設定されます。次に例を示します。

'+=200' は、前のアニメーションの実行から 200 ミリ秒後に現在のアニメーションを実行することを意味します。

「-=200」は、前のアニメーション実行が終了する 200 ミリ秒前に現在のアニメーションを実行することを意味します。

数値オフセットは、時間軸全体に対する絶対オフセットです

200 は、現在の時間軸の開始から 200ms 後に実行することを意味します。

// Create a timeline with default parameters
var tl = anime.timeline({
  easing: 'easeOutExpo',
  duration: 750
});

tl
.add({
  targets: '.offsets-demo .el.square',
  translateX: 250,
})
.add({
  targets: '.offsets-demo .el.circle',
  translateX: 250,
}, '-=600') // 相对偏移量————字符创
.add({
  targets: '.offsets-demo .el.triangle',
  translateX: 250,
}, 400); // 绝对偏移量————数字

3. パラメータの継承

タイムラインに追加されたアニメーションは、テーブル内のこれらのプロパティを継承できます
targets
easing
duration
delay
endDelay
round

知らせ:

direction 和 loop 是不可以被继承的。

デモ: (targets 属性を継承) 

 

 5、コントロール、コールバック、アシスタント

1. コントロール

ページに必要な要素:

 1. アニメーションの属性

animation.play(); //开始
animation.pause(); //暂停
animation.restart(); //重新开始
animation.reverse(); //反向移动
// seek 当前元素显示在具体时间的某一帧
// timeStamp:跳到具体的时间
animation.seek(timeStamp); 
// 通过滚动条来控制动画
// scrollPercent / 100:求滚动条的百分比
// animation.duration:当前动画的时间
// (scrollPercent / 100) * animation.duration:具体跳到的时间值
animation.seek((scrollPercent / 100) * animation.duration);

 

 2. 時間軸上の性質

// 控制时间轴上的动画:
timeline.play();
timeline.pause();
timeline.restart();
timeline.seek(timeStamp);

 2.コールバック

 1. UPDATE: フレームが更新されるたびに呼び出されます

var updates = 0;

anime({
  targets: '.update-demo .el',
  translateX: 270,
  delay: 1000,
  direction: 'alternate',
  loop: 3,
  easing: 'easeInOutCirc',
    // anim当前动画的实例
  update: function(anim) {
    updates++;
    // anim.progress 当前动画的进度
    progressLogEl.value = 'progress : '+Math.round(anim.progress)+'%';
    updateLogEl.value = 'updates : '+updates;
  }
});

例: 

 58 フレームが更新されたことを示します。

2、開始と完了

BEGIN: アニメーションの実行開始前に 1 回トリガーされます

COMPLETE: アニメーションの終了時に 1 回トリガーされます

        これら 2 つのプロパティはブール型です

例:

矢印の書き方が違うので注意!! !

 効果:

 3、LOOPBEGIN & LOOPCOMPLETE

LOOPBEGIN: ループの開始時に 1 回発生します。

LOOPCOMPLETE: ループの最後に 1 回トリガーされます

注: アニメーションはループ アニメーションである必要があります

var loopBegan = 0;
var loopCompleted = 0;

anime({
  targets: '.loopBegin-loopComplete-demo .el',
  translateX: 240,
  loop: true,
  direction: 'alternate',
  easing: 'easeInOutCirc',
  loopBegin: function(anim) {
    loopBegan++;
    beginLogEl.value = 'loop began : ' + loopBegan;
  },
  loopComplete: function(anim) {
    loopCompleted++;
    completeLogEl.value = 'loop completed : ' + loopCompleted;
  }
});

4. CHANGE: アニメーション要素が更新されるたびに呼び出されます

update との違い: change は delay と endDelay の間は更新されず、update はその逆です。

var changes = 0;

anime({
  targets: '.change-demo .el',
  translateX: 270,
  delay: 1000,
  endDelay: 1000,
  direction: 'alternate',
  loop: true,
  easing: 'easeInOutCirc',
  update: function(anim) {
    progressLogEl.value = 'progress : '+Math.round(anim.progress)+'%';
  },
  change: function() {
    changes++;
    changeLogEl.value = 'changes : ' + changes;
  }
});

 5. FINISHED PROMISE: 各アニメーション インスタンスは、完了すると Promise を返します。

// animation表示创建的动画实例
animation.finished.then(function() {
  // Do things...
});
var progressLogEl = document.querySelector('.promise-demo .progress-log');
var promiseEl = document.querySelector('.promise-demo .el');
var finishedLogEl = document.querySelector('.promise-demo .finished-log');
var demoPromiseResetTimeout;

function logFinished() {
  anime.set(finishedLogEl, {value: 'Promise resolved'});
  anime.set(promiseEl, {backgroundColor: '#18FF92'});
}

var animation = anime.timeline({
  targets: promiseEl,
  delay: 400,
  duration: 500,
  endDelay: 400,
  easing: 'easeInOutSine',
  update: function(anim) {
    progressLogEl.value = 'progress : '+Math.round(anim.progress)+'%';
  }
}).add({
  translateX: 250
}).add({
  scale: 2
}).add({
  translateX: 0
});

animation.finished.then(logFinished);

3.アシスタント

1、アニメ.削除

// remove 将某个targets对象移出
anime.remove(targets);
animation.remove(targets);
var animation = anime({
  targets: '.remove-demo .el',
  translateX: 270,
  direction: 'alternate',
  loop: true,
  easing: 'easeInOutQuad'
});

document.querySelector('.remove-el-button').addEventListener('click', function() {
  animation.remove('.remove-demo .line:nth-child(2) .el');
});

2、anime.get

// get 获取元素的信息
// target 获取的元素
// propertyName 获取的元素的属性
// unit 单位
anime.get(target, propertyName, unit);
var logEl = document.querySelector('.get-value-demo-log');
var el = document.querySelector('.get-value-demo .el');

logEl.innerHTML = '';
logEl.innerHTML += '".el" width is :<br>';
logEl.innerHTML += '"' + anime.get(el, 'width', 'px') + '"';
logEl.innerHTML += ' or "' + anime.get(el, 'width', 'rem') + 'rem"'

3、アニメセット

// set 设置元素的属性值是什么
// {property: value} :是一个对象,{属性:值}
// target(s) 类型是'string', var
// value 类型是object
anime.set(targets, {property: value});
anime.set('.set-value-demo .el', {
  translateX: function() { return anime.random(50, 250); },
  rotate: function() { return anime.random(0, 360); },
});

4、アニメ.ランダム

// random 返回一个随机数
anime.random(minValue, maxValue);
function randomValues() {
  anime({
    targets: '.random-demo .el',
    translateX: function() {
      return anime.random(0, 270);
    },
    easing: 'easeInOutQuad',
    duration: 750,
    complete: randomValues
  });
}

randomValues();

5、アニメ.ランニング

//running 表示动画实例,其长度代表动画个数
anime.running
var runninLogEl = document.querySelector('.running-log');

anime({
  targets: '.running-demo .square.el',
  translateX: 270,
  direction: 'alternate',
  loop: true,
  easing: 'linear'
});

anime({
  targets: '.running-demo .circle.el',
  translateX: 270,
  direction: 'alternate',
  loop: true,
  easing: 'easeInOutCirc'
});

anime({
  targets: '.running-demo .triangle.el',
  translateX: 270,
  direction: 'alternate',
  easing: 'easeInOutQuad',
  loop: true,
  update: function() {
    runninLogEl.innerHTML = 'there are currently ' + anime.running.length + ' instances running';
  }
});

6、イージング - アニメーション モーション カーブ

1.使用する

// linear表示线性
easing: 'linear'

2.方法

これらの方法がどのように変化したかをご覧ください

インアウト でアウト
'easeInQuad' 'easeOutQuad' 'easeInOutQuad' 'easeOutInQuad'
'easeInCubic' 'easeOutCubic' 'easeInOutCubic' 'easeOutInCubic'
'easeInQuart' 'easeOutQuart' 'easeInOutQuart' 'easeOutInQuart'
'easeInQuint' 'easeOutQuint' 'easeInOutQuint' 'easeOutInQuint'
'easeInSine' 'easeOutSine' 'easeInOutSine' 'easeOutInSine'
'easeInExpo' 'easeOutExpo' 'easeInOutExpo' 'easeOutInExpo'
'easeInCirc' 'easeOutCirc' 'easeInOutCirc' 'easeOutInCirc'
'easeInBack' 'easeOutBack' 'easeInOutBack' 'easeOutInBack'
'easeInBounce' 'easeOutBounce' 'easeInOutBounce' 'easeOutInBounce'

例:

 3. ベジエ曲線とバネ

どちらもパラメータが変化する曲線です

// 方法接收4个参数,通过参数来改变运动曲线
easing: 'cubicBezier(.5, .05, .1, .3)'
// mass 质量
// stiffness 高度
// damping 阻尼
// velocity 速度
easing: 'spring(mass, stiffness, damping, velocity)'
属性 デフォルト 最小 最大
質量 1 0 100
剛性 100 0 100
ダンピング 10 0 100
速度 0 0 100

4、弾性

// amplitude 振幅
// period 来回的次数
// 也是表示弹簧,只不过弹的方向不一样
easing: 'easeOutElastic(amplitude, period)'
インアウト でアウト
'easeInElastic' 'easeOutElastic' 'easeInOutElastic' 'easeOutInElastic'
属性 デフォルト 最小 最大
振幅 1 1 10
期間 .5 0.1 2

5. ジャンプ

// numberOfSteps跳动的步数
easing: 'steps(numberOfSteps)'
属性 デフォルト 最小 最大
ステップ数 10 1

6. カスタム機能

easing: function() { return function(time) { return time * i} }

戻り値は関数でなければならないことに注意してください

anime({
  targets: '.custom-easing-demo .el',
  translateX: 270,
  direction: 'alternate',
  loop: true,
  duration: 2000,
  easing: function(el, i, total) {
    return function(t) {
      return Math.pow(Math.sin(t * (i + 1)), total);
    }
  }
});

セブン、SVGアニメーション

1. スポーツ

// svg path 表示svg的路径
var myPath = anime.path('svg path');

// myPath 接收三个参数
// myPath('x'),传入的是svg path中 x 的值
// myPath('y'),传入的是svg path中 y 的值
// myPath('angle'),传入的是svg path中 角度 的值
var path = anime.path('.motion-path-demo path');

anime({
  targets: '.motion-path-demo .el',
  translateX: path('x'),
  translateY: path('y'),
  rotate: path('angle'),
  easing: 'linear',
  duration: 2000,
  loop: true
});

例:

 効果:

 2.変形

SVG 描画エディタの Web ページを共有してください:

SVG エディタ

 効果:ページ上にダイナミックな五角形が見える

 3.線を引く

まず、描画された svg ラインが必要であり、次に渡します。

strokeDashoffset: [anime.setDashoffset, 0]

 ラインを実現します。

 効果:


注記: https://www.jianshu.com/p/39fc8a837b31 

公式ドキュメント: https://animejs.com/documentation/#functionBasedParameters

おすすめ

転載: blog.csdn.net/qq_50497708/article/details/128322505