我根据重力感应得到手机的方向去动态设置direction也没有效果
一旦全屏后 再修改direction 并不能发生切换横向纵向的效果
只能在全屏之前确定direction的方向值才有效果
onResize: function (res) {
let lastState = 0; // 0为竖屏,1为横屏
let lastTime = Date.now();
wx.startAccelerometer();
wx.onAccelerometerChange((res) => {
const now = Date.now();
if (now - lastTime < 500) { // 500ms检测一次
return;
}
lastTime = now;
let nowState;
const Roll = Math.atan2(-res.x, Math.sqrt(res.y * res.y + res.z * res.z)) * 57.3; // 57.3 = 180 / Math.PI
const Pitch = Math.atan2(res.y, res.z) * 57.3;
console.log('Roll: ' + Roll, 'Pitch: ' + Pitch)
if (Roll > 50) {// 横屏状态
if ((Pitch > -180 && Pitch < -60) || (Pitch > 130)) {
nowState = 1;
} else {
nowState = lastState;
}
} else if ((Roll > 0 && Roll < 30) || (Roll < 0 && Roll > -30)) {
let absPitch = Math.abs(Pitch);
if ((absPitch > 140 || absPitch < 40)) { // 如果手机平躺,保持原状态不变,40容错率
nowState = lastState;
} else if (Pitch < 0) { /*收集竖向正立的情况*/
nowState = 0;
} else {
nowState = lastState;
}
} else {
nowState = lastState;
}
if (nowState !== lastState) {// 状态变化时,触发
lastState = nowState;
if (nowState === 1) {
console.log('change:横屏');
this.setData({
direction: '-90'
})
} else {
console.log('change:竖屏');
this.setData({
direction: '0'
})
}
}
},