我想在我的网页上显示一杯水。我想当用户旋转他们的设备时,水应该自然地下到地平线。
window.addEventListener('deviceorientation', this.handleOrientation.bind(this));
handleOrientation(orientData) {
var absolute = orientData.absolute;
var alpha = orientData.alpha;
var beta = orientData.beta;
var gamma = orientData.gamma;
}
从上面的api,我可以获得这四个角度信息。但是我不知道如何从设备到地平线获得当前角度,这样我就可以将水设置为旋转到地平线。
答案 0 :(得分:1)
根据来自MDN的the example和trigonometry的limitations,我能够提出以下代码。我在Android上的Chrome上成功测试了这一点,但很遗憾,Firefox不会触发deviceorientation
事件(即使MDN上的示例也不起作用)。
另一个警告是屏幕方向,即如果您的设备当前处于横向模式。某些浏览器不支持旧API(window.orientation
),新API(screen.orientation
)尚未完全实现且行为不同。
var watercup = document.querySelector('#watercup');
function handleOrientation(event) {
var x = event.beta; // In degree in the range [-180,180], x, 'front to back'
var y = event.gamma; // In degree in the range [-90,90], y, 'left to right'
var z = event.alpha; // 0-360, z, compass orientation
// coord 1: 0,0
// coord 2: x,y
// calculate the angle
var rad = Math.atan2(y, x);
var deg = rad * (180 / Math.PI);
// take into account if phone is held sideways / in landscape mode
var screenOrientation = screen.orientation || screen.mozOrientation || screen.msOrientation;
// 90, -90, or 0
var angle = screenOrientation.angle || window.orientation || 0;
deg = deg + angle;
watercup.innerHTML = Math.round(deg);
watercup.style.transform = 'rotate('+ -deg +'deg)';
}
window.addEventListener('deviceorientation', handleOrientation);
#watercup {
border:2px solid #aaa;
width:100px;
height:200px;
background: linear-gradient(to bottom, white 20%, lightblue 20%, blue);
margin: 20px auto;
}
<div id="watercup"></div>