PROGRAMMING/JavaScript

html canvas - 클릭하면 나눠지는 공

OJR 2023. 3. 31. 23:30

 

 

<!DOCTYPE html>
<html>
<head>
  <style>
    canvas {
      border: 1px solid black;
    }
  </style>
</head>
<body>
  <canvas id="myCanvas" width="500" height="500"></canvas>
  <script>
  const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

class Circle {
  constructor(x, y, radius) {
    this.x = x;
    this.y = y;
    this.radius = radius;
  }

  draw() {
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
    ctx.stroke();
    ctx.closePath();
  }
}

let circles = [new Circle(250, 250, 50)];
circles[0].draw();

canvas.addEventListener('click', (event) => {
  const rect = canvas.getBoundingClientRect();
  const x = event.clientX - rect.left;
  const y = event.clientY - rect.top;

  for (let i = circles.length - 1; i >= 0; i--) {
    const circle = circles[i];
    const distance = Math.sqrt(Math.pow(x - circle.x, 2) + Math.pow(y - circle.y, 2));

    if (distance <= circle.radius) {
      circles.splice(i, 1);
      circles.push(new Circle(circle.x - circle.radius / 2, circle.y, circle.radius / 2));
      circles.push(new Circle(circle.x + circle.radius / 2, circle.y, circle.radius / 2));
      break;
    }
  }

  ctx.clearRect(0, 0, canvas.width, canvas.height);
  circles.forEach(circle => circle.draw());
});

  </script>
</body>
</html>
반응형