gpt4 book ai didi

javascript - 'this' 在 requestAnimationFrame 的类方法中未定义

转载 作者:行者123 更新时间:2023-12-01 00:16:38 26 4
gpt4 key购买 nike

我正在使用面向对象的方法开发 JavaScript Canvas API。我的问题是,在 animate 方法中使用 requestAnimationFrame 后,我得到 this 为未定义。如果我从 animate 方法中删除 requestAnimationFrame ,错误就会消失 - 知道如何解决这个问题吗?

Canvas.js

export default class Canvas {
constructor(canvas, ctx) {
this.canvas = canvas;
this.ctx = ctx;
this.x = 100;
this.y = 100;
this.dx = 4;
this.dy = 5;
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
}

drawCircle(x, y) {
for (let i = 0; i < 6; i++) {
this.ctx.beginPath();
this.ctx.fillStyle = "lightblue";
this.ctx.arc(x, y, 30, 0, Math.PI * 2);
this.ctx.fill();
}
}

animate() {
// Clear rect
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

requestAnimationFrame(this.animate);

this.x += 1;

this.drawCircle(this.x, this.y);
}
}

app.js

import Canvas from "./Canvas";

let c = document.getElementById("canvas");
let ctx = c.getContext("2d");

const obj = new Canvas(c, ctx);

obj.animate();

最佳答案

您可能需要绑定(bind)方法才能使用它。

尝试以下 Canvas.js 代码

export default class Canvas {
constructor(canvas, ctx) {
this.canvas = canvas;
this.ctx = ctx;
this.x = 100;
this.y = 100;
this.dx = 4;
this.dy = 5;
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;

this.drawCircle = this.drawCircle.bind(this);
this.animate = this.animate.bind(this);
}

drawCircle(x, y) {
for (let i = 0; i < 6; i++) {
this.ctx.beginPath();
this.ctx.fillStyle = "lightblue";
this.ctx.arc(x, y, 30, 0, Math.PI * 2);
this.ctx.fill();
}
}

animate() {
// Clear rect
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

requestAnimationFrame(this.animate);

this.x += 1;

this.drawCircle(this.x, this.y);
}
}

关于javascript - 'this' 在 requestAnimationFrame 的类方法中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59719464/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com