본문 바로가기
JavaScript

[JavaScript] 마우스 드래그로 캔버스에 네모와 동그라미 그리기

by teamnova 2024. 8. 6.
728x90

 

안녕하세요 오늘은 자바스크립트에서 

마우스를 드래그하여 원하는 크기의 네모, 동그라미를 그려보도록 하겠습니다.

 

html 의 <canvas> 요소를 사용해보겠습니다. 

 

 

먼저 html 파일을 생성해줍니다. 

 

  html_shapes.html 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>마우스로 도형 그리기</title>
</head>
<body>
    <canvas id="myCanvas" width="500" height="500" style="border:1px solid #000000;"></canvas>
    <div>
        <button id="drawRect">네모 그리기</button>
        <button id="drawCircle">동그라미 그리기</button>
    </div>
    <script src="js_shapes.js"></script>
</body>
</html>

 

 

같은 폴더 안에 js 파일을 만들어줍니다. 

js_shapes.js 

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
let drawingShape = '';
let isDrawing = false;
let startX, startY;

document.getElementById('drawRect').addEventListener('click', () => {
    drawingShape = 'rectangle';
});

document.getElementById('drawCircle').addEventListener('click', () => {
    drawingShape = 'circle';
});

canvas.addEventListener('mousedown', (e) => {
    isDrawing = true;
    const rect = canvas.getBoundingClientRect();
    startX = e.clientX - rect.left;
    startY = e.clientY - rect.top;
});

canvas.addEventListener('mousemove', (e) => {
    if (!isDrawing) return;

    const rect = canvas.getBoundingClientRect();
    const currentX = e.clientX - rect.left;
    const currentY = e.clientY - rect.top;
    const width = currentX - startX;
    const height = currentY - startY;

    ctx.clearRect(0, 0, canvas.width, canvas.height);
    if (drawingShape === 'rectangle') {
        drawRectangle(startX, startY, width, height);
    } else if (drawingShape === 'circle') {
        const radius = Math.sqrt(width * width + height * height);
        drawCircle(startX, startY, radius);
    }
});

canvas.addEventListener('mouseup', () => {
    isDrawing = false;
});

function drawRectangle(x, y, width, height) {
    ctx.fillStyle = '#FF0000';
    ctx.fillRect(x, y, width, height);
}

function drawCircle(x, y, radius) {
    ctx.beginPath();
    ctx.arc(x, y, radius, 0, 2 * Math.PI);
    ctx.fillStyle = '#00FF00';
    ctx.fill();
    ctx.stroke();
}

 

 

결과 화면입니다