1. 程式人生 > >小程式-動畫,距離移動端適配方法

小程式-動畫,距離移動端適配方法

小程式動畫,距離移動端適配方法

問題:

由於小程式動畫如下:

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