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

414
Vistas
javascript: Display different color circles in different sizes

I have a homework assignment that asks me to print two alternating circle colors with different sizes. The end-result would look like this:

enter image description here

Right now, I am struggling to print the blue color circle on top of the red color circle and this is the code, i have written:

    canvas = document.getElementById("testCanvas");
    context = canvas.getContext("2d");
    
    centerX = canvas.width / 2;
    centerY = canvas.height / 2;
    
    //Creates a red color circle
    context.arc(centerX, centerY, 200, 0, 2 * Math.PI);
    context.fillStyle = 'red';
    context.fill();
    
    //Creates a blue color circle on top of the red color circle
    context.arc(centerX, centerY, 150, 0, 2 * Math.PI);
    // context.lineWidth=5;
    context.fillStyle = 'blue';
    context.stroke();
<canvas id="testCanvas" width="400" height="400"></canvas>

I am having trouble with the last block of code because if I say fill() on the last line of code, then blue color dominates the canvas. Any help would be greatly appreciated. Thanks in advance.

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

0

You have to loop through and draw circles increasing/decreasing radius. And toggle the color inside the loop. Each time to draw a circle you need to use beginPath() to start and closePath() to prevent overlaps.

const canvas = document.getElementById("testCanvas");
const context = canvas.getContext("2d");

const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
let radius = centerX;
let color = "red";

while (radius > 0) {
  context.beginPath();
  context.fillStyle = color;
  context.arc(centerX, centerY, radius, 0, 2 * Math.PI);
  context.fill();
  context.closePath();
  color = color === "red" ? "blue" : "red";
  radius -= 25;
}
<canvas id="testCanvas" width="400" height="400"></canvas>

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