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

145
Vistas
Why does rectX and rectY become NaN?

rectX and rectY are initialized as 0. Afterwards I'm adding 0 to either 0, or a small amount. I do not understand why it would become NaN all of the sudden. Can someone help me understand?

const context = document.querySelector("#background").getContext("2d");
let rectX = 0;
let rectY = 0;
let movingSpeed = 50;
let secondsPassed = 0;
let oldTimeStamp = 0;
let timePassed = 0;

// Listen to the onLoad event
window.onload = init;

// Trigger init function when the page has loaded
function init() {
  background.width = window.innerWidth;
  background.height = window.innerHeight;

  // Request an animation frame for the first time
  // The gameLoop() function will be called as a callback of this request
  window.requestAnimationFrame(gameLoop);
}

function gameLoop(timeStamp) {
console.log("timestamp", timeStamp);
  // Calculate how much time has passed
  secondsPassed = (timeStamp - oldTimeStamp) / 1000;
  oldTimeStamp = timeStamp;

  // Pass the time to the update
  update(secondsPassed);
  draw();

  window.requestAnimationFrame(gameLoop);
}

function update(secondsPassed) {
  // Use time to calculate new position
  rectX += movingSpeed * secondsPassed;
  rectY += movingSpeed * secondsPassed;
  console.log("rect", rectX, rectY);
}

function draw() {
  context.fillStyle = "#ff8080";
  context.fillRect(rectX, rectY, 150, 100);
}
gameLoop();
* {
  box-sizing: border-box;
  overflow: hidden;
  outline: none;
  margin: 0;
  border: 0;
  padding: 0;
  display: default;
}

html {
  background-color: dimgrey;
}

body {
  background-color: rgb(255, 93, 93);
}

canvas {
  image-rendering: pixelated;
  position: absolute;
  top: 0;
  left: 0;
}

#background {
  background-color: rgb(17, 17, 17);
}
<canvas id="background"></canvas>

All it does it add number to an initial number of 0. So how does JS suddenly see it as not a number?

Some other text.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

The other answers are correct, but here's how to fix it.

requestAnimationFrame does not get a timeStamp as a parameter, so instead use performance.now() (more precise than Date.now().getTime()) to initialize the timeStamp

/** @format */

// Declare as variable
const context = document.querySelector("#background").getContext("2d");
let rectX = 0;
let rectY = 0;
let movingSpeed = 50;
let secondsPassed = 0;
let oldTimeStamp = performance.now();
let timePassed = 0;

// Listen to the onLoad event
window.onload = init;

// Trigger init function when the page has loaded
function init() {
  background.width = window.innerWidth;
  background.height = window.innerHeight;

  // Request an animation frame for the first time
  // The gameLoop() function will be called as a callback of this request
  window.requestAnimationFrame(gameLoop);
}

function gameLoop() {
  const timeStamp = performance.now()
  // Calculate how much time has passed
  secondsPassed = (timeStamp - oldTimeStamp) / 1000;
  oldTimeStamp = timeStamp;

  // Pass the time to the update
  update(secondsPassed);
  draw();

  window.requestAnimationFrame(gameLoop);
}

function update(secondsPassed) {
  // Use time to calculate new position
  rectX += movingSpeed * secondsPassed;
  rectY += movingSpeed * secondsPassed;
}

function draw() {
  context.fillStyle = "#ff8080";
  context.fillRect(rectX, rectY, 150, 100);
}
gameLoop();
* {
  box-sizing: border-box;
  overflow: hidden;
  outline: none;
  margin: 0;
  border: 0;
  padding: 0;
  display: default;
}

html {
  background-color: dimgrey;
}

body {
  background-color: rgb(255, 93, 93);
}

canvas {
  image-rendering: pixelated;
  position: absolute;
  top: 0;
  left: 0;
}

#background {
  background-color: rgb(17, 17, 17);
}
<canvas id="background"></canvas>

about 4 years ago · Juan Pablo Isaza Denunciar

0

As 'mplungjan' mentioned. You can call the loop initially with 0 as a parameter. It fixes the problem quite simply. -> gameloop() as gameloop(0).

The actual proper way to do it, however, is to call the loop initially as window.requestAnimationFrame(gameLoop);.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You call gameLoop(); without parameters. So secondsPassed = (undefined - oldTimeStamp) / 1000; becomes undefined so eventuall you end up with rectX += movingSpeed * undefined;

about 4 years ago · Juan Pablo Isaza Denunciar
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