javascript实现旋转罗盘完整代码

本代码实现罗盘定时按随机数转过若干角度。


<!DOCTYPE html>

<html lang="zh-CN">
    <head>
        <meta charset="utf-8" />
        
        <title>指南针</title>

        <meta name="description" content="User page" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <style>
        .div {
            width:163px;
            height:163px;
            position:absolute;
            top:100px;
            left:300px;
        }
        
        .bg1 {
            background-image: url("./bg1.png");
        }
        
        .bg2 {
        }
        
        img_compass {
            transform:rotate(0deg);
            -ms-transform:rotate(45deg);     /* IE 9 */
            -moz-transform:rotate(0deg);     /* Firefox */
            -webkit-transform:rotate(0deg); /* Safari 和 Chrome */
            -o-transform:rotate(0deg);     /* Opera */
        }
        </style>
    </head>

    <body>
    
    <div class="div bg1">
        <div class="bg2">
            <img src="./bg2.png" id="compass" width="163px" height="163px" />
        </div>
    </div>

    <script type="text/javascript">
        var curDegree = 0;
        var targetDegree = 0;  /*change the degree*/
       /* var targetDegree = 361;*/
        function rotateTo (degree){
            var target = document.getElementById("compass");
            target.style.transform = "rotate(" + degree + "deg)";
            target.style.webkitTransform = "rotate(" + degree + "deg)";
            target.style.OTransform = "rotate(" + degree + "deg)";
            target.style.MozTransform = "rotate(" + degree + "deg)";
           curDegree = degree;           
          
        }
        //随机数产生函数
        function ran_num(){
            var number = Math.random();
            number = Math.ceil(number * 360);
            return(number);
            }
        function rotate(degree){
            var acc = 5;
            var gap = degree - curDegree;
            
            if (gap > 0) {
                var delta = gap / acc;
                //alert(delta);
                if(delta > 0.05){
                    rotateTo(curDegree + delta);
                    setTimeout(function () {
                        rotate(degree);
                    }, 10);
                }else rotateTo(degree);
            }
              if (gap < 0) {
                var delta = gap / acc;
                //alert(delta);
                if(delta < (-0.05)){
                    rotateTo(curDegree + delta);
                    setTimeout(function () {
                        rotate(degree);
                    }, 10);
                }else rotateTo(degree);
            }
            //else if(gap==0){
            //    targetDegree = targetDegree + curDegree;    
            //    }
        }
        
        setInterval("targetDegree=ran_num();rotate(targetDegree);",1000);
    </script>
 
    </body>
</html>








展开阅读全文

没有更多推荐了,返回首页