日期:2014-05-17 浏览次数:20619 次
需求:利用html5实现类似微信的手机摇一摇功能,并实现微博转发
?
难点:
1.监控摇动状态
2.播放摇动后音频
?
难点一,通过html5的DeviceMotionEvent实现,核心代码如下
var SHAKE_THRESHOLD = 3000; var last_update = 0; var x=y=z=last_x=last_y=last_z=0; function init(){ if (window.DeviceMotionEvent) { window.addEventListener('devicemotion',deviceMotionHandler, false); } else{ alert('not support mobile event'); } } function deviceMotionHandler(eventData) { var acceleration =eventData.accelerationIncludingGravity; var curTime = new Date().getTime(); if ((curTime - last_update)> 100) { var diffTime = curTime -last_update; last_update = curTime; x = acceleration.x; y = acceleration.y; z = acceleration.z; var speed = Math.abs(x +y + z - last_x - last_y - last_z) / diffTime * 10000; if (speed > SHAKE_THRESHOLD) { alert("摇动了"); } last_x = x; last_y = y; last_z = z; }?
难点二:代码
function deviceMotionHandler(eventData) { var acceleration =eventData.accelerationIncludingGravity; var curTime = new Date().getTime(); if ((curTime - last_update)> 100) { var diffTime = curTime -last_update; last_update = curTime; x = acceleration.x; y = acceleration.y; z = acceleration.z; var speed = Math.abs(x +y + z - last_x - last_y - last_z) / diffTime * 10000; if (speed > SHAKE_THRESHOLD) { media.setAttribute("src","http://192.168.1.106/weixin_yaoyiyao.mp3"); media.load(); media.play(); } last_x = x; last_y = y; last_z = z; } } <audio style="display:hide" id="musicBox" preload="metadata" controls src="http://192.168.1.106/weixin_yaoyiyao.mp3" autoplay="false" > </audio>
?
?
此两种方式为目前唯一方式
?
但只能适用少数浏览器
?
ios平台,safari,可以监控摇动,但无法通过js直接播放音频
android平台,android os 自带浏览器无法监控摇动,但是第三方浏览器,opera,chrome均能监控摇动,也可以通过js直接播放音频
?
?
总之目前,用手机实现摇一摇功能,不能完全满足要求
?
?