游戲畫布
HTML <canvas> 元素在網頁上顯示為矩形對象:
HTML Canvas
<canvas>
元素非常適合在 HTML 中開發游戲。
<canvas>
元素提供了制作游戲所需的所有功能。
請使用 JavaScript 在 <canvas>
上繪圖、寫文本、插入圖像等。
.getContext("2d")
<canvas>
元素有一個內置對象,稱為 getContext("2d")
對象,提供了用于繪圖的方法和屬性。
您能夠在我們的 Canvas 教程 中學習有關 <canvas>
元素和 getContext("2d")
對象的更多知識。
那么,開始吧
要制作游戲,首先創建一個游戲區域,并準備好進行繪圖:
實例
function startGame() { myGameArea.start(); } var myGameArea = { canvas : document.createElement("canvas"), start : function() { this.canvas.width = 480; this.canvas.height = 270; this.context = this.canvas.getContext("2d"); document.body.insertBefore(this.canvas, document.body.childNodes[0]); } }
在本教程的稍后部分中,對象 myGameArea
將獲得更多屬性和方法。
函數 startGame()
調用 myGameArea
對象的 start()
方法。
start()
方法創建了一個 <canvas>
元素,并作為第一個子節點插入到 <body>
元素中。