我在网上找到了这个,现在试图把它放在 TS 中。
运行以下抛出Uncaught TypeError: Cannot set property 'toggle' of null
@Injectable()
export class HomeUtils {
private canvas: HTMLCanvasElement;
private context;
private toggle = true;
constructor() { }
public startNoise(canvas: HTMLCanvasElement) {
this.canvas = canvas;
this.context = canvas.getContext('2d');
this.resize();
this.loop();
}
private resize() {
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
}
private loop() {
this.toggle = false;
if (this.toggle) {
requestAnimationFrame(this.loop);
return;
}
this.noise();
requestAnimationFrame(this.loop);
}
private noise() {
const w = this.context.canvas.width;
const h = this.context.canvas.height;
const idata = this.context.createImageData(w, h);
const buffer32 = new Uint32Array(idata.data.buffer);
const len = buffer32.length;
let i = 0;
for (; i < len;) {
buffer32[i++] = ((255 * Math.random()) | 0) << 24;
}
this.context.putImageData(idata, 0, 0);
}
}
我迷路了。
方法不捕获this
,并且依赖于调用方使用正确的this
调用它们。所以例如:
this.loop() // ok
let fn = this.loop;
fn(); // Incorect this
fn.apply(undefined) // Undefined this
由于loop
传递给另一个函数requestAnimationFrame
因此需要确保从声明上下文中捕获this
,而不是由requestAnimationFrame
决定:
您可以将箭头函数传递给requestAnimationFrame
private loop() {
this.toggle = false;
if (this.toggle) {
requestAnimationFrame(() => this.loop());
return;
}
this.noise();
requestAnimationFrame(() => this.loop());
}
或者你可以让循环成为箭头函数而不是方法:
private loop = () => {
this.toggle = false;
if (this.toggle) {
requestAnimationFrame(this.loop);
return;
}
this.noise();
requestAnimationFrame(this.loop);
}
第二种方法的优点是不会在每次调用requestAnimationFrame
时创建新的函数实例,因为这会被调用很多,您可能希望使用第二个版本以最小化内存分配。
对requestAnimationFrame
的召唤。您正在传递一个未绑定到上下文的函数,因此,在该调用中loop
没有this
。
将呼叫更改为:
requestAnimationFrame(() => this.loop());
与正常函数相反,箭头函数绑定到this
。