html canvas 弹球(模仿)

时间:2023-03-09 18:25:46
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>