微信小程序> 小程序开发API之监听设备方向wx.startDeviceMotionListening

小程序开发API之监听设备方向wx.startDeviceMotionListening

浏览量:6201 时间: 来源:钢丝球 M.Siebel

效果展示:


小程序

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





版权声明

即速应用倡导尊重与保护知识产权。如发现本站文章存在版权问题,烦请提供版权疑问、身份证明、版权证明、联系方式等发邮件至197452366@qq.com ,我们将及时处理。本站文章仅作分享交流用途,作者观点不等同于即速应用观点。用户与作者的任何交易与本站无关,请知悉。

  • 头条
  • 搜狐
  • 微博
  • 百家
  • 一点资讯
  • 知乎