微信“摇一摇”功能是怎么实现的?
程序员文章站
2024-01-01 13:26:58
...
微信“摇一摇”功能是怎么实现的?
代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" content="width=device-width,user-scalable=no" /> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> #box { width: 200px; height: 200px; background: red; font-size: 20px; color: #fff; } </style> </head> <body> <div id="box"></div> <script type="text/javascript"> toShake(function(){ alert("您进行了摇一摇"); }); function toShake(callBack){ var RANGE = 60;//当用户摇晃的幅度超过这个值,我们认定用户在摇一摇 var isShake = false;//是否进行了摇一摇 var lastX,lastY,lastZ; var lastTime = Date.now(); window.addEventListener('devicemotion', function(e) { var nowTime = Date.now(); //拉开执行的间隔,让iso和安卓的执行频率接近一致 if(nowTime - lastTime < 100){ return; } lastTime = nowTime; var motion = e.accelerationIncludingGravity; var x = motion.x; var y = motion.y; var z = motion.z; if(typeof lastX == "undefined"){//第一次进来还没有上一次的值 lastX = x; lastY = y; lastZ = z; return; } var nowRange = Math.abs(x - lastX) + Math.abs(y - lastY) + Math.abs(z - lastZ); if(nowRange > RANGE){ isShake = true; } //当用户进行了剧烈的摇动,我们就认定用户进行了摇一摇,然后摇晃幅度慢下来之后,执行摇一摇函数 if(isShake&&nowRange < 20){ callBack&&callBack(); isShake = false; } lastX = x; lastY = y; lastZ = z; }); } </script> </body> </html>
以上就是微信“摇一摇”功能是怎么实现的?的详细内容,更多请关注其它相关文章!