微信小程序—调用罗盘接口实现指南针效果,致敬四大发明

摘要

指南针是中国的四大发明之一,小程序实现并不复杂,却总有一种冲动去实现,可能是为了向老祖宗致敬吧!感兴趣的同学可以把它实现的更精致。

指南针效果(晃动真机)

在这里插入图片描述

扫码体验

体验路径:硬件系列>指南针
在这里插入图片描述

指南针代码

Page({
  data: {
    rotate:0,
    area:"东偏北",
    detailArea:90
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    wx.onCompassChange(function (res) {
      console.log(res)
      var rotate = 360 - res.direction.toFixed(0)
      var area = parseInt(rotate/90)
      var detailArea = rotate%90
      that.setData({
        rotate:rotate
      })
      if(area==0){
        that.setData({
          area:"西偏北",
          detailArea: 90-detailArea
        })
      }else if(area==1){
        that.setData({
            area: "西偏南",
            detailArea: detailArea
        })
      } else if (area == 2) {
        that.setData({
          area: "东偏南",
          detailArea: 90-detailArea
        })
      }else{
        that.setData({
          area: "东偏北",
          detailArea: detailArea
        })
      }
    });
  },
  onUnload: function () {
    wx.offCompassChange()
  }
})

wxml

<!--miniprogram/pages/index/pages/compass/compass.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>
  <image style="position:fixed;z-index:5;margin-top:190rpx;width:400rpx;height:400rpx;transform: rotate({{rotate}}deg);" src="./dial.png"></image>
  <image style="position:fixed;z-index:6;margin-top:190rpx;width:400rpx;height:400rpx;" src="./pointer.png"></image>
  <view style="font-size:60rpx;margin-top:450rpx;">{{area}}  {{detailArea}}°</view>
</view>

程序员不易,来个鼓励师

在这里插入图片描述

发布了24 篇原创文章 · 获赞 29 · 访问量 1909

猜你喜欢

转载自blog.csdn.net/WeiHan_Seven/article/details/103872637