本文详解为何基于 `setinterval` 的屏幕淡出动画仅执行一次,并提供完整可复用的修复方案:将绘制逻辑移入定时器循环、正确管理状态、避免闭包与作用域陷阱。
问题核心在于原始代码中 fadeRed() 方法仅启动定时器,却未在每次迭代中触发重绘,且 draw() 被外部调用(依赖单次 if 判断),导致视觉效果“只闪一次”。更关键的是:fadeRed() 立即返回 this.fadeFinished(初始为 false),而此时定时器才刚启动——fadeFinished 实际在几秒后才被设为 true,因此后续调用始终拿到过期的 false 值,但定时器已因前次未清理而冲突或失效。
export class FadeEffects {
constructor(game, context) {
this.game = game;
this.context = context || null;
this.width = 640;
this.height = 480;
this.fadeFinished = false;
this.fade = 255;
this._intervalId = null; // 缓存定时器ID,便于清理
}
fadeRed() {
// 防止重复启动(可选但推荐)
if (this._intervalId) {
clearInterval(this._intervalId);
}
this.fade = 255; // 重置为起始值(全红)
this.fadeFinished = false;
this._intervalId = setInterval(() => {
this.fade -= 1;
this.draw(); // ✅ 每帧绘制,保证视觉连续
if (this.fade <= 0) {
this.fade = 0; // 防止负值
this.fadeFinished = true;
clearInterval(this._intervalId);
this._intervalId = null;
}
}, 25);
}
draw() {
if (!this.context) return;
// 修正原代码:rgba 字符串末尾缺右括号 → "rgba(255, 0, 0, 0.5)"
this.context.fillStyle = `rgba(${this.fade}, 0, 0, 0.5)`;
this.context.fillRect(0, 0, this.width, this.height);
}
// 可选:提供手动停止接口
stopF
ade() {
if (this._intervalId) {
clearInterval(this._intervalId);
this._intervalId = null;
}
}
}// 初始化时传入 canvas 上下文
const fadeEffect = new FadeEffects(this.game, context);
// 触发淡出(可多次调用,每次都是全新动画)
function startFade() {
fadeEffect.fadeRed();
}
// 若需监听完成,使用 Promise 封装(更现代的做法):
fadeEffect.fadeRedAsync = function() {
return new Promise(resolve => {
this.fadeRed();
const check = () => {
if (this.fadeFinished) resolve();
else requestAnimationFrame(check);
};
check();
});
};通过以上重构,fadeRed() 成为真正可重入、可预测、视觉连贯的动画入口,彻底解决“只生效一次”的问题。