遊戲圖片
按下按鈕移動笑臉
如何使用圖片?
要在畫布上新增圖片,getContext("2d") 物件具有內建的圖片屬性和方法。
在我們的遊戲中,要將遊戲元素建立為圖片,請使用 component 建構函式,但不是引用顏色,而是必須引用圖片的 URL。並且您必須告訴建構函式此元件的型別是“image”。
示例
function startGame() {
myGamePiece = new component(30, 30, "smiley.gif", 10, 120, "image");
myGameArea.start();
}
在 component 建構函式中,我們檢查元件的型別是否為“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;
}
}
}
}
自己動手試一試 »