javascript - 使用类方法在 HTML5 Canvas 上绘图 : scope problems (JS, ES6)

标签 javascript html canvas es6-class

我在解决一些范围问题时遇到了一些麻烦。我正在使用一个类方法在 Canvas 上绘制一个正方形,并想使用另一个类方法来移动它,但似乎我无法传递上下文...

class User {
  constructor(user, x, y, ctx) {
    for (let metric in user) { this[metric] = user[metric]; }
    this.initialX = x;
    this.initialY = y;
    this.x = x;
    this.y = y;
    this.ctx = ctx;
    this.draw(this.initialX, this.initialY, this.ctx);
   }

  draw(x, y, ctx) {
    ctx.fillStyle = 'white';
    ctx.fillRect(x,y,20,20);
  }

  move(e) {
    //// stuff about motion goes here
     console.log(e.key, this.ctx); //// can't access `ctx` - the user key shows up in the console but the context is nowhere to be seen
     //// eventually this needs to be draw(x, y, ctx) that's passed back up to the draw function
  }

}

上下文被传递到代码中的 User 类中,如下所示 in this pen但据我所知,它传递给 User 类的方式不是问题,这是我在 move 函数中访问它的方式。

我也尝试在构造函数中为上下文定义一个独立于 this 的变量,但这也没有成功。

最佳答案

您必须绑定(bind)您的方法。 ES6 classes doesn't do that automatically.

在你的构造函数中尝试添加这一行:

this.move = this.move.bind(this);

关于javascript - 使用类方法在 HTML5 Canvas 上绘图 : scope problems (JS, ES6),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41169190/

相关文章:

javascript - 如何在 Node xmpp花名册中添加联系人?

jquery - 更改表格行的 CSS OnClick

html - 使用 photoshop 操作更改文件名

Javascript - 绘制曲线矩形的函数

php - 通过 PHP 发送电子邮件不起作用

javascript - 如何在应用程序浏览器中强制链接或页面在 facebook 之外打开?

javascript - iframe 之间通信

html - 使用伪类更改另一个元素的属性?

javascript - 创建连接到其他形状的 Canvas 形状

javascript - 使用 Canvas 将图像添加到轮子上