我正在尝试将精灵添加到游戏引擎中,并且尝试了很多事情。问题在于游戏可以运行,但我的图像从未显示。
编辑:我发现通过将图像和src放在钱币类构造函数中使其呈现。
我尝试过window.onLoad,img.onLoad,将vars放入构造函数中,将其拆分为2个函数(加载和绘制)。
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");
}
}
我需要显示图像,但不显示图像,游戏仍然可以运行。
最佳答案
根据MDN,this
的值在undefined
中为function draw
,因为它是类声明中的嵌套函数-并且在严格模式下解析类声明。
一种解决方案是
对draw
使用箭头函数,以便在将词法this
值分配给变量时捕获它,
将箭头函数表达式放在this
值引用类实例而不是图像元素的位置,并且
在设置图像的onload
处理程序之前,先分配它们的src
属性:
drawSprite(url){
let draw = ()=>c.drawImage(this.img, this.x, this.y, this.width, this.height);
this.img = new Image();
this.img.onload = draw;
this.img.src = url;
}
进一步的测试表明CanvasRenderingContext2D方法
drawImage
无法处理x和y的未定义值,如果可以,则不会绘制任何内容。class gameObject {
constructor(x,y,id){
this.x = x || 0; // default x and y to zero
this.y = y || 0;
this.id = id;
var velX, velY, width, height;
}
将未定义的值默认为零应该有助于进一步发展。