小程序使用 rpx 单位 转 px的方法(用于动画、canvas画图)

时间:2023-03-09 12:45:11
小程序使用 rpx 单位 转 px的方法(用于动画、canvas画图)

1、需要借助的API:wx.getSystemInfoSync();

通过API可获取的值:

 // 在 iPhone6 下运行:
var systemInfo = wx.getSystemInfoSync();
console.log(systemInfo.windowWidth); // 输出 375(单位 px)
// 在 iPhone6 Plus 下:
var systemInfo = wx.getSystemInfoSync();
console.log(systemInfo.windowWidth); // 输出 414 (单位 px)

2、px与rpx之间转换的公式:px = rpx / 750 * wx.getSystemInfoSync().windowWidth;

 // 假设设计图中按钮向右偏移了300rpx,动画代码如下:
this.animation.translateX(300 / 750 * systemInfo.windowWidth).step()

这样在所有机型上都可以进行适配。