我正在尝试使用智能手机中的陀螺仪来控制 HTML 元素。我设法提取陀螺仪的值(Alpha、Beta 和 Gamma),但无法将其转换为能够按照我想要的方式操纵对象的方式。
设备的起始位置为横向模式,位于用户正前方;就像平板电视一样。该设备将插入 Google Cardboard 查看器中。
所附图片解释了我想要实现的目标。
- CSS 中的对象“左”百分比。
- 从左向右旋转头部时的设备方向
我似乎找不到一种方法将旋转运动的范围“转换”为 0 到 100% 之间的百分比值。
例如:
- 如果我稍微向左看,Alpha 值约为 22/23,左侧百分比应约为 25。
- 如果我稍微向右看,Alpha 值约为 338/337,左侧百分比应约为 75。
你们能帮我一下吗?
最诚挚的问候,
彼得
最佳答案
您的理解有点错误,请在此处查看更多详细信息:https://developer.mozilla.org/en-US/docs/Web/API/Detecting_device_orientation
- The DeviceOrientationEvent.alpha value represents the motion of the device around the z axis, represented in degrees with values ranging from 0 to 360.
- The DeviceOrientationEvent.beta value represents the motion of the device around the x axis, represented in degrees with values ranging from -180 to 180. This represents a front to back motion of the device.
- The DeviceOrientationEvent.gamma value represents the motion of the device around the y axis, represented in degrees with values ranging from -90 to 90. This represents a left to right motion of the device.
东西向和南北向位置,注意 z 未在 x y 轴中表示
- x - beta: Represents the axis from West to East
- y - gamma: Represents the axis from South to North
- z - alpha: Represents the axis perpendicular to the ground
继续使用 CSS props:
- x - beta: Represents top property
- y - gamma: Represents left property
- z - alpha: not necessary usable in a 2d css but you can use it for zoom or angle to a 2d shape, div or image.
对于 left 属性,您应该使用 gamma 设备方向,这是一个很好的示例(砌体级别 gamma),其中使用百分比形式的 left css 属性来定位级别点。
尝试在移动设备上填写表单:https://jsfiddle.net/f7tdrb87/
百分比计算:
function precentageIn180(value)
{
var percent = ((value * 100) / 180).toFixed(0);
return percent;
}
并且区间 [-90, 90] 转置为 [0, 180],其中 0 == 0% 且 180 == 100%,因此 event.gamma + 90
用于所有时间;
var point = document.querySelector('.point');
var masonryLevel = document.querySelector('.masonry-level-gama');
var log = document.querySelector('.log');
var maxY = masonryLevel.clientWidth - point.clientWidth;
function precentageIn180(value)
{
var percent = ((value * 100) / 180).toFixed(0);
return percent;
}
function handleOrientation(event) {
var y = event.gamma; // In degree in the range [-90,90]
log.innerHTML = "gamma: " + y + "\n";
//value on gama is [-90, 90] => but we want to have between [0, 180], to be possiblle to compute 100% of 180
y += 90;
var percent = precentageIn180(y);
log.innerHTML += "gamma percent: " + percent + "\n";
point.style.left = (percent + "%");
}
window.addEventListener('deviceorientation', handleOrientation);
.masonry-level-gama {
position: relative;
width : 190px;
height: 40px;
border: 1px solid #CCC;
border-radius: 10px;
}
.point {
position: absolute;
top : 10px;
left : 50%;
margin-left: -10px;
width : 20px;
height: 20px;
background: blue;
border-radius: 100%;
}
<div class="masonry-level-gama">
<div class="point"></div>
</div>
<pre class="log"></pre>
关于jQuery 设备方向范围转换为 0 到 100 之间的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37814531/