[英]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. 我试图通过resizeCanvas()
方法调整画布元素的大小,以响应resize事件。 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
如果直接调用类方法,画布将调整大小,但是在随后通过事件处理程序的调用中,我将收到以下错误: 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 . 编辑:正如Heretic Monkey
指出的,此问题类似于JavaScript类方法中未定义的“ this” 。 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
. 我认为是因为this
的上下文。 Please, try to replace: 请尝试更换:
window.addEventListener("resize", canvasManager.resizeCanvas);
With: 附:
window.addEventListener("resize", canvasManager.resizeCanvas.bind(canvasManager));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.