小程序动画,距离移动端适配方法
问题:
由于小程序动画如下:
that.animation.translateY(-640 ).step()
距离没有单位,据实测是手机的分辨率,物理像素乘以dpr,导致在不同手机上移动距离不相同
解:
使用小程序的获取系统信息方法wx.getSystemInfo
获取windowWidth
(窗口宽度)和pixelRatio
(设备像素比)计算出当前rpx倍数,这里使用的是750是iphone6的宽度,是2倍计算起来比较方便。代码如下
var that=this;//小程序对象建议that一下,this可能在后面使用中被替换
wx.getSystemInfo({
success: function (res) {
let rpx = 1 * (res.windowWidth * res.pixelRatio) / (750 * res.pixelRatio);
that.setData({
rpx: rpx//添加到小程序全局data里面
})
}
});
//使用时
that.animation.translateY(-640*that.data.rpx).step();
下面附上我动画的代码可以看一下
wxml代码:
<view class='payfor' animation="{{animation}}"style=''>
这个是动画
</view>
<button class='' bindtap='move'>move</button>
js代码:
data:{
rpx: 0,
animation: '',
moveKey:true,
},
onLoad(options) {
var that =this;
wx.getSystemInfo({
success: function (res) {
let rpx = 1 * (res.windowWidth * res.pixelRatio) / (750 * res.pixelRatio);
that.setData({
rpx: rpx
})
}
})
//实例化一个动画
this.animation = wx.createAnimation({
// 动画持续时间,单位ms,默认值 400
duration: 300,
timingFunction: 'ease-out',
// 延迟多长时间开始
delay: 0,
transformOrigin: 'left top 0',
success: function (res) {
// console.log(res)
}
})
},
doAnimation(key) {//动画上部
var that = this;
if (key == true) {
setTimeout(function () {
that.animation.translateY(-640 * that.data.rpx).step()
that.setData({
//输出动画
animation: that.animation.export(),
close:true
})
}, 0)
} else {
setTimeout(function () {
that.animation.translateY(0 * that.data.rpx).step()
that.setData({
//输出动画
animation: that.animation.export()
})
}, 0)
},
move(){
var that= this;
var moveKey=that.data.moveKey;
that.doAnimation(!key)
that.setData({
moveKey:!moveKey
})
}