js html5 仿微信摇一摇

时间:2021-08-31 03:15:30

看微信摇一摇之后忽然想知道他是怎么写的。于是就在网上查了一些资料,有些是借鉴别人的。大家共同学习啊

先放代码

<body onload="init()">
<p>用力摇一摇你手机</p>
<audio style="display:hiden;width:0px; height:0px;" id="musicBox" preload="metadata" controls src="swiper/music/default.mp3"> <script>
init();
var SHAKE_THRESHOLD = 3000;//定义一个摇动的值
var last_update = 0;//定义一个变量保存上次更新的时间 var x = y = z = last_x = last_y = last_z = 0;//定义xyz记录三个轴的数据以及上一次出发的时间
function init() {
if (window.DeviceMotionEvent) {
window.addEventListener('devicemotion', deviceMotionHandler, false);
} else {
alert('not support mobile event');
}
}
function deviceMotionHandler(eventData) {
var meda01=document.getElementById('musicBox');
var acceleration = eventData.accelerationIncludingGravity;//含重力加速度
var curTime = new Date().getTime();//获取当前时间
if ((curTime - last_update) > 100) {//curTime - last_update 是固定时间段
var diffTime = curTime - last_update;
last_update = curTime;
//alert('last_update='+last_update)
x = acceleration.x;
//alert('x='+x)
y = acceleration.y;
//alert('y='+y)
z = acceleration.z;
//alert('z='+z)
var speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000;
//alert('speed='+speed) abs是取绝对值
if (speed > SHAKE_THRESHOLD) {
alert("摇动了+中大奖了,就是不知道有没有声音");
media.setAttribute("src", "swiper/music/default.mp3");
//setAttribute 锁定元素。此方法不能通过document对象调用,只能通过元素节点对象调用他
//例如,你可以把他与getElementByTagName()方法结合起来,去查询每个<p>元素的title属性
//var txt=document.getElementsByTagName('p')
//for(var i=0;i<text.length;i++){
//alert(txt[i].getAttribute('title'))
//}
//
//
//
//
media.load();
media.play();
meda01.play();
}
last_x = x;
last_y = y;
last_z = z;
}
}

html5 的 deviceorientation 他将底层的方向传感器和运动传感器进行了高级封装。提供了dom事件的支持。这个特性包括两种事件:

1.deviceOrientation:封装了方向传感器数据的事件,可以获取手机静止状态下的方向数据,例如手机所处角度、方位、朝向等。

2.deviceMotion:封装了运动传感数据的事件,可以获取手机运行状态下的运动加速度等数据。使用它我们能够很容易的实现重力感应、指南针等有趣的功能

3.DeviceMotionEvent(设备运动事件)返回设备有关于加速度和旋转的相关信息。加速度的数据讲包含3个轴:x,y,z。该事件会返回两个属性,accelerationIncludingGravity(含重力的加速度)和acceleration(加速度)。

 1.【代码】监听运动传感事件

if(window.DeviceMotionEvent){
window.addEventListener('devicemotion',deviceMotionHandler,false);
}
 2.[代码]获取含重力的加速度

function deviceMotionHandler(eventData){
 var acceleration=eventData.accelerationIncludingGravity;
 }