title: Resizing HTML5 canvas via a class method in response to a resize event
body: <p>I'm trying to resize a canvas element via a <code>resizeCanvas()</code> 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: <code>Uncaught TypeError: Cannot set property 'width' of undefined</code></p>
  
  <p>Here is my test code:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><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);</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
    &lt;head&gt;&lt;/head&gt;
    &lt;body&gt;
      &lt;canvas id="controller" style="border-style: solid;" width="300px" height="300px"&gt;&lt;/canvas&gt;
      &lt;script src="./test.js"&gt;&lt;/script&gt;
    &lt;/body&gt;
  &lt;/html&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>Any ideas why I'm getting the error?</p>
  
  <p>edit: As <code>Heretic Monkey</code> points out, this issue is similar to <a href="https://stackoverflow.com/questions/54894329/resizing-html5-canvas-via-a-class-method-in-response-to-a-resize-event">'this' is undefined in JavaScript class methods</a>. 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.</p>