javaScript實現(xiàn)網(wǎng)頁版的彈球游戲
更新時間:2021年07月28日 11:32:31 作者:晚安小點點
這篇文章主要為大家詳細(xì)介紹了javaScript實現(xiàn)網(wǎng)頁版的彈球游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
利用javeScript對象以及方法實現(xiàn)的網(wǎng)頁彈球游戲,供大家參考,具體內(nèi)容如下
<!DOCTYPE html>
<html>
<head>
<tilie>呼呼哈嘿的網(wǎng)頁彈球</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");
//創(chuàng)建一個小球?qū)ο?
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); //定時函數(shù),每30ms執(zhí)行一次大括號中的代碼;
//創(chuàng)建擋板的對象;
var panel ={
x:200,
y:390,
xSize: 50,
ySize: 5
};
//擋板移動方法
panel.draw=function(){
ctx.fillRect(this.x,this.y,this.xSize,this.ySize);
};
//利用jquery實現(xiàn)按鍵交互;
$("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>

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
JS實現(xiàn)websocket長輪詢實時消息提示的效果
這篇文章主要介紹了JS實現(xiàn)websocket長輪詢實時消息提示的效果的相關(guān)資料,需要的朋友可以參考下2017-10-10
'webpack-dev-server'?不是內(nèi)部或外部命令也不是可運行的程序?或批處理文件的最
這篇文章主要介紹了'webpack-dev-server'?不是內(nèi)部或外部命令也不是可運行的程序?或批處理文件的最新解決方法,文中給大家補(bǔ)充介紹了webpack-dev-server的介紹與用法,需要的朋友可以參考下2023-02-02
window.addeventjs事件驅(qū)動函數(shù)集合addEvent等
addEvent()、removeEvent()、handleEvent()、fixEvent()[2008-02-02
淺析Javascript中bind()方法的使用與實現(xiàn)
下面小編就為大家?guī)硪黄獪\析Javascript中bind()方法的使用與實現(xiàn)。小編覺得挺2016-05-05
uniapp獲取當(dāng)前位置及檢測授權(quán)狀態(tài)效果
這篇文章主要介紹了uniapp獲取當(dāng)前位置及檢測授權(quán)狀態(tài)效果,本文通過示例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-04-04

