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

415
Views
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 answers
Answer question

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 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!