HTML5實現簡單圓周運動示例


一、使用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>

順時針旋轉效果:

更多:

HTML5 <a>標簽download 屬性

html5 拖放---(二)轉

瀏覽器記住密碼、瀏覽器記住密碼表單自動加載


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM