我正在尝试将精灵添加到我的游戏引擎中,我已经尝试了一大堆东西。问题是游戏可以运行,但我的图像永远不会显示。编辑:我发现通过将图像和src放在coin类构造函数中,可以使其呈现。
我试过window.onLoad,img.onLoad,把变量放在构造函数中,把它分成两个函数(load和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");
}
}我需要图像显示,但它不显示,游戏仍然运行。
发布于 2019-08-07 11:19:49
根据MDN,this的值在function draw中是undefined,因为它是类声明中的嵌套函数-并且类声明是在严格模式下解析的。
一种解决方案是
draw使用箭头函数,以便在将其赋给变量时捕获词法图像值,this值引用类实例而不是图像元素的位置,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;
}将未定义的值默认为零应该有助于进一步开发。
https://stackoverflow.com/questions/57386207
复制相似问题