Javascript 画布和requestAnimationFrame出现问题

Javascript 画布和requestAnimationFrame出现问题,javascript,oop,html5-canvas,requestanimationframe,Javascript,Oop,Html5 Canvas,Requestanimationframe,虽然我刚刚完成了一个类似的项目,但我在javaScript的更新方面,这就是为什么这个项目让我感到困惑的原因。我以前的项目工作得很好,但是我使用了所有的globals,这个项目的目的是完全面向对象,但是我在早期遇到了一个问题,我的requestAnimationFrame似乎有问题。我不明白,因为它正在运行,因为我可以看到粒子的Y值发生了变化,但没有动画,它只是在requestAnimationFrame似乎自行决定停止时出现。我将粒子速度(P.vy)设置为令人讨厌的低值,以使粒子保持在画布上,

虽然我刚刚完成了一个类似的项目,但我在javaScript的更新方面,这就是为什么这个项目让我感到困惑的原因。我以前的项目工作得很好,但是我使用了所有的globals,这个项目的目的是完全面向对象,但是我在早期遇到了一个问题,我的requestAnimationFrame似乎有问题。我不明白,因为它正在运行,因为我可以看到粒子的Y值发生了变化,但没有动画,它只是在requestAnimationFrame似乎自行决定停止时出现。我将粒子速度(P.vy)设置为令人讨厌的低值,以使粒子保持在画布上,我不确定这是否与问题有关,因为我不必在我的上一个项目中使用荒谬的值

我现在有一个粒子,我想向上漂浮。游戏结束时,它将只是场景中火焰的一系列粒子中的一个

class Particle {
  constructor(context, width, height) {
    this.x = width / 2;
    this.y = height / 2;
    this.vx = 0;
    this.vy = -0.006;//I had to set like this to keep on the page
    this.radius = Math.random() * 10 + 10;
  }
  update() {
    this.y += this.vy;//change Y pos
  }
};

var App = {
  requestAnimationFrame: window.requestAnimationFrame || window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame || window.msRequestAnimationFrame || 
    function(callback) { 
      return setTimeout(callback, 1000 / 60); 
    },
  canvas: document.getElementById('canvas'),
  ctx: canvas.getContext('2d'),
  P: null,//this will be our particle
  initialize: function() {
    this.canvas.width = window.innerWidth;
    this.canvas.height = window.innerHeight;
    this.P = new Particle(this.ctx, this.canvas.width, this.canvas.height);//create particle
    this.draw();
  },
  draw: function() {
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
    this.ctx.beginPath();
    this.ctx.arc(this.P.x,this.P.y,this.P.radius,0,2*Math.PI);//draw particle
    this.ctx.stroke()
    this.P.update();
    this.requestAnimationFrame(this.draw());
  }
};

App.initialize();
这是我的上一个项目,它(接近)成功,但有着所有的全球性项目:


这是我当前的项目/问题:

+为什么要这样在你的物体上附加rAF?它不会工作,而且已经是全局的了……感谢您的反馈
requestAnimationFrame
需要函数引用,您很幸运没有全局绘制函数,否则它将递归到调用堆栈溢出。应该是
requestAnimationFrame(this.draw.bind(this))
或更好的
requestAnimationFrame(App.draw)
。顺便说一句,仅当您使用
new
创建时,App才应为
App
大写。此外,您还使用了对
ctx:canvas.getContext(“2d”
)的直接引用,上面的一行使用query获取引用
canvas:document.getElementById(“canvas”)
和窗口是默认设置,不是必需的
窗口。innerWidth
innerWidth
相同,非常感谢您的宝贵反馈。这完全把我搞定了,贴上评论回答投票