Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

246
Views
Generar colores infinitos para matriz

Quiero crear una matriz llena de colores aleatorios, que nunca se agote para generar bolas aleatorias con colores aleatorios. Entonces, en lugar de tener solo 5 colores (azul, rojo, verde, amarillo, blanco) para elegir, quiero un color diferente para cada pelota.

código completo:

Ya he probado:

 var randomColor = Math.floor(Math.random()*16777215).toString(16);

Aquí solo obtengo un color aleatorio para cada bola. Y también he usado bucles, que probablemente sea la respuesta correcta, pero la implementé incorrectamente.

JS:

 var ballArray = []; var colorArray = ['blue','red','green','yellow','white']; var gravity = 0.9; function drawBall() { for (var i = 0; i < ballArray.length; i++) { var ball = ballArray[i]; ctx.fillStyle = ball.color; ctx.beginPath(); ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2); ctx.fill(); ctx.closePath(); ball.x += ball.xd; if (ball.x + ball.radius > screenWidth || ball.x - ball.radius < 0) { ball.xd *= -1; }
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

No estoy seguro de haberte entendido bien. ¿Quieres que cada bola tenga un color aleatorio diferente sin la repetición de colores? ¿O simplemente arreglar el segundo código JSFiddle para generar bolas con números aleatorios sin parpadeo?

Si desea tener un color único para cada bola , puede almacenar colores ya utilizados en una matriz y verificar si el color recién generado está incluido en la matriz. Para eso, usaría este código:

 var ballArray = []; var usedColors = []; var gravity = 0.9; function generateNewColor() { var letters = '0123456789ABCDEF'; var colorIncluded = true; while (colorIncluded == true) { var color = '#'; // generate new color for (var i = 0; i < 6; i++) { color += letters[Math.floor(Math.random() * 16)]; } // check if the color is already used var used = false; for(var i = 0; i < usedColors.length; i++){ if(usedColors[i] == color){ used = true; break; } } if(!used){ break; } } usedColors.push(color); return color; }

Sin embargo, este método no es muy efectivo para una gran cantidad de bolas generadas.

Para corregir el parpadeo en su código, simplemente borre la función que devuelve un número aleatorio en una función Ball():

 this.color = getRndColor();

Y usa el color generado en una función dibujarBall():

 ctx.fillStyle = ball.color;
about 4 years ago · Juan Pablo Isaza Report

0

defina su randomColor directamente, reemplace

 this.color = colorArray[randomNumber(0, colorArray.length - 1)];

con

 this.color = '#' + Math.floor(Math.random()*16777215).toString(16);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!