본문 바로가기
■ 프로그래밍, 개발

자바스크립트로 별풍선 그리기

by 토크맨 2023. 6. 2.
반응형

HTML5 <canvas> 요소를 사용하여 별과 풍선을 그리는 간단한 예제입니다.

 

=================================================================

<!DOCTYPE html>
<html>
<head>
  <style>
    canvas {
      border: 1px solid black;
    }
  </style>
</head>
<body>
  <canvas id="myCanvas" width="400" height="400"></canvas>

  <script>
    // 캔버스 요소 가져오기
    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext("2d");

    // 별 그리기
    function drawStar(x, y, radius, spikes, rotation) {
      var xCenter = x;
      var yCenter = y;
      var outerRadius = radius;
      var innerRadius = radius / 2;

      var rot = Math.PI / 2 * 3;
      var step = Math.PI / spikes;

      context.beginPath();
      context.moveTo(xCenter, yCenter - outerRadius);

      for (var i = 0; i < spikes; i++) {
        x = xCenter + Math.cos(rot) * outerRadius;
        y = yCenter + Math.sin(rot) * outerRadius;
        context.lineTo(x, y);
        rot += step;

        x = xCenter + Math.cos(rot) * innerRadius;
        y = yCenter + Math.sin(rot) * innerRadius;
        context.lineTo(x, y);
        rot += step;
      }

      context.lineTo(xCenter, yCenter - outerRadius);
      context.closePath();
      context.lineWidth = 5;
      context.strokeStyle = "gold";
      context.fillStyle = "gold";
      context.fill();
      context.stroke();
    }

    // 풍선 그리기
    function drawBalloon(x, y, radius, color) {
      context.beginPath();
      context.arc(x, y, radius, 0, 2 * Math.PI, false);
      context.fillStyle = color;
      context.fill();
      context.lineWidth = 3;
      context.strokeStyle = "black";
      context.stroke();
    }

    // 별 그리기 호출
    drawStar(200, 200, 50, 5, 0);

    // 풍선 그리기 호출
    drawBalloon(300, 100, 30, "red");
  </script>
</body>
</html>

=======================================================================

 

위의 예제를 실행하면 캔버스 요소에 별과 풍선이 그려집니다.

drawStar 함수는 주어진 좌표(x, y), 반지름(radius), 가지 수(spikes),

회전(rotation)에 따라 별을 그리는 함수입니다.

drawBalloon 함수는 주어진 좌표(x, y), 반지름(radius), 색상(color)에

따라 풍선을 그리는 함수입니다.

이 예제는 <canvas> 요소를 사용하여 그래픽을 그리는 기본적인 방법을 보여줍니다.

별과 풍선의 모양, 위치, 색상 등을 원하는 대로 수정하여 사용할 수 있습니다.

 

 

반응형

댓글