效果展示:
wx.startDeviceMotionListening(Object object)
开始监听设备方向的变化。
参数Object
object.interval 的合法值
wx.stopDeviceMotionListening(Object object)
停止监听设备方向的变化。
参数Object
wx.onDeviceMotionChange(function callback)
监听设备方向变化事件。频率根据 wx.startDeviceMotionListening() 的 interval 参数。可以使用 wx.stopDeviceMotionListening() 停止监听。
参数
function callback
设备方向变化事件的回调函数
参数Object res
注:目前iOS的wx.onDeviceMotionChange无法正常关闭监听(安卓正常)20190508和官方联系,官方确定bug,正常修复中
示例代码:
效果展示:
代码:
index.wxml
<view class='messageView'>屏幕朝向:<text style='color:red;font-size:50rpx'>{{screen}}</text></view><!-- alpha number 当 手机坐标 X/Y 和 地球 X/Y 重合时,绕着 Z 轴转动的夹角为 alpha,范围值为 [0, 2*PI)。逆时针转动为正。 --><view class='messageView'>当前为alpha:{{alpha}}</view><button type='primary' bindtap='startScreenClick'>开始监听</button><button type='primary' bindtap='endScreenClick'>结束监听</button>
index.wxss
.messageView{ width: 100%; text-align: center;}button{ margin: 50rpx 50rpx 0 50rpx;}
index.js
//index.js//获取应用实例const app = getApp()Page({ /** * 页面的初始数据 */ data: { alpha: '0', screen: '正面' }, //开始监听屏幕方向 startScreenClick:function(){ wx.startDeviceMotionListening({ success: function () { console.log(e); } }) }, //结束监听屏幕方向 endScreenClick: function () { wx.stopDeviceMotionListening({ success: function (e) { console.log(e); }, fail(e) { console.log(e); } }) }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { var that = this; // alpha number 当 手机坐标 X / Y 和 地球 X / Y 重合时,绕着 Z 轴转动的夹角为 alpha,范围值为[0, 2 * PI) 。逆时针转动为正。 wx.onDeviceMotionChange(function (res) { var alpha = parseFloat(res.alpha); if (alpha > 45 && alpha < 136) { that.setData({ screen: '左侧' }) } else if (alpha > 225 && alpha < 316) { that.setData({ screen: '右侧' }) } else if (alpha > 135 && alpha < 226) { that.setData({ screen: '反面' }) } else { that.setData({ screen: '正面' }) } that.setData({ alpha: alpha }) }) },})
Demo:
Gitee: https://gitee.com/siebel/MGScreenDirection–MiniProgram