Javascript

(자바스크립트) HTML5 캔버스: 원 그리기

고니자니 2023. 7. 25. 09:08
반응형

HTML5의 <canvas> 요소로 원을 그리는 자바스트립트 코드입니다.

반지름과 원의 중심 좌표를 조정하여 원의 크기나 위치를 변경할 수 있습니다.

<!DOCTYPE html>
<html>
<head>
    <title>캔버스: 원 그리기</title>
</head>
<body>
    <canvas id="myCanvas" style="background-color:beige" 
       width="300" height="300"></canvas>

    <script>
        // Canvas 요소 가져오기
        var canvas = document.getElementById('myCanvas');
        var ctx = canvas.getContext('2d');

        // 원 그리기 함수
        function drawCircle(x, y, radius) {
            ctx.beginPath();
            ctx.arc(x, y, radius, 0, 2 * Math.PI);
            ctx.stroke(); // 원 그리기
            //ctx.fill();   // 원 채우기
        }

        // 원의 중심 좌표와 반지름 설정
        var centerX = canvas.width / 2;
        var centerY = canvas.height / 2;
        var radius = 50;

        // 원 그리기와 채우기
        drawCircle(centerX, centerY, radius);
    </script>
</body>
</html>

자바스크립트 HTML5 캔버스: 원 그리기

 

반응형

 

원의 내부를 채우기 위해서는 아래의 코드를 추가하면 됩니다.

// 도형이 내부를 채운다.
cts.fill();  

 

특정 색상으로 채우기 위해서는 fillStyle 속성을 사용합니다.

 // 내부를 파란색으로 채우기 위해 fillStyle 설정
ctx.fillStyle = 'blue';

 

<!DOCTYPE html>
<html>
<head>
    <title>캔버스: 원 그리기</title>
</head>
<body>
    <canvas id="myCanvas" style="background-color:beige" 
       width="300" height="300"></canvas>

    <script>
        // Canvas 요소 가져오기
        var canvas = document.getElementById('myCanvas');
        var ctx = canvas.getContext('2d');

        // 원 그리기 함수
        function drawCircle(x, y, radius) {
            ctx.beginPath();
            ctx.arc(x, y, radius, 0, 2 * Math.PI);
            ctx.stroke(); // 원 그리기
            ctx.se
            ctx.fill();   // 원 채우기
        }

        // 원의 중심 좌표와 반지름 설정
        var centerX = canvas.width / 2;
        var centerY = canvas.height / 2;
        var radius = 50;

        // 내부를 파란색으로 채우기 위해 fillStyle 설정
        ctx.fillStyle = 'blue';
        
        // 원 그리기와 채우기
        drawCircle(centerX, centerY, radius);
    </script>
</body>
</html>

자바스크립트 HTML5 캔버스: 원 그리기

 

728x90
반응형