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.