摘要
实现水平仪的算法不难,但是理解加速计—wx.onAccelerometerChange、陀螺仪—wx.onGyroscopeChange、设备方向—wx.onDeviceMotionChange这些接口返回数据很恶心,一是只能真机调试,二是晃动手机很难在一堆数据中找到规律,很恶心,为此,本文除了介绍水平仪的简单算法外,更重要的是介绍一款找数据规律的工具。
效果
水平仪效果(晃动真机)
硬件数据监听工具效果(晃动真机)
扫码体验
体验路径:
水平仪:硬件系列>水平仪
硬件数据监听工具:硬件系列>硬件数据监听工具
水平仪代码
// miniprogram/pages/index/pages/gyroscope/gyroscope.js
Page({
/**
* 页面的初始数据
*/
data: {
rotateXY:0,
rotateYZ:0,
rotateZX:0,
backgroundColor:'#000000',
degreesXY: 0,
degreesYZ: 0,
degreesZX: 0,
isOnAccelerometerChange: true,
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var that = this
wx.onAccelerometerChange(function (res) {
if(!that.data.isOnAccelerometerChange){
return
}
var rotateXY = Math.atan2(res.x, res.y) * 180 / Math.PI
var rotateYZ = Math.atan2(res.y, res.z) * 180 / Math.PI
var rotateZX = Math.atan2(res.z, res.x) * 180 / Math.PI
if (rotateXY<0){
that.setData({
rotateXY: rotateXY,
degreesXY: (rotateXY + 180).toFixed(2),
rotateYZ:rotateYZ,
rotateZX:rotateZX
})
}else{
that.setData({
rotateXY: rotateXY,
degreesXY: -(180 - rotateXY).toFixed(2),
rotateYZ: rotateYZ,
rotateZX: rotateZX
})
}
})
},
onUnload: function () {
this.setData({
isOnAccelerometerChange:false
})
wx.stopAccelerometer({
})
}
})
wxml
<view class="container">
<view class="view-row" style="color:#aaa;font-size:36rpx;margin:30rpx;border-bottom:1rpx solid #aaa;padding:10rpx">hardware—水平仪</view>
<view style="font-size:32rpx;color:#aaa">加速计实现(请竖直摆放手机)</view>
<view style="width:300rpx;height:10rpx;background:{{backgroundColor}};margin-top:200rpx;transform: rotate({{rotateXY}}deg);border-radius:5rpx;"></view>
<view class="view-row" style="color:#aaa;font-size:36rpx;margin:30rpx;padding:10rpx;margin-top:200rpx;">水平偏移{{degreesXY}}°</view>
</view>