這篇文章將為大家詳細講解有關canvas實現彈球的案例,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
效果

代碼
<!DOCTYPE html>
<html lang="zh_CN">
<head>
<meta charset="UTF-8">
<title>彈球</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script>
// 全局canvas
let canvas = document.getElementById("canvas");
let context = canvas.getContext("2d");
// 彈球對象
class Ball{
x = 100;
y = 40;
xSpeed = -2;
ySpeed = -2;
constructor(){};
getX(){
return this.x;
}
getY(){
return this.y;
}
setX(x){
this.x = x;
}
setY(y){
this.y = y;
}
getXSpeed(){
return this.xSpeed;
}
setXSpeed(xSpeed){
this.xSpeed = xSpeed;
}
getYSpeed(){
return this.ySpeed;
}
setYSpeed(ySpeed){
this.ySpeed = ySpeed;
}
// 繪制小球的方法
draw = () => {
context.beginPath();
context.arc(this.x, this.y, 10, 0, Math.PI * 2, false);
context.strokeRect(0, 0, 400, 400);
context.fill();
};
// 移動操作
move = () => {
this.x = this.x + this.xSpeed;
this.y = this.y + this.ySpeed;
};
// 邊緣檢測,碰撞檢測
checkCanvas = (panel) => {
// 左右
if(this.x < 5 || this.x > 400 - 5){
this.xSpeed = -this.xSpeed;
}
// 上方
if(this.y < 0){
this.ySpeed = -this.ySpeed;
}
// 下方
// 碰到擋板
if(this.y > 390 - 10){
if(this.x > panel.x && this.x < panel.xSize + panel.x){
this.ySpeed = -this.ySpeed;
}else{
alert("游戲結束");
this.x = 100;
this.y = 10;
}
}
}
}
// 增加一個擋板對象
class Panel{
constructor(){};
// 左x
x = 200;
// 左y
y = 390;
// 長度
xSize = 50;
// 寬度
ySize = 5;
draw(){
context.fillRect(this.x, this.y, this.xSize, this.ySize);
}
}
// 創建出一個小球對象
let ball = new Ball();
// 創建出擋板對象
let panel = new Panel();
// 每10秒為一幀
window.setInterval(() => {
// 清空畫布
context.clearRect(0, 0, 400, 400);
// 畫出小球
ball.draw();
// 畫出擋板
panel.draw();
// 移動
ball.move();
// 進行邊界判斷
ball.checkCanvas(panel);
},10);
// 控制擋板
$("body").keydown((event) => {
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 + panel.xSize > 400){
panel.x = 400 - panel.xSize;
}
}
})
</script>
</body>
</html>思路
這就是倆對象,,一個依賴于另一個。。
碰撞檢測時實的坐標判斷,碰撞完成以后兩個速度分量為取反即可。
事件是左右事件。。移動即可。
需要時實刷新,即,幀的概念
關于canvas實現彈球的案例就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。