Document

Home  >  Article  >  Web Front-end  >  How is the WeChat “Shake” function implemented?

How is the WeChat “Shake” function implemented?

零下一度
零下一度Original
2017-07-19 17:32:492520browse

How is the "Shake" function of WeChat implemented?

The code is as follows:

<!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(&#39;devicemotion&#39;, 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>


The above is the detailed content of How is the WeChat “Shake” function implemented?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn