JavaScript模拟抛物效果

快乐打工仔 分类:实例代码

JavaScript模拟抛物效果属于前端实例代码,有关更多实例代码大家可以查看

本章节分享一段代码实例,它模拟实现了物体被抛出运行轨迹效果。

并且可以调整相应的参数,代码其实非常简单,其实就是一个数学运算过程。

代码实例如下:

<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<title>前端教程网</title>
<style type="text/css">
*{
  padding:0;
  margin:0;
}
body{
  font-size:13px;
  padding:10px;
}
p{margin:2px;}
.wrap{
  position:relative;
  width:1000px;
  height:550px;
  margin:0 auto;
  border:1px solid #ccc;
  margin-top:50px;
}
#fall{
  width:20px;
  font-size:1px;
  height:20px;
  background:#000;
  position:absolute;
  top:0;
  left:0;
}
</style>
<script type="text/javascript">
function demo(x,y,a,t) {
  var f=document.getElementById('fall');
  var Vx=parseInt(x),
  Vy=parseInt(y),
  g=a,
  t=parseInt(t),
  h=0,l=0,Sx=0,Sy=0;
  var i=setInterval(function(){
    if(f){
      Sx+=Vx*t;
      l=Sx;
      Vy+=g*t;
      h+=Vy*t;
      f.style.left=l+'px';
      f.style.top=h+'px';
      if(h>500||l>900)clearInterval(i);
    }
  },t);
}
window.onload=function(){
  var bt=document.getElementById("bt");
  var Vx=document.getElementById("Vx");
  var Vy=document.getElementById("Vy");
  var a=document.getElementById("a");
  var t=document.getElementById("t");
  bt.onclick=function(){
    demo(Vx.value,Vy.value,a.value,t.value)
  }
}
</script>
</head>
<body>
<h3>模拟重力状态下的抛物运动(假使1px==1mm)</h3>
<p>横向初速度:<input id="Vx" type="text" value="2" />px/ms</p>
<p>纵向初速度:<input id="Vy" type="text" value="-2" />px/ms</p>
<p>重力加速度:<input id="a" type="text" value="0.0098" />px/平方ms</p>
<p>(如果这个加速度是一个随时间变化的值,就能达到其他非匀加速运动的效果了。)</p>
<p>单位时间:<input id="t" type="text" value="10" />(记录运动的时间间隔)</p>
<input id="bt" type="button" value="演示"/>
<div class="wrap">
  <div id="fall">o</div>
</div>
</body>
</html>

JavaScript模拟抛物效果,这样的场景在实际项目中还是用的比较多的,关于JavaScript模拟抛物效果就介绍到这了。

回复

我来回复
  • 暂无回复内容