我有一些代码在工作,但是对我来说看起来太丑陋(使用闭包将_this入侵Canvas对象以及this.resize()()),并且必须有一种更好的方法来实现。任何指针将不胜感激。
'use strict'
const Canvas = {
canvas: null, // DOM element
ctx: null, // 2D canvas.context
canvasWidth: 0,
canvasHeight: 0,
init(canvasDOMElement) {
this.canvas = canvasDOMElement;
if(!canvas.getContext) return undefined;
this.ctx = canvas.getContext("2d");
window.addEventListener('resize', this.resize(), false);
window.addEventListener('orientationchange', this.resize(), false);
this.resize()();
},
resize() {
const _this = this;
return function() {
_this.canvas.width = window.innerWidth;
_this.canvas.height = window.innerHeight;
_this.ctx.fillText("Hello, World!",20,20);
};
},
};
window.addEventListener('DOMContentLoaded', function() {
Canvas.init(document.getElementById('canvas'));
});