本文实例讲述了JS小球抛物线轨迹运动的两种实现方法。分享给大家供大家参考,具体如下:
js实现小球抛物轨迹运动的大致思路:
1、用setInterval()方法,进行间隔性刷新,更新小球位置,以实现动态效果
2、绘制小球和运动区域,运动区域可通过flex布局实现垂直居中
3、用物理公式S(y)=1/2*g*t*t,S(x)=V(x)t来计算路径
现确定V(x)=4m/s,刷新的时间间隔设置为0.1s。原本px和米之间的转换,不同尺寸转换不同,本例采用17寸显示器,大约1px=0.4mm。但浏览器太小,因此只能模拟抛物线轨迹,本例将px和米之间缩成100倍。
第一种:通过border-radius绘制小球
思路:用border-radius: 50%绘制小球,给小球设置relative,每次计算小球当前位置,赋给top和left。计算运动轨迹时,可用变量自增计算setInterval调用次数,每次是0.1s,这样可计算总时间。代码如下:
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title></title>
<style type="text/css">
/*给body进行flex布局,实现垂直居中*/
body {
min-height: 100vh;/*高度适应浏览器高度*/
display: flex;
justify-content: center;/*水平居中*/
align-items: center;/*垂直居中*/
font-size: 20px;
font-weight: bold;
}
/*设置运动区域*/
#bg {
width: 600px;
height: 600px;
border: 2px solid #e0e0e0;
border-radius: 4px;/*给div设置圆角*/
padding: 20px;
}
/*生成小球,并定义初始位置*/
#ball {
border-radius: 50%;/*可把正方形变成圆形,50%即可*/
background: #e0e0e0;
width: 60px;
height: 60px;
position: relative;
top: 30px;
left: 30px;
}
button {
width: 80px;
height: 30px;
border-radius: 4px;
color: #fff;
background: #AA7ECC;
font-size: 20px;
font-weight: bold;
margin-left: 20px;
}
</style>
</head>
<body>
<div id="bg">
此时水平速度为:4<button onclick="start()">演示</button>
<div id="ball"></div>
</div>
<script type="text/javascript">
function start(){
var x,y,k=1,t;
//x是水平方向移动路径;y是垂直方向的;k记录次数,可与0.1相乘得时间;t记录setInterval的返回id,用于clearInterval
t = setInterval(function(){
x = 30+0.1*k*4*100;
//S(x)=S(0)+t*V(x),100是自定义的米到px转换数
y = 30+1/2*9.8*0.1*k*0.1*k*100;//S(y)=S(0)+1/2*g*t*t
var j = document.getElementById("ball");
//通过修改小球的top和left,修改小球的位置
j.style.top = y;
j.style.left = x;
k++;//每次调用,k自增,简化计算
if(x>480||y>480){
clearInterval(t);//小球达到边界时,清除setInterval
}
},100);//每0.1s调用一次setInterval的function
}
</script>
</body>
</html>
内容版权声明:除非注明,否则皆为本站原创文章。

