javaScript实现网页版的弹球游戏

2022-07-22,,,

利用javescript对象以及方法实现的网页弹球游戏,供大家参考,具体内容如下

<!doctype html>
<html>
<head>
<tilie>呼呼哈嘿的网页弹球</title>
</head>
<body>
<canvas id="canvas"width="400"height="400"></canvas>
 <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script>
var canv=document.getelementbyid("canvas");
var ctx=canv.getcontext("2d");
//创建一个小球对象
var ball={
x: 100,
y: 100,
xspeed: -5,
yspeed: -5
};
//定义绘制小球的方法
ball.draw=function(){
  ctx.beginpath();
  ctx.arc(this.x,this.y,10,0,math.pi*2,false);
  ctx.fill();
};
//定义小球运动的方法
ball.move=function(){
 this.x =this.x+this.xspeed;
 this.y =this.y+this.yspeed;
};
//边界判断
ball.checkcanvas=function(panelstart,panelend)
{
 if(this.x<0||this.x>400)
 this.xspeed=-this.xspeed;
if(this.y<0)
 this.yspeed=-this.yspeed;
if(this.y>390){
 if(this.x>panelstart && this.x<panelend)
   this.yspeed=-this.yspeed;
 else{
  alert("game over!!!");
  this.x= 50;
 this.y=100;
}
}
};
//定时功能使得小球动起来
setinterval(function()
{
  ctx.clearrect(0,0,400,400);
  ball.draw();
  panel.draw();
  ball.move();
  ball.checkcanvas(panel.x,panel.x+panel.xsize);
  ctx.strokerect(0,0,400,400);
},30);  //定时函数,每30ms执行一次大括号中的代码;
//创建挡板的对象;
var panel ={
 x:200,
 y:390,
 xsize: 50,
 ysize: 5
};
//挡板移动方法
panel.draw=function(){
    ctx.fillrect(this.x,this.y,this.xsize,this.ysize);
};
//利用jquery实现按键交互;
$("body").keydown(function(event)
{
console.log(event.keycode);
if(event.keycode==37){
  panel.x=panel.x-5;
 if(panel.x<0){
panel.x=0;
   }
  }
if(event.keycode==39){
 panel.x=panel.x+5;
if(panel.x>400-50){
panel.x=350;
    }
  }
} 
);
</script>
</body>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

《javaScript实现网页版的弹球游戏.doc》

下载本文的Word格式文档,以方便收藏与打印。