tween.js 使用指南

390 阅读1分钟

tween.js

效果展示

动画.gif

介绍

允许你以平滑的方式更改对象的属性*(注意是对象的属性)*。 你只需告知它哪些属性要更改,属性的最终值,以及需要运行的时间

安装

with npm:

npm i @tweenjs/tween.js@^18

引入:

const TWEEN = require('@tweenjs/tween.js')

使用指南

例如 position 对象有 xy 属性:

var position = {x: 100, y: 0}

假如想将 x 的值从 100 改为 200, 可以这么做:

// 为 position 创建一个 tween 实例
var tween = new TWEEN.Tween(position)

// 告诉 tween 我们想要改变 x 的值在 1000 毫秒之内
tween.to({x: 200}, 1000)
  

这样做不会起作用的. tween被创建了但是还没激活 . 先启动它:

// start
tween.start()

最后,想要成功的完成所需的效果,需要在主函数中调用 TWEEN.update . 就像这样:

animate()

function animate() {
	requestAnimationFrame(animate)
	// [...]
	TWEEN.update()
	// [...]
}

会更新所有的激活的 tweens 实例; 1 秒之后 position.x 的值就会变为 200.

可以使用 onUpdate 函数实时获取更新的值:

tween.onUpdate(function (object) {
	console.log(object.x)
})

每一个 tween 函数都会返回一个实例,因此它可以链式调用,因此我们可以重写如下代码:

var tween = new TWEEN.Tween(position)
tween.to({x: 200}, 1000)
tween.start()

变为

var tween = new TWEEN.Tween(position).to({x: 200}, 1000).start()

with Vue

<template>
  <div class="about">
    <div class="core">
      <p>count: {{ position.x }}</p>
      <div class="change" @click="change">变化</div>
    </div>
  </div>
</template>
<script>
const TWEEN = require("@tweenjs/tween.js");
export default {
  data() {
    return {
      position: { x: 100, y: 0 },
    };
  },
  methods: {
    change() {
      var tween = new TWEEN.Tween(this.position);
      tween.to({ x: +this.position.x + 100 }, 2000).onUpdate((object) => {
        this.position.x = object.x.toFixed(0);
      });

      tween.start();
      animate();

      function animate() {
        requestAnimationFrame(animate);
        TWEEN.update();
      }
    },
  },
};
</script>
<style lang="css">
.about {
  width: 100vw;
  height: 100vh;
  color: #fff;
  display: flex;
  font-size: 30px;
  align-items: center;
  justify-content: center;
}
.core {
  color: pink;
  width: 100vw;
  text-align: center;
}
.change {
  padding: 20px;
  margin: 20px;
  border-radius: 20px;
  text-align: center;
  color: #fff;
  background-color: pink;
}
</style>

Animating with tween.js

还有还有...