图片与墙碰撞

来源:互联网 发布:淘宝服装网店经营技巧 编辑:程序博客网 时间:2024/04/28 16:09
<html>
<head>
<title>Bouncing Ball with inputs</title>
<style>
form{
width:330px;
margin:20px;
background-color:green;
padding:20px;
}
</style>
<script type="text/javascript">
var boxx=20;//盒子左上角的x位置
var boxy=30;//盒子左上角的y位置
var boxwidth=350;//盒子宽度
var boxheight=250;//盒子高度
var ballrad=20;//球的半径
var boxboundx=boxx+boxwidth-ballrad;//右边界
var boxboundy=boxy+boxheight-ballrad;//下边界
var inboxboundx=boxx+ballrad;//左边界
var inboxboundy=boxy+ballrad;//上边界
var ballx=50;//球的初始x位置
var bally=60;//球的初始y位置
var ctx;
var ballvx=4;//初始水平位移
var ballvy=8;//初始垂直位移
var img=new Image();;
img.src="r.jpg";
var grad;//grad变量,在init中调用
var color;//用于建立梯度grad
var hue=[
[255,0,0],//红
[255,255,0],//黄
[0,255,0],//绿
[0,255,255],//青
[0,0,255],//蓝
[255,0,255]//紫
];


function init(){
var h;
ctx=document.getElementById('canvas').getContext('2d');
grad=ctx.createLinearGradient(boxx,boxy,boxx+boxwidth,boxy+boxheight);
for(h=0;h<hue.length;h++){
color='rgb('+hue[h][0]+','+hue[h][1]+','+hue[h][2]+')';
grad.addColorStop(h*1/6,color);
}
ctx.fillStyle=grad;
ctx.lineWidth=ballrad;
moveball();//第一次调用moveball来移动、检查和显示球
setInterval(moveball,60);//建立定时事件
}


function moveball(){
ctx.clearRect(boxx,boxy,boxwidth,boxheight);//清除盒子,包括球
moveandcheck();
ctx.drawImage(img,ballx-ballrad,bally-ballrad,2*ballrad,2*ballrad);//对象左上角的位置,宽度和高度是球半径的2倍
ctx.fillRect(boxx,boxy,ballrad,boxheight);//绘制左墙
ctx.fillRect(boxx+boxwidth,boxy,ballrad,boxheight);//绘制右墙
ctx.fillRect(boxx,boxy,boxwidth,ballrad);//绘制上墙
ctx.fillRect(boxx,boxy+boxheight-ballrad,boxwidth,ballrad);//绘制下墙
}


function moveandcheck(){
var nballx=ballx+ballvx;//设置试探的下一个x位置
var nbally=bally+ballvy;  
if(nballx>boxboundx){
ballvx=-ballvx;
nballx=boxboundx;
}
if(nballx<inboxboundx){
nballx=inboxboundx;
ballvx=-ballvx;
}
if(nbally>boxboundy){
ballvy=-ballvy;
nbally=boxboundy;
}
if(nbally<inboxboundy){
nbally=inboxboundy;
ballvy=-ballvy;
}
ballx=nballx;
bally=nbally;
}


function change(){
ballvx=Number(f.hv.value);
ballvy=Number(f.vv.value);
return false;//返回false,确保不重新加载页面
}
</script>
</head>
<body onload="init();">
<canvas id="canvas" width="400" height="300">
Your browser doesn't support the HT
</canvas>
<br/>
<form name="f" id="f" onSubmit="return change();">
Horizontal velocity<input name="hv" id="hv" value="4" type="number" min="-10" max="10"></input>
<br/>
Vertical velocity<input name="vv" id="vv" value="8" type="number" min="-10" max="10"></input>
<input type="submit" value="CHANGE"></input>
</form>
</body>
</html>
0 0
原创粉丝点击