Javascript

(자바스크립트) HTML5 캔버스에 마우스로 그림 그리기

고니자니 2023. 7. 24. 15:45
반응형

HTML5에서 지원하는 <canvas> 태그에 마우스를 움직여서 그림을 그리는 코드입니다.

캔버스에 그림을 그리는 코드는 자바스크립트를 사용합니다.

<!DOCTYPE html>
<html>
<head>
    <title>캔버스: 마우스로 그림 그리기</title>
    <style>
        canvas {
            border: 1px solid #000;
        }
    </style>
</head>
<body>
    <canvas id="drawCanvas" width="800" height="600"></canvas>

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

        // Initialize variables to track mouse movement and drawing state
        let isDrawing = false;
        let lastX = 0;
        let lastY = 0;

        // Function to handle mouse down event
        function handleMouseDown(event) {
            isDrawing = true;
            [lastX, lastY] = [event.offsetX, event.offsetY];
        }

        // Function to handle mouse move event
        function handleMouseMove(event) {
            if (!isDrawing) return; // Exit if not drawing

            const currentX = event.offsetX;
            const currentY = event.offsetY;

            // Draw a line from the last position to the current position
            ctx.beginPath();
            ctx.moveTo(lastX, lastY);
            ctx.lineTo(currentX, currentY);
            ctx.stroke();

            // Update last position to the current position
            [lastX, lastY] = [currentX, currentY];
        }

        // Function to handle mouse up and mouse leave events
        function handleMouseUp() {
            isDrawing = false;
        }

        function handleMouseLeave() {
            isDrawing = false;
        }

        // Attach event listeners to the canvas
        canvas.addEventListener('mousedown', handleMouseDown);
        canvas.addEventListener('mousemove', handleMouseMove);
        canvas.addEventListener('mouseup', handleMouseUp);
        canvas.addEventListener('mouseleave', handleMouseLeave);
    </script>
</body>
</html>

(자바스크립트) HTML5 캔버스에 마우스로 그림 그리기

 

 

728x90
반응형