[英]Creating/Drawing multiple images on canvas html5
I was wondering what I was doing wrong because I'm making a memory game but the images wouldn't draw on my 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));
}
}
}
You need to draw an HTML image element onto the canvas, not a url. 您需要在画布上绘制HTML图像元素,而不是URL。 I think you could do 我想你可以做
var cardBacks = new Image();
cardBacks.src = "Resources/monster.png";
Here's an example: https://jsfiddle.net/yarhqskx/ 这是一个示例: https : //jsfiddle.net/yarhqskx/
Here's with multiple (added onload): https://jsfiddle.net/yarhqskx/7/ 这里有多个(添加了onload): https : //jsfiddle.net/yarhqskx/7/
Try this code with onload callback function. 使用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));
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.