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.