游戲圖像
按下按鈕可移動笑臉:
如何使用圖像?
如需在畫布上添加圖像,請使用 getContext("2d") 對象內置的圖像屬性和方法。
在我們的游戲中,如需將游戲件創建為圖像,請使用組件構造函數,但您必須引用圖像的 url,而不是引用顏色。并且必須告訴構造函數該組件的類型為 "image":
實例
function startGame() { myGamePiece = new component(30, 30, "smiley.gif", 10, 120, "image"); myGameArea.start(); }
在組件構造函數中,我們測試組件是否屬于 "image" 類型,并使用內置的 "new Image()" 對象構造函數創建一個圖像對象。在我們準備繪制圖像時,我們使用的是 drawImage 方法而不是 fillRect 方法:
實例
function component(width, height, color, x, y, type) { this.type = type; if (type == "image") { this.image = new Image(); this.image.src = color; } this.width = width; this.height = height; this.speedX = 0; this.speedY = 0; this.x = x; this.y = y; this.update = function() { ctx = myGameArea.context; if (type == "image") { ctx.drawImage(this.image, this.x, this.y, this.width, this.height); } else { ctx.fillStyle = color; ctx.fillRect(this.x, this.y, this.width, this.height); } } }
更改圖像
您可以隨時通過更改組件的 image
對象的 src
屬性來更改圖像。
如果您想在每次移動時更改笑臉,請在用戶單擊按鈕時更改圖像源,并在未單擊按鈕時恢復正常:
實例
function move(dir) { myGamePiece.image.src = "angry.gif"; if (dir == "up") {myGamePiece.speedY = -1; } if (dir == "down") {myGamePiece.speedY = 1; } if (dir == "left") {myGamePiece.speedX = -1; } if (dir == "right") {myGamePiece.speedX = 1; } } function clearmove() { myGamePiece.image.src = "smiley.gif"; myGamePiece.speedX = 0; myGamePiece.speedY = 0; }
背景圖片
通過將背景圖像添加為組件,可將其添加到游戲區域,并在每個幀中更新背景:
實例
var myGamePiece; var myBackground; function startGame() { myGamePiece = new component(30, 30, "smiley.gif", 10, 120, "image"); myBackground = new component(656, 270, "citymarket.jpg", 0, 0, "image"); myGameArea.start(); } function updateGameArea() { myGameArea.clear(); myBackground.newPos(); myBackground.update(); myGamePiece.newPos(); myGamePiece.update(); }
移動背景
更改背景組件的 speedX
屬性可使背景移動:
實例
function updateGameArea() { myGameArea.clear(); myBackground.speedX = -1; myBackground.newPos(); myBackground.update(); myGamePiece.newPos(); myGamePiece.update(); }
背景循環
為了讓這幅相同的背景永遠循環,我們必須使用特定的技術。
首先告訴組件構造函數這是背景。然后,組件構造函數將添加圖像兩次,將第二個圖像立即放置在第一個圖像之后。
在 newPos()
方法中,檢查組件的 x 位置是否已到達圖像的末尾,如果已到達,則將組件的 x
位置設置為 0:
實例
function component(width, height, color, x, y, type) { this.type = type; if (type == "image" || type == "background") { this.image = new Image(); this.image.src = color; } this.width = width; this.height = height; this.speedX = 0; this.speedY = 0; this.x = x; this.y = y; this.update = function() { ctx = myGameArea.context; if (type == "image" || type == "background") { ctx.drawImage(this.image, this.x, this.y, this.width, this.height); if (type == "background") { ctx.drawImage(this.image, this.x + this.width, this.y, this.width, this.height); } } else { ctx.fillStyle = color; ctx.fillRect(this.x, this.y, this.width, this.height); } } this.newPos = function() { this.x += this.speedX; this.y += this.speedY; if (this.type == "background") { if (this.x == -(this.width)) { this.x = 0; } } } }