【Anime.js】—Biblioteca de animación de JavaScript: Anime.js——Notas de estudio

Tabla de contenido

1. Cree un entorno de desarrollo

 2. Funciones básicas y uso

iniciar animación

propiedades de animación

Tres, anime.stagger - animación entrelazada

Cuatro, línea de tiempo - eje de tiempo

 Five, control, callback y asistente

1. Controlar

 2. Devolución de llamada

3. Asistente

Seis, flexibilización - curva de movimiento de animación

Siete, animación SVG


Definición del sitio web oficial:

anime.js es una biblioteca de animación JS simple, que es fácil de usar y tiene una amplia gama de aplicaciones, que cubre objetos CSS, DOM, SVG y JS, se puede animar todo tipo de cosas con atributos numéricos.

1. Cree un entorno de desarrollo

1. Cree una nueva carpeta, ábrala con el código vs y agréguela al espacio de trabajo.

2. Abre la terminal

Escriba en la terminal:

npm i animejs --save

 3. Crea una carpeta y usa el paquete anime.js

La ubicación se muestra en la figura.

4. Implementa un estilo de animación simple

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

 Se puede lograr el efecto de un movimiento uniforme de un bloque.

 2. Funciones básicas y uso

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

 El primer div se mueve:

 Si cambias el código a esto:

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

 Como puede ver, los objetivos se utilizan como selectores para seleccionar elementos móviles. 

iniciar animación

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

El atributo de objetivos define el elemento u objeto js para animar:

  • selectores css como: 'div', '#el camino';
  • Elementos DOM como: document.querySelector('.item')
  • Una lista de nodos como: document.querySelectorAll('.item')
  • objeto
  • Matriz como: ['div', '.item', domNode]

propiedades de animación

1, CSS:

  • opacidad Transparencia 0~1
  • color de fondo
  • tamaño de fuente
  • bordeRadio
  • color de fondo

2, transforma la transformación:

  • valor del eje x de translateX
  • valor del eje y de translateY
  • girar
  • ejemplo de conversión de tamaño de escala: escala:2 escala:0.5   
  • rotar Ejemplo: rotar: '1 vuelta' (rotar una vuelta)

3. Propiedades del objeto

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

comenzar: 

 

 se convierte en:

4. Atributos 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. Establecer cada atributo por separado

<!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. Parámetros de atributo

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

Tres, anime.stagger - animación entrelazada

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.
});

Efecto: 

 

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'})
})

 

Cuatro, línea de tiempo - eje de tiempo

A continuación, aprenda el módulo de línea de tiempo del sitio web oficial.

 Este módulo nos dice que podemos crear una línea de tiempo en la que se pueden crear múltiples animaciones , y cada animación agregada a la línea de tiempo comenzará a ejecutarse después de que finalice la animación anterior .

1. Crea una línea de tiempo

Crear una línea de tiempo:

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

Cómo llamar a objetos a través de esta línea de tiempo:

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

Ejemplo: 

// 创建了一个时间轴对象
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,
});

 El círculo no se ejecutará hasta que se ejecute el bloque anterior.

2. Compensación de tiempo

 El desplazamiento de tiempo es el segundo parámetro que usamos para crear el eje de tiempo.

De forma predeterminada, cada animación comenzará a ejecutarse después de que finalice la animación anterior, y la hora a la que cada animación comienza a ejecutarse se puede cambiar a través de la compensación de tiempo.

Como se puede ver en la figura a continuación, el desplazamiento de tiempo puede tener dos tipos de datos: Cadena y Número

 Las cadenas se establecen en relación con la animación anterior, por ejemplo:

'+=200' significa: ejecutar la animación actual después de 200 ms después de la ejecución de la animación anterior

'-=200' significa: ejecutar la animación actual 200ms antes del final de la ejecución de la animación anterior

Los desplazamientos numéricos son desplazamientos absolutos relativos a todo el eje de tiempo .

200 significa: Ejecutar después de 200 ms desde el inicio del eje de tiempo actual.

// 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. Herencia de parámetros

Las animaciones agregadas a la línea de tiempo pueden heredar estas propiedades en la tabla
targets
easing
duration
delay
endDelay
round

Aviso:

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

Demostración: (heredar el atributo de objetivos) 

 

 Five, control, callback y asistente

1. Controlar

Elementos requeridos en la página:

 1. Atributos en la animación

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. Propiedades en el eje del tiempo

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

 2. Devolución de llamada

 1. ACTUALIZAR: Llamado cada vez que se actualiza un marco

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;
  }
});

Ejemplo: 

 Indica que se han actualizado 58 fotogramas.

2, COMENZAR Y COMPLETAR

BEGIN: se activa una vez antes de que la animación comience a ejecutarse.

COMPLETO: se activa una vez cuando finaliza la animación

        Estas dos propiedades son de tipo booleano.

Ejemplo:

¡Tenga en cuenta que la escritura en la flecha es diferente! ! !

 Efecto:

 3, INICIO DE BUCLE Y BUCLE COMPLETO

LOOPBEGIN: se dispara una vez cuando comienza el bucle

LOOPCOMPLETE: Activado una vez al final del ciclo

Nota: La animación debe ser una animación en bucle.

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. CAMBIO: Llamado cada vez que se actualiza el elemento de animación

La diferencia con la actualización: el cambio no se actualiza durante el retraso y el retraso final, y la actualización es viceversa.

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. PROMESA FINALIZADA: cada instancia de animación devolverá una promesa cuando se complete

// 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. Asistente

1、anime.eliminar

// 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.obtener

// 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, juego de anime

// 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, anime.aleatorio

// 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、anime corriendo

//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';
  }
});

Seis, flexibilización - curva de movimiento de animación

1. Uso

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

2. Método

Vea cómo han cambiado estos métodos

EN AFUERA EN FUERA SALIR EN
'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'

Ejemplo:

 3. Curva BÉZIER y resorte

Ambas son curvas con parámetros cambiantes.

// 方法接收4个参数,通过参数来改变运动曲线
easing: 'cubicBezier(.5, .05, .1, .3)'
// mass 质量
// stiffness 高度
// damping 阻尼
// velocity 速度
easing: 'spring(mass, stiffness, damping, velocity)'
Atributos valores predeterminados MÍN. MÁX.
Masa 1 0 100
Rigidez 100 0 100
Mojadura 10 0 100
Velocidad 0 0 100

4 、 ELÁSTICO

// amplitude 振幅
// period 来回的次数
// 也是表示弹簧,只不过弹的方向不一样
easing: 'easeOutElastic(amplitude, period)'
EN AFUERA EN FUERA SALIR EN
'easeInElastic' 'easeOutElastic' 'easeInOutElastic' 'easeOutInElastic'
Atributos valores predeterminados MÍN. MÁX.
Amplitud 1 1 10
Período .5 0.1 2

5. Saltar

// numberOfSteps跳动的步数
easing: 'steps(numberOfSteps)'
Atributos valores predeterminados MÍN. MÁX.
Numero de pasos 10 1

6. Funciones personalizadas

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

Tenga en cuenta que el retorno debe ser una función

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);
    }
  }
});

Siete, animación SVG

1. Deportes

// 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
});

Ejemplo:

 Efecto:

 2. Deformación

Comparta con usted una página web del editor de dibujo svg:

editor de svg

 Efecto: Puedes ver el pentágono dinámico en la página.

 3. Dibuja una línea

Primero, debe haber una línea svg dibujada y luego pasar:

strokeDashoffset: [anime.setDashoffset, 0]

 para realizar la línea.

 Efecto:


Nota de referencia: https://www.jianshu.com/p/39fc8a837b31 

Documentación oficial: https://animejs.com/documentation/#functionBasedParameters

Supongo que te gusta

Origin blog.csdn.net/qq_50497708/article/details/128322505
Recomendado
Clasificación