grav html5,如何通过html5实现摇一摇的功能

原理:使用DeviceMotion实现,关于DeviceMotion介绍可以查看

https://developer.mozilla.org/en-US/docs/Web/Reference/Events/devicemotion

通过DeviceMotionEvent,可以获得accelerationIncludingGravity的x,y,z属性,根据x,y,z属性的变化来判断设备是否有摇一摇的事件发生。

accelerationIncludeingGravity说明:

The acceleration of the device. This value includes the effect of gravity, and may be the only value available on devices that don’t have a gyroscope to allow them to properly remove gravity from the data.

代码如下:

html5使用DeviceMotionEvent实现摇一摇

.center{position:absolute; width:640px; height:480px; left:50%; top:50%; margin-left:-320px; margin-top:-240px; line-height:480px; text-align:center; font-size:100px; }

.normal{background:#000000;}

.normal .txt{color:#FFFFFF;}

.doing{background:#FF0000;}

.doing .txt{color:#FFFF00;}

请执行摇一摇

var doing = 0; // 判断是否在动画显示中

var speed = 23; // 定义摇动的速度数值

var lastx = 0; var lasty = 0; var lastz = 0; function handleMotionEvent(event) {

var x = event.accelerationIncludingGravity.x; var y = event.accelerationIncludingGravity.y; var z = event.accelerationIncludingGravity.z; if(doing==0){ if(Math.abs(x-lastx)>speed || Math.abs(y-lasty)>speed){

doing = 1;

show();

}

}

lastx = x;

lasty = y;

lastz = z;

} function show(){

document.getElementById('mybody').className = 'doing';

document.getElementById('txt').innerHTML = '执行了摇一摇';

setTimeout(function(){

doing=0;

document.getElementById('mybody').className='normal';

document.getElementById('txt').innerHTML = '请执行摇一摇';

},3000);

}

window.addEventListener("devicemotion", handleMotionEvent, true);

本文介绍了通过html5实现摇一摇的功能,更多相关内容请关注php中文网。

相关推荐:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值