DIV CSS 佈局教程網

JavaScript 控制元素做圓周運動的實作原理
編輯:關於JavaScript     

要讓一個 DOM 元素沿著圓周跑,核心數學其實很單純:用正弦與餘弦把角度換算成座標偏移量,再用 setInterval 持續更新。以下範例讓一個紅色小方塊繞著時鐘背景轉圈,同時在按鈕上顯示目前時間。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "https://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>圓周運動</title>
<script type="text/javascript">
window.onload = function(){
  var ctrlBtn = $id("ctrl");
  var isMove = true;
  oM = null;
  ctrlBtn.onclick = function(){
    if (isMove) {
      moveByCircle();
    } else {
      clearInterval(oM);
    }
    isMove = !isMove;
  }
}

function moveByCircle(){
  var bacL = parseInt($id("clockBac").style.left);
  var bacT = parseInt($id("clockBac").style.top);
  var bacW = parseInt($id("clockBac").style.width);
  var bacH = parseInt($id("clockBac").style.height);

  // 以背景圖片的中心作為圓心
  var initL = bacL + bacW / 2;
  var initT = bacT + bacH / 2;

  var step = 0;
  var r = 65;                                  // 半徑

  $id("tt").style.left = initL + "px";
  $id("tt").style.top  = initT + "px";

  var l = parseInt($id("tt").style.left);
  var t = parseInt($id("tt").style.top);

  oM = window.setInterval(function(){
    if (step == 360) { step = 1; }
    // 關鍵:正弦給水平位移,餘弦給垂直位移
    $id("tt").style.left = (l + r * Math.sin(step)) + "px";
    $id("tt").style.top  = (t - r * Math.cos(step)) + "px";
    step += 3.14 / 30;

    var d  = new Date();
    var hh = d.getHours();
    var mm = d.getMinutes();
    var ss = d.getSeconds();
    $id("ctrl").value = hh + ":" + mm + ":" + ss;
  }, 1000);
}

function $id(id){ return document.getElementById(id); }
</script>
</head>
<body>
<div id="tt" style="width:10px;height:10px;background:red;position:absolute;top:105px;left:130px;"></div>
<input type="button" id="ctrl" style="width:100px;position:absolute;"/>
<img src="../img/clock.jpg" id="clockBac"
     style="width:200px;height:200px;top:100px;left:100px;position:absolute;z-index:-999"/>
</body>
</html>

原理說明

圓的參數方程式是 x = r·sin(θ)、y = r·cos(θ)。程式每輪把角度 step 遞增,重新計算元素的 left 與 top,視覺上就形成圓周運動。垂直方向要減去 r * Math.cos(step),是因為螢幕座標的 Y 軸向下,而數學座標的 Y 軸向上。

這裡有兩個可以改進的地方值得注意:一是 step += 3.14 / 30 混用了「角度」與「弧度」概念,實際上 Math.sin 吃的是弧度,而遞增量寫成小數、重置條件卻是 360,邏輯並不嚴謹;若改成 step += 0.1 並在 step >= 2 * Math.PI 時歸零,行為會更直觀。二是 setInterval 間隔 1000 毫秒配合每秒 0.1 弧度的步長,轉一圈需要一分多鐘,速度偏慢;想要更順滑的動畫,通常會改用 requestAnimationFrame。

希望本文對你的 JavaScript 動畫開發有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved