之前在HTML5 Canvas屬性和方法匯總一文中,介紹過Canvas
的各種屬性以及方法的說明,並列舉了自己寫的一些Canvas demo
,接下來開始寫一個簡單的小游戲吧,有多簡單,這么說吧,代碼不到100行,先上效果圖:
左側為我們控制的控制板,右側為假想的電腦控制的控制板
體驗小游戲鏈接: https://demo.luckyw.cn/code.h...
初始化
首先在html
頁面中添加中添加一個canvas
元素,並給出一個id
用於在js
代碼中獲取該元素並對其進行操作
<canvas id="canvas"></canvas>
然后就是對各種參數,注釋中都有給出,我就不多說了,直接看
//獲取canvas元素以及2d繪圖環境c,以及設置canvas寬高為800x600
var canvas = document.getElementById("canvas"),
c = canvas.getContext("2d"),
W = canvas.width = 800,
H = canvas.height = 600;
var ballX = W / 2, ballY = H / 2, ballR = 10, ballVx = 10, ballVy = 2, //球的位置、半徑以及在X軸及Y軸的速度
panelW = 10, panelH = 100, panel1Y = (H - panelH) / 2, panel2Y = (H - panelH) / 2, //控制板的寬高以及初始位置
player1Score = 0, player2Score = 0, winnerScore = 3, //記錄玩家的分數以及得了多少分算贏
isEnd = 0; //判斷是否比賽結束的變量,0為未結束,1為已結束
封裝工具方法
//繪制長方形(也就是控制板)
function fillRect(x, y, w, h, style) {
c.fillStyle = style;
c.fillRect(x, y, w, h);
}
//繪制圓(也就是游戲中的球)
function fillCircle(x, y, r, style) {
c.fillStyle = style;
c.beginPath();
c.arc(x, y, r, 0, Math.PI * 2);
c.fill();
}
//繪制文字(得分和顯示輸贏)
function fillText(txt, x, y, font, style) {
c.fillStyle = style || "white";
c.font = font || "40px DejaVu Sans Mono";
c.textAlign = "center";
c.textBaseline = "middle";
c.fillText(txt, x, y);
}
添加事件
我們需要在canvas
元素上添加監聽事件,一是當結束的也就是isEnd
為1的時候,當鼠標點擊在canvas
上的時候再來一把游戲,重置玩家分數以及重啟動畫繪制,二是我們需要控制左側控制板的運動,不過只需要在Y軸運動即可
canvas.addEventListener("click", function () {
if (isEnd) {
player1Score = 0;
player2Score = 0;
isEnd = 0;
animate(); //主要的繪制方法
}
});
//獲取鼠標在canvas上實際Y軸位置減去控制板的高度也就是控制板實際繪制的初始位置
canvas.addEventListener("mousemove", function (e) {
panel1Y = e.clientY - canvas.getBoundingClientRect().top - panelH / 2;
});
邊界判斷
//球邊界判斷
if (ballX - ballR - panelW < 0) {
if (ballY > panel1Y && ballY < panel1Y + panelH) {
ballVx = -ballVx;
ballVy = (ballY - (panel1Y + panelH / 2)) * .3;
} else {
player2Score++;
ballReset();
}
}
if (ballX + ballR + panelW > W) {
if (ballY > panel2Y && ballY < panel2Y + panelH) {
ballVx = -ballVx;
ballVy = (ballY - (panel2Y + panelH / 2)) * .3;
} else {
player1Score++;
ballReset();
}
}
if (ballY + ballR < 0 || ballY - ballR > H) {
ballVy = -ballVy;
}
//用於控制右側控制板的運動
if (panel2Y + panelH / 2 < ballY - 40) {
panel2Y = panel2Y + 5;
} else if (panel2Y + panelH / 2 > ballY + 40) {
panel2Y = panel2Y - 5;
}
執行動畫
我這里直接在animate
方法里使用requestAnimationFrame(animate)
,更兼容的方法應該是以下這樣,為了偷個懶就沒寫兼容寫法
var RAF = (function () {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame || function (callback) {
window.setTimeout(callback, 1000 / 60);
}
})();
RAF(animate);
到此,該小游戲的介紹到此結束,簡單吧