JAVAScript簡單動畫~移動方塊~setInterval()~碰到邊緣彈回

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>移動方塊</title>
    <section>
    <canvas id="canvas" width="600" height="600"></canvas></section>
    </head>
    <body>
        <script type="text/javascript">
            function draw (id){            
            //獲取畫布id
            var canvas =document.getElementById(id);
            if(canvas==null)
            return false;
            //獲取上下文
            var  cxt =canvas.getContext("2d");            
            var interval=setInterval(function(){move(cxt);},10);
            }
            var x=100;//矩形的x座標
            var y=100;//矩形的y座標
            var mx=0;//值爲0向右,值爲0向左
            var my=0;//值爲0向下,值爲0向上
            var ml=10;//移動的長度
            var w=20;//矩形的寬
            var h=20;//矩形的高
            var cw=600;//畫布的寬
            var ch=600;//畫布的高
           
           function move(cxt){               
               cxt.clearRect(0,0,600,600);//在給定的矩形內清除所有的像素爲透明
               cxt.fillStyle="#EEEEFF";//把填充顏色設置爲指定的顏色
               cxt.fillRect(0,0,600,600);//是用當前的填充風格填充指定的區域
               cxt.fillStyle="red";//把矩形設置爲紅色
               cxt.fillRect(x,y,w,h);//繪製矩形
           //判斷是否到達邊緣
           if(mx==0){
                   x=x+ml;//x座標加上移動長度
                   if(x>cw-w){
                       mx=1;
                   }
               }else{
                   x=x-ml;
                   if(x<=0){
                       mx=0;                       
                   }
               }
                    if(my==0){
                   y=y+ml;
                   if(y>ch-h){
                       my=1;
                   }
               }else{
                   y=y-ml;
                   if(y<=0){
                       my=0;                       
                   }
               }
           }
           window.addEventListener("load",draw("canvas"),true);
        </script>
    </body>
</html>

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