HTML5画布 - drawImage不起作用(仅在错误发生时)

时间:2015-12-20 14:23:42

标签: javascript html5 canvas

我正在尝试创建一个简单的画布游戏。我开始使用游戏循环(更新,渲染功能)绘制游戏的所有元素。我设法绘制简单的图像,但是当我尝试使用它的函数类的一些特征来绘制图像时,它不显示任何东西。尽管如此,数组项目符号[]包含具有正确对象的所有对象。

我观察到,如果我故意做错误,那么就会画出子弹。为什么会发生这样的情况,只有在发生错误时才会绘制,但并非总是如此?

谢谢!

// Create the canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 512;
canvas.height = 480;
document.body.appendChild(canvas);

// Bullet class, defining it's proprieties
var Bullet = function (x,y,orientation) {
    this.x = x;
    this.y = y;
    this.speed = 512;
    this.orientation = orientation;
    if (orientation == 0)
    {
        var bulletImageUp = new Image();
        bulletImageUp.src = "images/bullet-up.png";
        this.image = bulletImageUp;
    }
    else if (orientation == 90){
        var bulletImageRight = new Image();
        bulletImageRight.src = "images/bullet-right.png";
        this.image = bulletImageRight;
    }
    else if (orientation == 180){
        var bulletImageDown = new Image();
        bulletImageDown.src = "images/bullet-down.png";
        this.image = bulletImageDown;
    }
    else if (orientation == 270){
        var bulletImageLeft = new Image();
        bulletImageLeft.src = "images/bullet-left.png";
        this.image = bulletImageLeft;
    }    
    this.draw  = function () {
        ctx.drawImage(this.image, this.x, this.y);
    }
}

// The array containing all the bullets objects
var bullets = [];

// Update game objects
var update = function (modifier) {
// When I press a key it executes 
bullets.push(new Bullet(tank.x, tank.y, tank.orientation));
};

// Draw everything
var render = function () {
    for ( i=0; i<bullets.length; i++) {
        bullets[i].draw()
    }
};

// The main game loop
var main = function () {
    var now = Date.now();
    var delta = now - then;
    update(delta / 1000);
    render();
    then = now;
};

0 个答案:

没有答案