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