JavaScript drawImage()不起作用

时间:2013-02-01 22:12:51

标签: javascript jquery html5 canvas

进入JS游戏开发但遇到了一个小问题。图像不会被吸引。它加载正常,没有错误在控制台,但它只是不会显示。我错过了什么?

JS

var Game = {
characterSpeed: 2,
characterHorizontalSpeed: this.characterSpeed,
characterVerticalSpeed: this.characterSpeed,
characterX: 400,
characterY: 500,
mouseX: 0,
mouseY: 0,
gameRunning: false,
debug: true,
characterImg: '',
context: '',

init: function() {
    $('#game').mousemove(function(event) {
        Game.mouseX = event.pageX;
        Game.mouseY = event.pageY;
    });

    Game.context = document.getElementById('game').getContext('2d');

    Game.loadImages();
    Game.game();
},

loadImages: function() {
    Game.characterImg = new Image;
    Game.characterImg.src = 'images/character.png';

    Game.characterImg.onload = function() {
        Game.context.drawImage(Game.characterImg, 400, 500);
    }
},
}

$(function() {
Game.init();
});

HTML

    <div id="inner">
        <canvas id="game" style="background: white; width: 800px; height: 500px;"></canvas>
    </div>

3 个答案:

答案 0 :(得分:0)

您需要在widthheight属性中设置不属于样式的画布大小。

<div id="inner">
    <canvas id="game" width="800" height="500"></canvas>
</div>

答案 1 :(得分:0)

尝试在最后设置src属性,因此在onload之后。

loadImages: function() {

    Game.characterImg = new Image();

    Game.characterImg.onload = function() {
        Game.context.drawImage(Game.characterImg, 400, 500);
    }

    Game.characterImg.src = 'images/character.png';

}

答案 2 :(得分:0)

图像可能位于缓存中,因此在设置onload事件时,图像已经加载,因此不会调用onload。简单地颠倒顺序,如下所示:

Game.characterImg.onload = function() {
      Game.context.drawImage(Game.characterImg, 400, 500);
   }
Game.characterImg.src = 'images/character.png';