I'm trying to add sprites to my game engine and I've tried a whole bunch of things. The problem is that the game can run but my image never shows. EDIT: I have found by putting the image and src in the coin class constructor makes it render.
I've tried window.onLoad, img.onLoad, putting the vars in the constructor, splitting it into 2 functions (load and draw).
class gameObject {
constructor(x,y,id){
this.x = x;
this.y = y;
this.id = id;
var velX, velY, width, height;
}
drawRect(){
c.fillRect(this.x, this.y, this.width, this.height);
}
drawSprite(url){
this.img = new Image();
this.img.src = url;
this.img.onload = function(){
function draw(){
c.drawImage(this.img, this.x, this.y, this.width, this.height)
}
draw();
}
}
move(){
this.x += this.velX;
this.y += this.velY;
}
}
class Coin extends gameObject{
constructor(x,y,id,img){
super(x,y,id);
this.velX = 0;
this.velY = 0;
this.width = 32;
this.height = 32;
}
tick(){
this.move();
}
render(){
this.drawSprite("coin.png");
}
}
I need the image to show but it doesn't show and the game still runs.