我试图使用Javascript中的HTML5 deviceOrientation事件来旋转图像,当用户围绕他旋转自己的iPhone时。
我使用此代码来检测陀螺仪何时移动:
window.addEventListener('deviceorientation', function (e) {
alpha = e.alpha;
beta = e.beta;
gamma = e.gamma;
}, true);它在iPhone 4+和iPad 2上确实工作得很好,但是在3GS (和更老的iPhones)上没有陀螺仪。这就是为什么我要像这样测试deviceOrientationSupport:
if(window.DeviceOrientationEvent){ // gyroscope support
alert('DeviceOrientationEvent support OK');
} else {
alert('DeviceOrientationEvent support KO');
}我在许多网站或论坛上看到了这段代码,但我的问题是,在IOS 5.0.1下使用我的iPhone 3GS,这个测试表明了我: deviceOrientationSupport OK!
我认为,只有Safari能够处理这些事件时,才会进行此测试检查:
所以我的问题是,是否可以添加一个测试来确定硬件是否可以触发定向事件?
谢谢!
发布于 2014-01-14 15:24:43
在出现了同样的问题后,我还遇到了老款iPad/iPhones的问题,甚至没有在addEventListener上调用这个功能。
因此,我发现下面的方法对我来说更好,并且消除了不受支持的设备通过的任何机会(这是一个装载屏幕,所以它确实需要一个间隔,然后才能完成它的全部测试。所以不是每个人都需要的)。
var _i = null;
var _e = null;
var _c = 0;
var updateDegree = function(e){
_e = e;
}
window.addEventListener('deviceorientation', updateDegree, false);
// Check event support
_i = window.setInterval(function(){
if(_e !== null && _e.alpha !== null){
// Clear interval
clearInterval(_i);
// > Run app
}else{
_c++;
if(_c === 10){
// Clear interval
clearInterval(_i);
// > Redirect
}
}
}, 200);发布于 2012-03-25 00:25:15
我希望这不会太晚,但iOS 4.2+的Safari会在iPhone 3GS (或其他没有陀螺仪的设备)上注册DeviceOrientationEvent,这难道不让人沮丧吗?
说到底,DeviceOrientation不适用于iPhone 3GS。但是,正如有人提到的,DeviceMotionEvent可以工作,但是您必须以与使用陀螺仪的设备不同的方式访问事件数据(我知道这很愚蠢!)
第一步:我在混合中添加了一个变量,以捕获OrientationEvent是否实际使用任何非空数据(就像存在陀螺仪一样)。
var canHandleOrientation;
if (window.DeviceOrientationEvent) {
window.addEventListener("deviceorientation", handleOrientation, false);
}
function handleOrientation(event){
console.log("Orientation:" + event.alpha + ", " + event.beta + ", " + event.gamma);
canHandleOrientation = event; // will be either null or with event data
}现在你知道事件是否真的有陀螺仪数据!所以,如果你想默认其他的东西(即。window.DeviceMotionEvent)您可以使用条件。
if (!canHandleOrientation) {
console.log("There is no gyroscope")
}我在移动Safari上测试了iPhone 3GS (无陀螺仪)、iPad 2(陀螺仪)和Chrome在我的Macbook (陀螺仪)上的测试。似乎很管用。
现在,如果您想获得DeviceMotionEvent数据作为替代,如果定位数据不可用,那么.
if (window.DeviceMotionEvent && !canHandleOrientation) {
window.addEventListener('devicemotion', handleMotion, false);
}
function handleMotion(event){
if(event.acceleration){
//requires a gyroscope to work.
console.log("Motion Acceleration: " + event.acceleration.x + ", " + event.acceleration.y + ", " + event.acceleration.z);
}
else{
//this is for iPhone 3GS or a device with no gyroscope, and includes gravity.
console.log("Motion AccelerationGravity: " + event.accelerationIncludingGravity.x + ", " + event.accelerationIncludingGravity.y + ", " + event.accelerationIncludingGravity.z);
}
}这应该包括你的基础上的大多数设备的webkit浏览器..。我希望如此。还没有在任何Android设备上进行测试。
应该注意,每个事件返回不同的数字,因此您可能需要做一些工作来规范它们。但这是你如何访问它们的基本知识。
如果这有帮助的话请告诉我!
发布于 2012-01-31 11:07:05
虽然3GS上没有陀螺仪,但它完全能够使用内置的加速度计来检测设备方向的变化。iOS从第一个iPhone开始就提供了这种支持。
https://stackoverflow.com/questions/9077325
复制相似问题