Почему мое изображение не нарисовано, но оно загружается? - PullRequest
0 голосов
/ 29 июня 2018

Я начинаю создавать игру и собираю небольшой «движок игры», чтобы делать вещи легко, а не печатать так многократно. У меня есть функция спрайта, которая загружает изображение и функция обновления, которая его рисует. Проблема в том, что он не будет отрисовываться, и в консоли не сообщалось об ошибках.

jsfiddle

var canvas = document.createElement("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
canvas.style.position = "absolute";
canvas.style.right = "0px";
canvas.style.top = "0px";
document.body.appendChild(canvas);
var c = canvas.getContext("2d");

var Squares = [];

var Square = function(x,y,w,h,color="black") {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.color = color;
    Squares.push(this);
    return this
}

var Sprites = [];

var Sprite = function(x,y,w,h,src) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.src = src;
    this.img = new Image();
    this.img.onload = function() {

    }
    this.img.src = this.src;
    this.img.width = this.w;
    this.img.height = this.h;
    return this
} 

function Clear(x,y,w,h) {
    c.clearRect(x,y,w,h);
}

function Update() {
    Clear(0,0,canvas.width,canvas.height);
    for(var square in Squares) {
        c.fillStyle = Squares[square].color;
        c.fillRect(Squares[square].x,Squares[square].y,Squares[square].w,Squares[square].h);
    }
    for(var sprite in Sprites) {
        console.log(Sprites[sprite].img)
        Sprites[sprite].img.onload = function() {
            c.drawImage(Sprites[sprite].img);   
        }
    }
}

var ground = new Square(0,0,canvas.width,canvas.height,color="forestgreen");
var player = new Square(10,10,6,6,color="red");
var Mtn = new Sprite(50,50,50,50,"mountain.png");
console.log(Mtn.img)

function Logic() {

}


function Main() {
    Logic();
    Update();
}
setInterval(Main,2);
...