在画布html5上创建/绘制多个图像

时间:2016-05-31 02:18:54

标签: javascript html5 canvas

我想知道我做错了什么,因为我正在制作记忆游戏,但图像不会在我的画布上绘制。

    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));
            }
        }
    }

2 个答案:

答案 0 :(得分:0)

您需要在画布上绘制HTML图像元素,而不是网址。我想你可以做到

var cardBacks = new Image();
cardBacks.src = "Resources/monster.png";

以下是一个例子:https://jsfiddle.net/yarhqskx/
这里有多个(添加了onload):https://jsfiddle.net/yarhqskx/7/

答案 1 :(得分:0)

使用onload回调函数尝试此代码。

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));
        }
    }
}