DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> HTML基礎知識 >> HTML5教程 >> HTML5 canvas小球碰壁效果
HTML5 canvas小球碰壁效果
編輯:HTML5教程     
html canvas 彈球(模仿)

代碼如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>彈球 何問起</title>
</head>

<body>
    <script type="text/javascript">
          window.onload=function(){
                var boxx=20,
                    boxy=20,
                    boxwidth=350,
                    boxheight=250,
                    ballrad=10,
                    boxboundx=boxx+boxwidth-ballrad,//右
                    boxboundy=boxy+boxheight-ballrad,//下
                    inboxboundx=boxx+ballrad,//左
                    inboxboundy=boxy+ballrad,//上
                    ballx=50,
                    bally=60,
                    ctx,
                    ballvx=4,
                    ballvy=8;
                
                function init(){
                    ctx=document.getElementById("canvas").getContext("2d");
                    ctx.fillStyle="rgb(200,0,50)";
                    moveball();
                    setInterval(moveball,50)
                }

                function moveball(){
                    ctx.clearRect(boxx,boxy,boxwidth,boxheight);
                    moveandcheck();
                    ctx.beginPath();
                    ctx.arc(ballx,bally,ballrad,0,Math.PI*2,true);
                    ctx.fill();
                    ctx.strokeRect(boxx,boxy,boxwidth,boxheight);

                }

                function moveandcheck(){
                    var nballx=ballx+ballvx;
                    var nbally=bally+ballvy;

                    if(nballx > boxboundx){
                       ballvx = -ballvx;
                       nballx = boxboundx;
                    }
                    
                    if(nballx < inboxboundx){
                       nballx = inboxboundx;
                       ballvx = -ballvx;
                    }

                    if(nbally > boxboundy){
                      nbally = boxboundy;
                      ballvy = -ballvy
                    }

                    if(nbally < inboxboundy){
                       nbally = inboxboundy;
                       ballvy = -ballvy;
                    }

                    ballx= nballx;
                    bally= nbally;

                }
                
                init();

          }
    </script>
    <canvas id="canvas" width="400" height="300"></canvas>
</body>
</html>

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved