目是这样的:假设有一定点(400px,300px),通过JavaScript使一个直径20px的圆点以 r=180px 为半径围绕该点做匀速圆周运动。
这个问题的整体实现思想应该是这样的,看到“半径”,“圆周运动”这些字眼首先应该想到的是数学方法,想到sin,cos这些三角函数。有了定点坐标和半径 r,我们可以初始化一个角度 a,通过 400-cos(a)*r 和 300-sin(a)*r 来分别获取圆点相对于定点在角度为 a 时刻的横纵坐标,至于匀速的问题,可以通过 setInterval()方法来处理。
<!DOCTYPE html> <meta charset="utf-8"/> <style> body { margin: 0; background: #2b5996; } #earth { width: 20px; height: 20px; border-radius: 10px; position: absolute; background: url(images/earth.jpg); } #sun{ position: absolute; top: 275px; left: 375px; } </style> <div id="earth"></div> <div id="sun"><img src="images/sun.jpg"></div> <script> var r = 180; var b = document.getElementById("earth"); var t = 0; var xy = {top: 0, left: 0}; setInterval(function(){ xy.top = 300 - Math.sin(t)* r; xy.left = 400 - Math.cos(t)* r; b.setAttribute("style", 'top: ' + xy.top + 'px; left: ' + xy.left + 'px'); t += 0.01; },20); </script>
示例:http://shaozhuang.me/demo/yuanzhou.html