1
我已經開始用畫布開發小型JavaScript遊戲。 所以我需要在畫布上顯示多張卡片。 但我似乎,我使用gameArea.clear();
方法updateGameArea()
功能後,一張卡不顯示。但是如果不使用這種方法,那麼這些卡片顯示效果不錯。但我需要多張卡片。JavaScript畫布元素在畫布清晰後不顯示
這裏我的JavaScript代碼
var cards = [];
var selectedCards = [];
var select = true;
window.addEventListener('DOMContentLoaded', function() {
startGame();
});
function startGame() {
cards.push(new PlayingCard("blue", 5, 150, 10));
cards.push(new PlayingCard("red", 1, 10, 10));
gameArea.click();
gameArea.start();
}
var gameArea = {
canvas: document.createElement("canvas"),
start: function() {
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 100);
},
click: function() {
this.canvas.addEventListener('click', getPosition);
},
clear: function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
};
function getPosition(e) {
var top = this.offsetTop;
var left = this.offsetLeft;
var x = e.pageX - left;
var y = e.pageY - top;
cards.forEach(function (card) {
if (y > card.y && y < card.y + card.height && x > card.x && x < card.x + card.width) {
card.selected = select;
if (selectedCards.length < 2) {
selectedCards.push(card);
} else {
selectedCards = [];
selectedCards.push(card);
}
if (selectedCards.length === 2) {
selectedCards.forEach(function (selected_card) {
selected_card.x = 400;
if (selected_card.selected === select) {
console.log(selected_card);
}
});
}
}
});
}
function PlayingCard(color, value, x, y) {
this.color = function() {
if (color === 'red') {
return "#E53935";
} else if (color === 'blue') {
return "#0D47A1";
} else {
throw new Error("No Color Code Found!");
}
};
this.value = value;
this.width = 120;
this.height = 160;
this.x = x;
this.y = y;
this.selected = false;
this.update = function() {
var ctx = gameArea.context;
ctx.fillStyle = this.color();
ctx.shadowBlur = 8;
ctx.shadowColor = 'rgba(0, 0, 0, 0.5)';
ctx.fillRect(this.x, this.y, this.width, this.height);
};
}
function updateGameArea() {
cards.forEach(function (card) {
gameArea.clear();
card.update();
});
}
爲什麼你爲每個'card'調用'gameArea.clear()'? – Andreas
明確畫布區域 – DININDU
但爲什麼每個卡** **?在更新'forEach'中的卡片之前,只需調用它一次。 – Andreas