首先, html 提供了2个类似 timer 事件的接口:
setTImeout() // 只执行一次
setInterval( 函数, 间隔) // 其中 间隔 : 1000 表示 1秒 , 反复执行
.js file
// box & ball
var boxx = 20;
var boxy = 30;
var boxwidth = 350;
var boxheight = 250;
var ballrad = 10;
var boxboundx = boxwidth + boxx - ballrad ; //右边界
var boxboundy = boxheight + boxy - 2*ballrad ; //下边界
var inboxboundx = boxx + ballrad; //左边界
var inboxboundy = boxy + 2*ballrad; //上边界
var ballx = 50;
var bally = 60;
var ctx ;
var ballvx = 4; //初始水平速度
var ballvy = 8; //初始垂直速度
//初始化
function init()
{
ctx = document.getElementById("canvas").getContext("2d");
ctx.linewith = ballrad;
ctx.fillStyle = "rgb(200, 0, 50)";
moveball();
setInterval(moveball,100);
}
//移动
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 ; //新坐标 x
var nbally = bally + ballvy ; //新坐标 y
if (nballx > boxboundx){
ballvx = -ballvx ;
nballx = boxboundx ; //如果达到右边界,就象左
}
if (nballx < inboxboundx){
ballvx = -ballvx ;
nballx = inboxboundx ; //如果达到左边界,就象左
}
if (nbally > boxboundy) {
ballvy = -ballvy ; //下边界
nablly = boxboundy ;
}
if (nbally < inboxboundy) {
ballvy = -ballvy ; //下边界
nablly = inboxboundy ;
}
ballx = nballx ;
bally = nbally;
}
//提交,改变速度
function change()
{
ballvx = Number( f.hv.value) ;
ballvy = Number( f.vv.value );
return false ;
}
.html file
<!doctype html>
<html>
<head>
<title>Bouncing Ball with inputs</title>
<script src = "ball.js" type = "text/javascript"></script>
<link rel = "stylesheet" href = "ball.css" type = "text/css" />
</head>
<body onLoad = "init()">
<canvas width = "400" height = "300" id = "canvas" >
Your browser doesn't support HTML5.
</canvas><br />
<form name = "f" id = "f" onSubmit = "return change()">
Horizontal velocity <input type = "number" id = "hv" name = "hv" value = "4" min = "-10" max = "10"/><br />
Vertial velocity <input type = "number" name = "vv" id = "vv" value = "8" min = "-10" max = "10" />
<input type = "submit" value = "Change" />
</form>
</body>
</html>
. css file
#hv : valid {
background : green ;
}
input : invalid {
background : red ;
}
form {
width : 330 px ;
margin : 20 px ;
background-color : brown ;
padding : 20 px ;
}