一、使用JS實現圓周運動
根據指定圓心、半徑,在定時器中移動固定的弧度,重繪圓圈的位置
源代碼:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .circle{ width:20px; height:20px; background:blue; border-radius:50%; position: absolute; } .rectangle{ width:300px; height:300px; border:1px solid red; position: relative; } </style> </head> <body> <div class="rectangle"> <div class="circle"></div> </div> <script src="../Js/jquery-1.11.3.min.js"></script> <script> (function(){ //圓周運動js實現 var circle=$('.circle'); var rect=$('.rectangle'); //獲取半徑和圓心 var centerX=(rect.width()-circle.width())/2; var centerY=(rect.height()-circle.height())/2; var radius=centerX; //時間遞進 var times=0; //重繪位置 function reset(){ times+=1; var hudu=(2*Math.PI/360)*times; //console.info(hudu); var x=centerX+Math.sin(hudu)*radius; var y=centerY+Math.cos(hudu)*radius; circle.css({ left:x, top:y }); //調用自己 requestAnimationFrame(reset); } //啟動定時器 requestAnimationFrame(reset); })(); </script> </body> </html>
逆時針旋轉效果:
二、使用CSS實現圓周運動
使用transform的rotate方法實現旋轉,需要重點設置一下圓心位置
源代碼:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> @keyframes run{ from{ transform:rotate(0deg); } to{ transform:rotate(360deg); } } .circle{ width:20px; height:20px; background:blue; border-radius:50%; position: absolute; transform-origin:110px 110px; animation:run 5s linear infinite; left:40px; top:40px; } .rectangle{ width:300px; height:300px; border:1px solid red; position: relative; } </style> </head> <body> <div class="rectangle"> <div class="circle"></div> </div> </body> </html>
順時針旋轉效果:
更多: