このサンプルではiOS、Androidのブラウザで、スマホを握って振ったときに、文字が切り替わるスクリプトを実装しています。
スマホを上下左右に振ってください
サンプルのスクリプトは以下の通りです。
function ClickRequestDeviceSensor(){ //デバイスのイベントへのリクエスト許可確認 DeviceOrientationEvent.requestPermission().then( function( response ){ if( response === 'granted' ){ //許可されたらイベントを実行する window.addEventListener("devicemotion", devicemotionHandler); //許可ボタンを消す $('#sensorrequest').css( 'display', 'none' ); } }).catch( function( e ){ console.log( e ); }); } $(function(){ if( window.DeviceOrientationEvent ){ if( DeviceOrientationEvent.requestPermission && typeof DeviceOrientationEvent.requestPermission === 'function' ){ var banner = '<div onclick="ClickRequestDeviceSensor();" class="btn" id="sensorrequest">加速度センサーの有効化</div>'; $('#demo_info').append( banner ); }else{ window.addEventListener("devicemotion", devicemotionHandler); } } }); function devicemotionHandler(event) { // X軸 var x = event.acceleration.x; // Y軸 var y = event.acceleration.y; // Z軸 var z = event.acceleration.z; var l = 5; if (x > l) { $('#demo_data span').html('<b>右</b>に振りました!'); } else if (x < -l) { $('#demo_data span').html('<b>左</b>に振りました!'); } else if (y > l) { $('#demo_data span').html('<b>上</b>に振りました!'); } else if (y < -l) { $('#demo_data span').html('<b>下</b>に振りました!'); } else return; }
このサンプルはjQueryを組み合わせて実装しています。