0

I'm trying to resize a canvas element via a resizeCanvas() method in response to a resize event. The canvas resizes if I call the class method directly, but I get the following error in subsequent calls through the event handler: Uncaught TypeError: Cannot set property 'width' of undefined

Here is my test code:

class CanvasManager {
  constructor(canvasID) {
    this.canvas = document.getElementById(canvasID);
    this.context = this.canvas.getContext('2d');
  }

  resizeCanvas() {
    this.canvas.width = window.innerWidth-30;
    this.canvas.height = window.innerHeight-30;
    window.scrollTo(0, 0);
  }
}

let canvasManager = new CanvasManager('controller');
canvasManager.resizeCanvas();
window.addEventListener("resize", canvasManager.resizeCanvas);
<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <canvas id="controller" style="border-style: solid;" width="300px" height="300px"></canvas>
    <script src="./test.js"></script>
  </body>
</html>

Any ideas why I'm getting the error?

edit: As Heretic Monkey points out, this issue is similar to 'this' is undefined in JavaScript class methods. However, as a new coder, I would have never figured out both issues were related. I think this post should remain in case someone else has a similar problem can cannot figure out the underlying issue.

IdoTuchman
  • 67
  • 1
  • 9
  • Possible duplicate of ['this' is undefined in JavaScript class methods](https://stackoverflow.com/questions/4011793/this-is-undefined-in-javascript-class-methods) – Heretic Monkey Feb 26 '19 at 21:31

1 Answers1

0

I think it's because of the context of the word this. Please, try to replace:

window.addEventListener("resize", canvasManager.resizeCanvas);

With:

window.addEventListener("resize", canvasManager.resizeCanvas.bind(canvasManager));
amedina
  • 2,838
  • 3
  • 19
  • 40