js小球拋物線效果程式碼例項

admin發表於2017-04-17

分享一段程式碼例項,它實現了小球的拋物線效果。

程式碼相對比較簡單,如果數學過關的話就很好理解了。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
#div, #div1 {
  position: absolute;
  top: 500px;
  width: 100px;
  height: 100px;
  border-radius: 50%;
}
#div {
  left: 300px;
  background: red;
}
#div1 {
  right: 0px;
  background: blue;
}
</style>
<script>
function start() {
  var div = document.getElementById("div");
  var div1 = document.getElementById("div1");
  var lang = (div1.offsetLeft - div.offsetLeft);
  var tops = div1.offsetTop - div.offsetTop;
  var lang1 = Math.sqrt(lang * lang + tops * tops) / 2;
  if (Math.abs(tops / lang1) <= 1) {
    var c = Math.ceil(90 + (90 - Math.abs(Math.asin(tops / lang1) * 180 / Math.PI)));
  } else {
    var c = Math.ceil((90 - Math.abs(Math.asin(lang1 / tops) * 180 / Math.PI)));
  }
  var num = 0;
  var left = 300;
  var timer = setInterval(function() {
    if (num < c) {
      num++;
      var top1 = Math.ceil(Math.sin(num * Math.PI / 180) * lang / 2);
      left = left + lang / c;
      div.style.top = (500 - top1) + "px";
      div.style.left = left + "px";
    } else {
      clearInterval(timer);
    }
 
  }, 1)
}
window.onload = function() {
  var odiv = document.getElementById("div");
  odiv.onclick = function() {
    start()
  }
}
</script>
</head>
<body>
  <div id="div"></div>
  <div id="div1"></div>
</body>
</html>

相關文章