因为是第一次在微信小程序中使用动画对象,因此记录一下,先封装了一个简单的左右滑动的动画效果,其他动画效果的定义也类似,可以传递动画详细参数进去自定义。
定义一个动画工具类 animationUtil.js
var app = getApp()
//左右平缓滑动
function sliderOfRightLeft(that){
var circleCount = 0;
// 创建一个动画实例
var animation = wx.createAnimation({
duration: 2000, // 动画持续时间
timingFunction: 'linear' // 定义动画效果,当前是匀速
})
// 将该变量赋值给当前动画
that.animationData = animation
setInterval(function () {
if (circleCount % 2 == 0) {
that.animationData.translateX(30).step();
}
else {
that.animationData.translateX(0).step();
}
that.setData({
animationData: that.animationData.export() // 通过export()方法导出数据
})
circleCount++;
if (circleCount == 1000) {
circleCount = 0;
}
}, 1000)
return that.animationData;
}
module.exports = {
sliderOfRightLeft: sliderOfRightLeft
}
- 自定义函数需要暴露时使用
module.exports = {
sliderOfRightLeft: sliderOfRightLeft
}
- 因为是设置一直运行的首页动画,使用circleCount变量和setInterval周期函数控制动画重复播放
- 动画设置完毕后,需要返回动画对象给调用方
使用如下
- 先引入动画工具类
var animationUtil= require('../../utils/animationUtil');
- 在page的data对象中定义动画对象变量
Page({
data: {
animationData: {}
},
- 在view中设置动画属性,绑定动画对象
<view animation='{{animationData}}' class="timeicon">
<image wx:if="{{isnight}}" src="../../image/夜晚.png" mode="scaleToFill"></image>
<image wx:if="{{!isnight}}" src="../../image/太阳.png" mode="scaleToFill"></image>
</view>
- 最后在onShow页面加载事件中使用动画函数,传递page对象进去
onShow: function () {
animationUtil.sliderOfRightLeft(this);
},