我正在尝试通过resizeCanvas()
方法调整canvas元素的大小以响应resize事件。如果我直接调用类方法,画布会调整大小,但是在后续通过事件处理程序调用时出现以下错误:Uncaught TypeError: Cannot set property 'width' of undefined
这是我的测试代码:
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>
任何想法为什么我收到错误?
编辑:正如Heretic Monkey
所指出的,这个问题类似于'this' is undefined in JavaScript class methods。但是,作为一个新的编码器,我绝不会想到这两个问题都是相关的。我认为这篇文章应该保留,以防其他人有类似的问题无法弄清楚潜在的问题。
我认为这是因为this
这个词的背景。请尝试替换:
window.addEventListener("resize", canvasManager.resizeCanvas);
附:
window.addEventListener("resize", canvasManager.resizeCanvas.bind(canvasManager));