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

175
Vistas
El lienzo de Javascript parpadea al dibujar marcos

He tenido problemas con esto durante un par de días, no estoy seguro de por qué el texto que estoy representando en el lienzo parpadea tanto. Estoy usando la función requestAnimationFrame(), pero sigue parpadeando.

Lo que quiero que suceda es que el texto se mueva suavemente y se eliminen de la matriz cuando se muevan completamente fuera de la pantalla.

 var canvas = document.getElementById("myCanvas"); var c = canvas.getContext('2d'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; var w = canvas.width; var h = canvas.height; var texts = []; window.addEventListener("load", init); function init() { draw(); mainLoop(); } function mainLoop() { texts.push(createText("wow", "blue")); texts.push(createText("wow", "green")); texts.push(createText("wow", "red")); setTimeout(function() { mainLoop(); }, 100); } function Text(x, y, vx, vy, varText, theColor){ this.x = x; this.y = y; this.vx = vx; this.vy = vy; this.color = theColor; this.draw = function() { drawStroked(varText, this.x, this.y, this.color); } } function drawStroked(text, x, y, color) { c.font = "30px bold Comic Sans MS"; c.strokeStyle = 'black'; c.lineWidth = 8; c.strokeText(text, x, y); c.fillStyle = color; c.fillText(text, x, y); } function createText(varText, color) { var x = (Math.random() * w / 2 ) + w/4; var y = (Math.random() * h / 2) + h/2; var vx = (Math.random() * .5) - .25 var vy = -(Math.random() * 3) - 1 return new Text(x, y, vx, vy, varText, color); } function draw() { c.clearRect(0, 0, c.canvas.width, c.canvas.height); for(var i = 0;i < texts.length; i++) { var currentText = texts[i]; currentText.x += currentText.vx; currentText.y += currentText.vy; currentText.draw(); if(currentText.x>w||currentText.x<0||currentText.y<10){ texts.splice(i, 1); } } requestAnimationFrame(draw); }
 body { margin: 0; padding: 0; overflow: hidden; }
 <!DOCTYPE html> <html> <head> <title>Game Screen</title> </head> <body> <canvas id="myCanvas"></canvas> </body> </html>

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

El parpadeo que está viendo es el resultado de su código de bucle, donde omite elementos de la matriz al eliminar elementos (¿El elemento 3 debe eliminarse? Llama a splice(3, 1) y luego continúa con el bucle en el índice 4. Dado que la matriz cambia cuando llama a splice , debe procesar el elemento 3 nuevamente). En mi humilde opinión, la forma más fácil de solucionar esto es iterar hacia atrás sobre la matriz. Tenga en cuenta que iterar hacia atrás es menos eficiente en la memoria caché de la CPU (porque cada acceso a la matriz conduce a una pérdida de memoria caché), por lo que otra solución sería

 if(currentText.x>w||currentText.x<0||currentText.y<10){ texts.splice(i--, 1); // decrement i after accessing and deleting } 

 var canvas = document.getElementById("myCanvas"); var c = canvas.getContext('2d'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; var w = canvas.width; var h = canvas.height; var texts = []; window.addEventListener("load", init); function init() { draw(); mainLoop(); } function mainLoop() { texts.push(createText("wow", "blue")); texts.push(createText("wow", "green")); texts.push(createText("wow", "red")); setTimeout(function() { mainLoop(); }, 100); } function Text(x, y, vx, vy, varText, theColor){ this.x = x; this.y = y; this.vx = vx; this.vy = vy; this.color = theColor; this.draw = function() { drawStroked(varText, this.x, this.y, this.color); } } function drawStroked(text, x, y, color) { c.font = "30px bold Comic Sans MS"; c.strokeStyle = 'black'; c.lineWidth = 8; c.strokeText(text, x, y); c.fillStyle = color; c.fillText(text, x, y); } function createText(varText, color) { var x = (Math.random() * w / 2 ) + w/4; var y = (Math.random() * h / 2) + h/2; var vx = (Math.random() * .5) - .25 var vy = -(Math.random() * 3) - 1 return new Text(x, y, vx, vy, varText, color); } function draw() { c.clearRect(0, 0, c.canvas.width, c.canvas.height); for(var i = texts.length - 1;i >= 0; i--) { var currentText = texts[i]; currentText.x += currentText.vx; currentText.y += currentText.vy; currentText.draw(); if(currentText.x>w||currentText.x<0||currentText.y<10){ texts.splice(i, 1); } } requestAnimationFrame(draw); }
 body { margin: 0; padding: 0; overflow: hidden; }
 <!DOCTYPE html> <html> <head> <title>Game Screen</title> </head> <body> <canvas id="myCanvas"></canvas> </body> </html>

over 4 years ago · Santiago Trujillo 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