用JS完成圖片在窗體中的彈碰效果

一、由於是動態效果這裏就不展示效果圖了,先來簡介編程思路:

1、圖片需要移動

移動方式:將圖片設置爲絕對定位,通過改變絕對定位的位置來達到圖片移動的效果(當然,這只是一種思路,讀者可自行選擇其它方式)

移動方法:需要使用setInterval();;間隔計時器來控制速度和移動效果

2、碰撞

需要獲取自身電腦的屏幕寬度,碰撞其實就是邊界的檢測,如果檢測到在邊界則改變移動方向,

3、圖片的移動方向

圖片移動只有八個方向:左上(左移、右移)、左下(左移、右移)、右上(左移、右移),右下(左移、右移)

二、代碼展示:(代碼中添加了鼠標事件,當鼠標移到圖片時,會停止移動,移開會繼續移動)

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        img{
            position: absolute;
            top:300px;
            left:300px;
            width:100px;
            height: 100px;
        }
    </style>
</head>
<body>
<img src="1.jpg" alt="" id="img1"/>
</body>
<script>
    //獲取圖片節點、由於圖片沒法代碼一起上傳,如果讀者想要看到效果,必須自己添加圖片
    var img2=document.getElementById("img1");
    //獲取屏幕可利用寬度
    var sWidth=window.screen.availWidth;
    //獲取屏幕可利用高度
    var sHeight=window.screen.availHeight;
    //每次移動距離
    var left=10;
    console.log(sWidth-100);
    //true代表的是右方向,false代表的是左方向,默認爲右
    var direction=1;
    //間隔時間爲50ms調用一次move方法
    var time=setInterval(move,50);
    //添加鼠標事件,鼠標移開,繼續使用間隔計時器
    img2.onmouseout=function(){
     fun2()
    };
    //鼠標移入,取消間隔計時器
    img2.onmouseover=function(){
     fun1();
    };
   function fun1(){
       clearInterval(time);
   }
    function fun2(){
        time=setInterval(move,50);
    }
    //移動的方法
    function move(){
        //使用最終樣式獲取當前絕對定位left數值,需要轉int類型
        var x=parseInt(document.defaultView.getComputedStyle(img2,null).left);
        //使用最終樣式獲取當前絕對定位top數值,需要轉int類型
        var y=parseInt(document.defaultView.getComputedStyle(img2,null).top);
        //移動方向左上、左下、右上、右下
        judgeBorder(x,y);
          switch(direction){
              case 1:
                  x+=left;
                  y-=left;
                  break;
              case 2:
                  x+=left;
                  y+=left;
                  break;
              case 3:
                  x-=left;
                  y+=left;
                  break;
              case 4:
                  x-=left;
                  y-=left;
                  break;
          }
        //設置圖片絕對定位位置
        img2.style.left=x+"px";
        img2.style.top=y+"px";

    }
    //邊界判斷
    function judgeBorder(objX,objY){
       if(objY<0&&direction==1||objX<0&&direction==3){
            direction=2;
        }
        if(objX>(sWidth-100)&&direction==2||objY<0&&direction==4){
            direction=3;
        }
        if(objX>(sWidth-100)&&direction==1||objY>(sHeight-200)&&direction==3){
            direction=4;
        }
        if(objY>(sHeight-200)&&direction==2||objX<0&&direction==4){
            direction=1;
        }


    }
</script>
</html>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章