以前在HTML5 Canvas屬性和方法彙總一文中,介紹過Canvas
的各類屬性以及方法的說明,並列舉了本身寫的一些Canvas demo
,接下來開始寫一個簡單的小遊戲吧,有多簡單,這麼說吧,代碼不到100行,先上效果圖:
左側爲咱們控制的控制板,右側爲假想的電腦控制的控制板
體驗小遊戲連接: https://demo.luckyw.cn/code.h...html
首先在html
頁面中添加中添加一個canvas
元素,並給出一個id
用於在js
代碼中獲取該元素並對其進行操做html5
<canvas id="canvas"></canvas>
而後就是對各類參數,註釋中都有給出,我就很少說了,直接看web
//獲取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
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);
到此,該小遊戲的介紹到此結束,簡單吧動畫