How to make multiple Circles using Recursion in javascript?

Viewed 39

let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");

ctx.beginPath();
ctx.linewidth = 2;
ctx.strokeStyle = "black";

function drawCircle(x, y, r) {
  ctx.arc(x, y, r, 0, 2 * Math.PI, false);
  if (r > 2) {
    drawCircle(x + r + 10, y, r * 0.5);
  }
  ctx.stroke();
}
drawCircle(300, 300, 70)
<canvas id="canvas" width="600" height="600"></canvas>

here's an example of the drawing. Circle

I still don't understand recursion, especially in canvas. I find it difficult to understand.

I want to make a row of circles if possible. What should I do? Please help

A simple row of circles will, I just want to understand how will I be able to do it.

1 Answers

I'm not quite sure what it is you are having trouble with. But adjusting the updated value for r and starting a new path for each circle might bring you closer the image you added in your question.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Circles</title>
</head>
<body>
<canvas id="canvas" width="600" height="600"></canvas>
<script>
    let canvas = document.getElementById("canvas");
    let ctx = canvas.getContext("2d");



    function drawCircle(x, y, r) {
        ctx.beginPath();
        ctx.linewidth = 2;
        ctx.strokeStyle = "black";
        ctx.arc(x, y, r, 0, 2 * Math.PI, false);
        ctx.stroke();
        if (r > 2) {
            drawCircle(x + r + r/2 , y, r * 0.5);
        }
    }
    drawCircle(300, 300, 70)
</script>
</body>
</html>

Related