Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

226
Vistas
Javascript - simple requestAnimationFrame gameloop

I'm going to make this very simple. Every frame, I need to render the 'player' wherever they are. Using setInterval, I was able to do this. Unfortunately, that causes it to occasionally flicker and my many hours trying to correct this have been unsuccessful. I've narrowed down the problem to inside this code:

function eachFrame(){
    ctx.clearRect(0,0,canvas.width,canvas.height);
    player.motion();
    player.render();
    setTimeout(window.requestAnimationFrame(eachFrame), 1000 / fps);
};

window.requestAnimationFrame(eachFrame);

When this runs, absolutely nothing appears onscreen.

player.motion updates the player position and handle movement logic. It is not the issue, but I need it.

player.render draws the current player position on the screen. It also is not the problem.

The reason I know player.motion and player.render are completely fine is because, when you get rid of ctx.clearRect(), you can move the player around and it renders perfectly.

function eachFrame(){
    //ctx.clearRect(0,0,canvas.width,canvas.height);
    player.motion();
    player.render();
    setTimeout(window.requestAnimationFrame(eachFrame), 1000 / fps);
};

window.requestAnimationFrame(eachFrame);

When you get rid of that, of course you're now playing snake and you're left with a trail behind the player. ctx.clearRect does it's job, it clears the screen.

This line is the problem: setTimeout(window.requestAnimationFrame(eachFrame), 1000 / fps);

How do I fix it?

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda