我正在尝试使用对象文字模式与HTML5进行蛇形游戏,但我似乎无法在画布上绘制图像。我已经研究了很多,并且发现在创建对象时我无法设置图像src
(所以我把它放在一个函数中)。图像似乎可用,因为它显示在控制台中,可以附加到正文。我错过了什么?
(function ($) {
$.fn.preload = function() { // http://stackoverflow.com/a/476681
this.each(function(){
$('<img/>')[0].src = this;
});
}
})(jQuery);
$(document).ready(function() {
$(['./images/grass-500x500.png']).preload(); // I've tried with and without this function (defined elsewhere)
// Object literal pattern
var game = {
// Background image
background: new Image(),
setBGSource: function() {
this.background.src = 'images/grass-500x500.png';
},
// Canvas details
canvas: $("#canvas")[0],
ctx: canvas.getContext("2d"),
WIDTH: $("#canvas").width(),
HEIGHT: $("#canvas").height(),
// Game details
CELL_WIDTH: 10,
direction: null,
food: null,
score: null,
snakeArray: [],
init: function() {
this.direction = "right";
this.createSnake();
this.setBGSource();
this.draw();
},
createSnake: function() {
var length = 5; // Initial length of snake
for (var i = length - 1; i >= 0; i--) {
this.snakeArray.push({
x: i,
y: 1 // y : 0 - initial position of snake in cell units
});
}
},
// Create food item
createFood: function() {
this.food = {
x: Math.round(Math.random() * (WIDTH - CELL_WIDTH) / CELL_WIDTH),
y: Math.round(Math.random() * (HEIGHT - CELL_WIDTH) / CELL_WIDTH)
} // Position of food with x and and y between 0 and e.g 44
},
// Drawing function
draw: function() {
// Repaint the background on each frame
console.log(this.background); // displays <img src="images/grass-500x500.png">
this.ctx.drawImage(this.background, 0, 0); // WHY DOESN'T THIS WORK PLEASE?
$('body').append(this.background); // appends image, no problem
}
};
game.init();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas"></canvas>
答案 0 :(得分:1)
这里的问题是图像是异步预加载的,同时你调用game.init()
,因此game.draw()
,它期望图像已经被加载。
因此,除非图像在浏览器的缓存中,否则异步预加载可能在game.draw()
时尚未完成。
您需要等到预加载完成后才能调用game.init()
。 JavaScript提供了一些处理异步执行的好工具,例如回调,承诺等。
看看这里:https://gamedev.stackexchange.com/questions/24102/resource-loader-for-an-html5-and-javascript-game