<!--pages/index.wxml--> <view class='box'> <view class='title'>传感器</view> <view class='btnLayout'> <button type='primary' bindtap='startCompass'>启动罗盘监听</button> <button type='primary' bindtap='stopCompass'>停止罗盘监听</button> </view> <view class='txtLayout'> <view>罗盘方位角:{{resCompass.direction}}</view> <view>罗盘精度:{{resCompass.accuracy}}</view> </view> <view class='btnLayout'> <button type='primary' bindtap='startAcc'>启动加速度计</button> <button type='primary' bindtap='stopAcc'>停止加速度计</button> </view> <view class='txtLayout'> <view>X轴方向加速度:{{resAcc.x}}</view> <view>Y轴方向加速度:{{resAcc.y}}</view> <view>Z轴方向加速度:{{resAcc.z}}</view> </view> <view class='btnLayout'> <button type='primary' bindtap='startGyroscope'>启动陀螺仪</button> <button type='primary' bindtap='stopGyroscope'>停止陀螺仪</button> </view> <view class='txtLayout'> <view>X轴方向角速度:{{resGyroscope.x}}</view> <view>Y轴方向角速度:{{resGyroscope.y}}</view> <view>Z轴方向角速度:{{resGyroscope.z}}</view> </view> </view>
/* pages/index.wxss */ button { /*button组件样式*/ margin: 10rpx; width: 45%; } view { /*view组件样式*/ margin: 5rpx 0rpx; padding: 5rpx; } .btnLayout { /*button组件布局*/ display: flex; flex-direction: row; justify-content: center; } .txtLayout { /*text组件布局*/ display: flex; flex-direction: column; margin: 5rpx 0rpx; border: 1px solid burlywood; }
// pages/index.js Page({ startCompass: function() { var that = this wx.startCompass({ //启动罗盘传感器监听功能 success: function() { wx.onCompassChange(function(res) { //监听罗盘传感器 that.setData({ resCompass: res //res为回调函数的参数,监听数据赋值给resCompass,监听数据都在回调函数的参数res里面 }) }) } }) }, stopCompass: function() { var that = this; wx.stopCompass({ //停止罗盘传感器监听功能 success: function(res) { console.log('罗盘已经停止!') } }) }, startAcc: function() { var that = this; wx.startAccelerometer({ //启动加速度感器监听功能 success: function() { wx.onAccelerometerChange(function(res) { //监听罗盘传感器 that.setData({ resAcc: res //res为回调函数的参数 }) }) } }) }, stopAcc: function() { wx.stopAccelerometer({ //停止罗盘传感器监听功能 success: function(res) { console.log('已停止加速度传感器监听!') } }) }, startGyroscope: function() { var that = this; wx.startGyroscope({ //启动陀螺仪传感器监听功能 success: function(res) { wx.onGyroscopeChange(function(res) { //监听陀螺仪传感器 that.setData({ resGyroscope: res //res为回调函数的参数 }) }) } }) }, stopGyroscope: function() { wx.stopGyroscope({ //停止陀螺仪传感器监听功能 success: function(res) { console.log('已停止陀螺仪传感器监听!') } }) } })
罗盘传感器的使用方法
加速度传感器的使用方法
陀螺仪传感器的使用方法
罗盘传感器
与罗盘传感器有关的API函数包括:
wx.startCompass(Object object)
wx.stopCompass(Object object)
wx.onCompassChange(function callback)
wx.startCompass() 和 wx.stopCompass() 分别 用于启动和停止罗盘监听,它们的参数属性包含: success、fail和complete。
wx.onCompassChange(function callback)用于 监听罗盘数据变化事件。监听频率是5次/秒, 接 口调用后会自动开始监听 , 可使用 wx.stopCompass 停止监听。
wx.onCompassChange(function callback) 的参数为罗盘数据变化事件的回调函数。 该回调函数的参数属性如下:
陀螺仪传感器
与陀螺仪传感器有关的API函数包括:
wx.startGyroscope(Object object)
wx.stopGyroscope(Object object)
wx.onGyroscopeChange(function callback)