Javascript

(자바스크립트) HTML5 캔버스: 키보드로 이미지 움직이기

고니자니 2023. 8. 3. 09:24
반응형

이전에 작성했던 키보드로 도형을 움직이는 코드를

도형 대신에 이미지로 변경해 봤습니다.

 

 

 

(자바스크립트) HTML5 캔버스: 키보드로 도형 움직이기

HTML5의 요소를 이용해서 웹브라우저에 직접 그림을 그리거나 이미지 등을 출력할 수 있습니다. 다음 코드는 HTML5의 캔버스에 도형을 그리고 키보드의 상하좌우 키를 이용해서 도형을 움직이는

gonyzany.tistory.com

 

 

키보드로 이미지 움직이기

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>캔버스: 이미지 출력하기</title>
    </head>
<body>
<!-- <h3>캔버스: 이미지 출력하기</h3>
<hr> -->
<canvas id="myCanvas" style="background-color:white" width="300" height="300">
</canvas>

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

    // Set the initial position of the image
    let x = 100;
    let y = 100;
    const moveSpeed = 5;

    // Load the image
    const image = new Image();
    image.src = 'dog.png'; // Replace 'path_to_your_image.png' with the actual path to your image

    // Function to draw the image on the canvas
    function drawImage() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(image, x, y, image.width, image.height);
    }

    // Function to handle keyboard events
    function handleKeyDown(event) {
        // Arrow keys (left, right, up, down) have key codes 37, 39, 38, 40
        switch (event.keyCode) {
            case 37: // Left arrow
                x -= moveSpeed;
                break;
            case 39: // Right arrow
                x += moveSpeed;
                break;
            case 38: // Up arrow
                y -= moveSpeed;
                break;
            case 40: // Down arrow
                y += moveSpeed;
                break;
        }
    }

    // Event listener for keydown events
    document.addEventListener('keydown', handleKeyDown);

    // Function to update the canvas
    function updateCanvas() {
        drawImage();
        requestAnimationFrame(updateCanvas);
    }

    // Wait for the image to load before starting the animation
    image.onload = function() {
        updateCanvas();
    };
</script>

</body>
</html>

웰시코기

 

728x90
반응형