Javascript

(자바스크립트) HTML5 캔버스: 움직이는 도형 만들기

고니자니 2023. 7. 25. 10:49
반응형

HTML5의 <canvas> 요소와 자바스크립트로 움직이는 도형을 만드는 코드입니다.

이 코드는 캔버스에 가로로 이동하는 크기가 다른 세 개의 원을 만듭니다.

도형은 캔버스의 벽에 닿으면 반대 반향으로 다시 움직입니다.

<!DOCTYPE html>
<html>
<head>
  <title>Shapes Moving with HTML5 Canvas</title>
</head>
<body>
  <canvas id="myCanvas" width="400" height="300"></canvas>

  <script>
    // Get the canvas and 2D context
    const canvas = document.getElementById('myCanvas');
    const ctx = canvas.getContext('2d');

    // Create an array to store the circles
    const circles = [
      { x: 50, y: 150, radius: 30, dx: 3, color: 'blue' }, // Circle 1
      { x: 150, y: 150, radius: 40, dx: 2, color: 'green' }, // Circle 2
      { x: 250, y: 150, radius: 25, dx: 4, color: 'red' }, // Circle 3
    ];

    function drawCircle(x, y, radius, color) {
      ctx.beginPath();
      ctx.arc(x, y, radius, 0, Math.PI * 2);
      ctx.fillStyle = color;
      ctx.fill();
      ctx.closePath();
    }

    function animate() {
      // Clear the canvas
      ctx.clearRect(0, 0, canvas.width, canvas.height);

      // Update and draw each circle
      circles.forEach(circle => {
        circle.x += circle.dx;
        if (circle.x + circle.radius > canvas.width || circle.x - circle.radius < 0) {
          circle.dx = -circle.dx; // Reverse direction on hitting the canvas edges
        }
        drawCircle(circle.x, circle.y, circle.radius, circle.color);
      });

      requestAnimationFrame(animate); // Repeat the animation
    }

    // Start the animation
    animate();
  </script>
</body>
</html>

(자바스크립트) HTML5 캔버스: 움직이는 도형 만들기

728x90
반응형