游戏二: 随处移动的Ball

首先, 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 ;
}


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值