JSilv
JSilv

Reputation: 1055

Using class methods to draw on HTML5 Canvas: scope problems (JS, ES6)

I am having some trouble wrapping my head around some scope problems. I am using a class method to draw a square on the canvas and would like to move it around using another class method, but it seems I can't pass along the context...

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
  }

}

The context is passed into the User class further down in the code as shown in this pen but as far as I can tell the way it's being passed to the User class isn't a problem, it's the way I'm accessing it in the move function.

I did also try defining a variable for the context in the constructor function independent of this but that wasn't successful either.

Upvotes: 0

Views: 1625

Answers (2)

Diogo Sgrillo
Diogo Sgrillo

Reputation: 2701

You must bind your method. ES6 classes doesn't do that automatically.

In your constructor try to add this line:

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

Upvotes: 3

David Gomez
David Gomez

Reputation: 2772

You are expecting four arguments (e, x, y, ctx) into your event listener function but the listener will receive only one argument, the event.

Your have to explicitly pass all the arguments to your handler in order to use them or figure out another way to access them.

Upvotes: 1

Related Questions