在JavaScript中,我们可以获得设备的alpha,beta和gamma角度。
window.addEventListener('deviceorientation', (event)=>{
const alpha = event.alpha; // Returns the rotation of the device around the Z axis
const beta = event.beta; // Returns the rotation of the device around the X axis; that is, the number of degrees, ranged between -180 and 180
const gamma = event.gamma; // Returns the rotation of the device around the Y axis; that is, the number of degrees, ranged between -90 and 90
console.log(`alpha: ${alpha}, beta: ${beta}, gamma: ${gamma}`);
}, false);
但是,我想使用这些角度确定设备的基本方向(北,西,东和南)。
我的问题:
是否可以仅使用Alpha角确定设备的基本方向,还是应该同时使用beta和gamma?
如果需要beta和gamma;为了计算基本方向,我应该如何在计算中使用它们,我应该知道什么公式吗?
var heading;
window.addEventListener('deviceorientation', handleOrientation, false);
const handleOrientation = (event) => {
if(event.webkitCompassHeading) {
// some devices don't understand "alpha" (especially IOS devices)
heading = event.webkitCompassHeading;
}
else{
heading = compassHeading(event.alpha, event.beta, event.gamma);
}
};
const compassHeading = (alpha, beta, gamma) => {
// Convert degrees to radians
const alphaRad = alpha * (Math.PI / 180);
const betaRad = beta * (Math.PI / 180);
const gammaRad = gamma * (Math.PI / 180);
// Calculate equation components
const cA = Math.cos(alphaRad);
const sA = Math.sin(alphaRad);
const cB = Math.cos(betaRad);
const sB = Math.sin(betaRad);
const cG = Math.cos(gammaRad);
const sG = Math.sin(gammaRad);
// Calculate A, B, C rotation components
const rA = - cA * sG - sA * sB * cG;
const rB = - sA * sG + cA * sB * cG;
const rC = - cB * cG;
// Calculate compass heading
let compassHeading = Math.atan(rA / rB);
// Convert from half unit circle to whole unit circle
if(rB < 0) {
compassHeading += Math.PI;
}else if(rA < 0) {
compassHeading += 2 * Math.PI;
}
// Convert radians to degrees
compassHeading *= 180 / Math.PI;
return compassHeading;
};
上面的代码受以下链接的启发:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句