简体   繁体   中英

Resizing HTML5 canvas via a class method in response to a resize event

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.

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM