• Jobs
  • About Us
  • Jobs
    • Home
    • Jobs
    • Courses and challenges
  • Businesses
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

294
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.

over 3 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>

over 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Show me some job opportunities
There's an error!