如何在Class对象中正确使用requestAnimationFrame实现SVG动画
解决类中
requestAnimationFrame回调的this指向问题 这个问题我之前踩过坑!核心原因是当你把类方法this.step直接传给requestAnimationFrame时,方法的上下文(也就是this)会被丢失。第一次调用正常是因为你大概率是通过类实例直接触发的(比如myAnimator.step()),这时候this还牢牢绑定在实例上;但当requestAnimationFrame异步调用回调时,它是在全局上下文执行的,this就不再指向你的类实例了,自然就陷入了所谓的“回调黑洞”。
下面给你几个靠谱的解决方案,按推荐程度排序:
方案1:构造函数中提前绑定this
这是最稳妥的传统方案,在类的构造函数里提前把step方法的this绑定到当前实例,一劳永逸:
class SVGAnimator { constructor(coords, duration) { this.coords = coords; this.duration = duration; this.currentFrame = 0; // 关键操作:把step方法的this永久绑定到当前实例 this.step = this.step.bind(this); } step() { // 这里的this现在永远指向SVGAnimator实例 const progress = this.currentFrame / (this.duration * 60); // 示例:修改SVG元素属性 this.circleLine.setAttribute('cx', this.coords[progress].x); this.circleLine.setAttribute('cy', this.coords[progress].y); this.currentFrame++; if (this.currentFrame < this.duration * 60) { // 现在传this.step时,上下文不会丢失 requestAnimationFrame(this.step); } } start() { this.currentFrame = 0; requestAnimationFrame(this.step); } }
方案2:用箭头函数定义类方法
ES6的箭头函数会自动捕获当前上下文的this,用它来定义step方法,就不用手动绑定了,代码更简洁:
class SVGAnimator { constructor(coords, duration) { this.coords = coords; this.duration = duration; this.currentFrame = 0; } // 箭头函数自动绑定this到类实例 step = () => { const progress = this.currentFrame / (this.duration * 60); this.circleLine.setAttribute('cx', this.coords[progress].x); this.circleLine.setAttribute('cy', this.coords[progress].y); this.currentFrame++; if (this.currentFrame < this.duration * 60) { requestAnimationFrame(this.step); } } start() { this.currentFrame = 0; requestAnimationFrame(this.step); } }
方案3:调用时用箭头函数临时包裹
如果不想修改方法定义,也可以在传给requestAnimationFrame的时候,用箭头函数包裹一下,临时保留正确的this指向:
class SVGAnimator { constructor(coords, duration) { this.coords = coords; this.duration = duration; this.currentFrame = 0; } step() { const progress = this.currentFrame / (this.duration * 60); this.circleLine.setAttribute('cx', this.coords[progress].x); this.circleLine.setAttribute('cy', this.coords[progress].y); this.currentFrame++; if (this.currentFrame < this.duration * 60) { // 用箭头函数包裹,确保回调时this指向实例 requestAnimationFrame(() => this.step()); } } start() { this.currentFrame = 0; requestAnimationFrame(() => this.step()); } }
这三个方案都能解决你的问题,个人推荐方案1或2,代码更整洁,也避免了每次回调都创建新箭头函数的微小性能开销。
内容的提问来源于stack exchange,提问作者icicleking
相关产品推荐
相关产品推荐

