摘要
指南针是中国的四大发明之一,小程序实现并不复杂,却总有一种冲动去实现,可能是为了向老祖宗致敬吧!感兴趣的同学可以把它实现的更精致。
指南针效果(晃动真机)
扫码体验
体验路径:硬件系列>指南针
指南针代码
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>