Skip to content
Advertisement

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.

Advertisement

Answer

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>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement