How to make a circle of variable radius

Viewed 54

So I want to make a increasing size bubble kind circle of different color upon clicking on the blank page if I keep clicked on that some initial size circle its size should be keep increasing... until I stop my mouse which was clicked on the circle .I want to use html CSS and JS how I can achieve that?

1 Answers

You can use canvas and getContext('2d'), check inline comments for more details:

// Set canvas element
const canvas = document.getElementById('circle');
// Init canvas context if possible
const ctx = canvas?.getContext ? canvas.getContext('2d') : null;

// Set initial Radius and modification radius
let R = 0;
let modR = 0;

// Draw function
const draw = (ctx, mod) => {
  // If canvas context not initialized properly
  // print error and return
  if(!ctx) return console.error("Can't get canvas context");
  
  // If inc mod and modification radius less then or equal current radius
  // or dec mod and modification radius greater then or equal current radius
  // stop animating
  if(
    mod == "inc" && modR <= R ||
    mod == "dec" && modR >= R
  ) return;

  // Increase/decrease radius on 0.5
  // Here you can control animation speed:
  // increase value to speed up, decrease to slow down
  if(mod == "inc") R += 0.5;
  if(mod == "dec") R -= 0.5;

  // Position
  let X = canvas.width / 2;
  let Y = canvas.height / 2;

  // Clear previous circle
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // Draw new circle
  ctx.beginPath();
  ctx.arc(X, Y, R, 0, 2 * Math.PI, false);
  ctx.fillStyle = '#FF0000';
  ctx.fill();

  // Try to animate resizing
  requestAnimationFrame(() => draw(ctx, mod));
}

// Circle increase function
const inc = r => {
  // Check if requested circle will fit canvas area
  // If not, return
  if(canvas?.width && modR * 2 >= canvas.width) return;
  
  // Increase total radius
  modR += r;

  // Draw new circle with increase mode
  draw(ctx, "inc");
}

// Circle decrease function
const dec = r => {
  // Check if requested circle is not less then
  // some size or return
  if(modR * 2 <= 10) return;
  
  // Decrease total radius
  modR -= r;
  
  // Draw new circle with decrease mode
  draw(ctx, "dec");
}
body {
  text-align: center;
}
<html>
  <head>
    <meta charset=utf-8 />
    <title>Draw a circle</title>
  </head>
  <body onload="inc(5);">
    <canvas id="circle" width="150" height="150"></canvas>
    <div class="btn">
      <button onClick="inc(5);">Increase</button>
      <button onClick="dec(5);">Decrease</button>
    </div>
  </body>
</html>

Related