首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >未捕获的TypeError:无法读取未定义的属性“”img“”

未捕获的TypeError:无法读取未定义的属性“”img“”
EN

Stack Overflow用户
提问于 2019-08-07 10:23:53
回答 2查看 2.2K关注 0票数 0

我正在尝试将精灵添加到我的游戏引擎中,我已经尝试了一大堆东西。问题是游戏可以运行,但我的图像永远不会显示。编辑:我发现通过将图像和src放在coin类构造函数中,可以使其呈现。

我试过window.onLoad,img.onLoad,把变量放在构造函数中,把它分成两个函数(load和draw)。

代码语言:javascript
复制
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");
        }
    }

我需要图像显示,但它不显示,游戏仍然运行。

EN

Stack Overflow用户

发布于 2019-08-07 11:19:49

根据MDNthis的值在function draw中是undefined,因为它是类声明中的嵌套函数-并且类声明是在严格模式下解析的。

一种解决方案是

  • draw使用箭头函数,以便在将其赋给变量时捕获词法图像值,
  • 将箭头函数表达式放在this值引用类实例而不是图像元素的位置,
  • 在设置其<代码>D14属性之前分配图像处理程序:<代码>H215F216

代码语言:javascript
复制
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的未定义值,如果是,则不会绘制任何内容。

代码语言:javascript
复制
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;
    }

将未定义的值默认为零应该有助于进一步开发。

票数 1
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57386207

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档