uni-app animation动画
来源:     阅读:1391
云上智慧
发布于 2020-04-24 16:19
查看主页

##? uni.createAnimation(OBJECT)

[官方文档](https://uniapp.dcloud.io/api/ui/animation?id=createanimation)

官方是这么形容animation动画的过程:

创立一个动画实例 animation。调用实例的方法来形容动画。最后通过动画实例的export方法导出动画数据传递给组件的animation属性。

接下来我就逐个说明

### 如何使用uniapp动画

先说需求, 点击按钮小猫开始运动

![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly91c2VyLWdvbGQtY2RuLnhpdHUuaW8vMjAxOS8xMS8xOS8xNmU3ZjU2ZjdhZTA2ODk3?x-oss-process=image/format,png)

首先在元素上绑定动画(`:animation="animationData"`)

```

<view :animation="animationData" class="animation">

? ? <image src="../../static/猫.png"></image>

</view>

<button @click="running" >别跑</button>

```

这一步是把animationData数据传递给animation属性

```

? export default {

? ? data() {

? ? ? return {

? ? ? ? animationData: {}

? ? ? ? // 在data中初始化animationData

? ? ? }

? ? },

? ? onUnload() {

? ? ? this.animationData = {}

? ? ? // 页面关闭后清空数据

? ? },

? ? onload(){

? ? ? ? ? this.animation = uni.createAnimation()?

? ? ? ? // 创立动画实例

? ? },

? ? methods: {

? ? ? running() {

? ? ? ? this.animation.translateX(500).step({duration:1000})

? ? ? ? // 调用实例的方法来形容动画,translateX定义动画类型为x轴偏移, 500为偏移长度, 单位px

? ? ? ? // 调用 step() 来表示一组动画完成(当前参数动画时间1s)

? ? ? ? // step 可以配置参数用于指定当前组动画的配置。具体参数请看文档

? ? ? ? this.animationData = this.animation.export()

? ? ? ? // export方法导出动画数据

? ? ? }

? ? }

? }

```

一个动画就定义好了

下面来看效果

![](https://pic.songma.com/wenzhang/20200120/kteujlrf1zv2903.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxMjc5Mzc0,size_16,color_FFFFFF,t_70)

### 链式动画

可以在step()之后紧接第二个动画, 相似promise写法

```

this.animation.translateX(100).step()

? ? .translateY(100).step()

? ? .translateX(0).step()

? ? .translateY(0).step()

```

效果

![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly91c2VyLWdvbGQtY2RuLnhpdHUuaW8vMjAxOS8xMS8xOS8xNmU3ZjkxYTE3NjZiNjUy?x-oss-process=image/format,png)

### 动画屡次触发

假如动画完成后, 元素未回到初始位置, 第二次动画是无法触发的

有两种方法使元素回到原位

#### 通过链式操作

在动画最后在增加一个动画的, 效果是返回原位(透明度,动画时间都是0)

```

this.animation.translateX(200).step({duration:700})

? ? .translateX(0).opacity(0).step({duration:0})

```

#### 设置timeout

假如动画时间是0.7s, 那就在0.8s之后使用动画让元素返回

timeout调用时间在动画完成之后

同样duration,opacity都为0

```

running() {

? ? ? ? this.animation = uni.createAnimation()

? ? ? ? this.animation.translateX(200).step({duration:700})

? ? ? ? this.animationData = this.animation.export()


? ? ? ? setTimeout(()=>{

? ? ? ? ? this.animation.translateX(0).opacity(0).step({duration:0})

? ? ? ? ? this.animationData = this.animation.export()

? ? ? ? }, 800);

? ? ? }

```

效果

![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly91c2VyLWdvbGQtY2RuLnhpdHUuaW8vMjAxOS8xMS8xOS8xNmU3ZjllNTQ2MjNjMWM1?x-oss-process=image/format,png)

免责声明:本文为用户发表,不代表网站立场,仅供参考,不构成引导等用途。 系统环境 服务器应用
相关推荐
Kafka Producer 阻拦器
spring-boot-maven-plugin not found 标红
Unity 打包apk关于AndroidSDKTools版本问题
20届毕业生请看过来!!!
请人搭Vue.js脚手架要收一千元,学了这篇文章终于会弄了
首页
搜索
订单
购物车
我的