これが遅すぎないことを願っていますが、iOS 4.2+ の Safari が iPhone 3GS (またはジャイロスコープのない他のデバイス) で DeviceOrientationEvent を登録するのはイライラしませんか?
要するに、DeviceOrientation は iPhone 3GS では機能しません。しかし、誰かが言ったように、DeviceMotionEvent は機能しますが、ジャイロスコープを備えたデバイスの場合とは異なる方法でイベント データにアクセスする必要があります (ばかげたことです!)。
最初のステップ: ミックスに変数を追加して、OrientationEvent が実際に null 以外のデータで発火しているかどうかをキャプチャします (ジャイロスコープがある場合と同様)。
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")
}
iPhone 3GS (ジャイロスコープなし) と iPad 2 (ジャイロスコープ) の Mobile Safari、および Macbook Pro (ジャイロスコープ) の Chrome でこれをテストしました。うまくいくようです。
ここで、Orientation データが利用できない場合に代わりに 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 デバイスでテストしたことはありません。
各イベントは異なる数値を返すため、それらを正規化するために何らかの作業が必要になる場合があることに注意してください。しかし、これはアクセス方法の基本です。
これが役立つかどうか教えてください!