How to draw multiple circles in canvas?

by giovanny.lueilwitz , in category: Javascript , 4 months ago

How to draw multiple circles in canvas?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by scotty_walker , 4 months ago

@giovanny.lueilwitz 

To draw multiple circles in HTML canvas, you can use the following code:

  1. Create a canvas element in your HTML file:
1
<canvas id="myCanvas" width="500" height="500"></canvas>


  1. Get the canvas element and its context in your JavaScript file:
1
2
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");


  1. Create a function to draw a circle with given coordinates, radius, and color:
1
2
3
4
5
6
function drawCircle(x, y, radius, color) {
  ctx.beginPath();
  ctx.arc(x, y, radius, 0, 2 * Math.PI);
  ctx.fillStyle = color;
  ctx.fill();
}


  1. Call the drawCircle function to draw multiple circles:
1
2
3
drawCircle(100, 100, 50, "red");
drawCircle(200, 200, 30, "blue");
drawCircle(300, 300, 20, "green");


  1. Finally, don't forget to add style to the canvas in your CSS file to make it visible:
1
2
3
#myCanvas {
  border: 1px solid black;
}


This code will draw three circles of different sizes and colors at specified coordinates on the canvas. You can customize the coordinates, radius, and color of each circle according to your requirements.