我想知道我做错了什么,因为我正在制作一个记忆游戏,但图像无法在我的画布上绘制。
var ctx;
var cardBacks = "Resources/monster.png"; //shows back of card when turned over
var faces = [];
var tiles = [];
var Tile;
var columns = 5;
var rows = 4;
function createTile(x,y){
this.x = x;
this.y = y;
this.width = 70;
ctx.drawImage(cardBacks, this.x, this.y, this.width, this.width);
}
function initialize(){
ctx = document.getElementById("myCanvas").getContext("2d");
for (var i = 0; i < columns; i++) {
for (var j = 0; j < rows; j++) {
tiles.push(createTile(i * 78 + 10, j * 78 + 40));
}
}
}
尝试使用加载回调函数编写此代码。
var ctx;
var cardBacks = new Image();
cardBacks.src = "Resources/monster.png"; //shows back of card when turned over
cardBacks.onload = function() {
ctx.drawImage(cardBacks, this.x, this.y, this.width, this.width);
}
var faces = [];
var tiles = [];
var Tile;
var columns = 5;
var rows = 4;
function createTile(x, y) {
this.x = x;
this.y = y;
this.width = 70;
}
function initialize() {
ctx = document.getElementById("myCanvas").getContext("2d");
for (var i = 0; i < columns; i++) {
for (var j = 0; j < rows; j++) {
tiles.push(createTile(i * 78 + 10, j * 78 + 40));
}
}
}
您需要在画布上绘制HTML图像元素,而不是URL。我想你可以做到
var cardBacks = new Image();
cardBacks.src = "Resources/monster.png";
下面是一个示例:https://jsfiddle.net/yarhqskx/
这是多个(添加加载): https://jsfiddle.net/yarhqskx/7/