为什么我的图片不会绘制但会加载?

时间:2018-06-28 21:12:55

标签: javascript html5 image drawimage

我开始制作游戏,并且我在组合一个小的“游戏引擎”以轻松地进行操作,而不是重复输入。我有一个加载图像的精灵功能和一个绘制它的更新功能。问题是它不会绘制,并且控制台中未报告任何错误。

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);

0 个答案:

没有答案