一、简述
小程序实现水平仪效果的方式有很多,主要使用wx.startGyroscope,wx.onAccelerometerChange,官方定义如下
二、示例
三、代码
html:
<view class="gyroscope">
<view class="region" style="background:{{regionBG}};"></view>
<view class="core" style="background:{{backgroundColor}};top: {{top}}rpx;left: {{left}}rpx;"></view>
</view>
css:
.gyroscope{
width: 200rpx;
height: 200rpx;
border-radius: 100rpx;
margin-top: 50rpx;
margin-left: 50rpx;
border: 1rpx solid #000000;
position: absolute;
top: 0rpx;
left: 0rpx;
background: #d1cfcf;
}
.region{
width: 50rpx;
height: 50rpx;
margin-top: 75rpx;
margin-left: 75rpx;
border-radius: 26rpx;
border: 1rpx solid #000000;
}
.core{
width: 30rpx;
height: 30rpx;
border-radius: 15rpx;
position: absolute;
}
js:
data: {
top: 86,
left: 86,
backgroundColor: '#000000',
regionBG: "#f04f4f",
isOnAccelerometerChange: true,
x: 0,
y: 0,
z: 0,
},
onLoad: function (options) {
var that = this
wx.startGyroscope({
interval: "normal",
success: function () {
wx.onAccelerometerChange(function (res) {
if (!that.data.isOnAccelerometerChange) {
return
}
var x = (res.x * 180).toFixed(2)
var y = -(res.y * 180).toFixed(2)
var z = (res.z * 180).toFixed(2)
var top = 86 + Number(y)
var left = 86 + Number(x)
if (top < 0) {
top = 0
}
if (top > 170) {
top = 170
}
if (left < 0) {
left = 0
}
if (left > 170) {
left = 170
}
that.setData({
x: x,
y: y,
z: z,
top: top,
left: left
})
if (top > 76 && top < 105 && left > 76 && left < 109) {
that.setData({
regionBG: "#82ec82",
})
} else {
that.setData({
regionBG: "#f04f4f",
})
}
})
}
})
},
onUnload: function () {
this.setData({
isOnAccelerometerChange: false
})
wx.stopAccelerometer({
})
wx.stopGyroscope({
})
},
代码中onUnload为生命周期中监听页面卸载,停止监听陀螺仪数据和停止监听加速计数据
代码可直接使用!!!