Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

146
Visualizações
¿Por qué rectX y rectY se convierten en NaN?

rectX y rectY se inicializan como 0. Luego estoy agregando 0 a 0, o una pequeña cantidad. No entiendo por qué se convertiría en NaN de repente. ¿Puede alguien ayudarme a entender?

 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>

Todo lo que hace es agregar un número a un número inicial de 0. Entonces, ¿cómo JS de repente lo ve como si no fuera un número?

Algún otro texto.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Las otras respuestas son correctas, pero aquí se explica cómo solucionarlo.

requestAnimationFrame no obtiene una timeStamp de tiempo como parámetro, por lo tanto, use performance.now() (más preciso que Date.now().getTime() ) para inicializar la timeStamp de tiempo

 /** @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 Relatório

0

Como se mencionó 'mplungjan'. Puede llamar al bucle inicialmente con 0 como parámetro. Soluciona el problema de forma bastante sencilla. -> gameloop() como gameloop(0) .

Sin embargo, la forma correcta de hacerlo es llamar al bucle inicialmente como window.requestAnimationFrame(gameLoop); .

about 4 years ago · Juan Pablo Isaza Relatório

0

Llamas a gameLoop(); sin parámetros. Así que secondsPassed = (undefined - oldTimeStamp) / 1000; se vuelve undefined , por lo que eventualmente terminará con rectX += movingSpeed * undefined;

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda