簡體   English   中英

對象文字內部的HTML5 Canvas drawImage()

[英]HTML5 Canvas drawImage() inside object literal

我正在嘗試使用對象文字模式使用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 eg 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> 

這里的問題是圖像是異步預加載的,而同時您調用game.init()並因此game.draw() ,它期望圖像已被加載。

因此,除非圖像位於瀏覽器的緩存中,否則在game.draw()時異步預加載可能尚未完成。

您需要等到預加載完成后才能調用game.init() JavaScript提供了一些處理異步執行的好工具,例如回調,promise等。

在這里看看: https : //gamedev.stackexchange.com/questions/24102/resource-loader-for-an-html5-and-javascript-game

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM