Javascript

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

고니자니 2023. 7. 27. 08:33
반응형

HTML5의 <canvas> 요소를 이용해서 웹브라우저에 직접 그림을 그리거나 이미지 등을 출력할 수 있습니다.

다음 코드는 HTML5의 캔버스에  도형을 그리고 키보드의 상하좌우 키를 이용해서 도형을 움직이는 자바스크립트 코드입니다.

<!DOCTYPE html>
<html>
<head>
  <title>Shapes Moving with HTML5 Canvas</title>
</head>
<body>
  <canvas id="myCanvas" width="400" height="300"
     style="border: 1px solid black;"></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 shape
    let x = 150;
    let y = 100;
    const shapeSize = 50;
    const moveSpeed = 5;

    // Function to draw the shape on the canvas
    function drawShape() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.fillStyle = "rgb(255, 0,0)";
        ctx.fillRect(x, y, shapeSize, shapeSize);
    }

    // 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() {
        drawShape();
        requestAnimationFrame(updateCanvas);
    }

    // Start the animation
    updateCanvas();
</script>
</body>
</html>

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

 

 


 

 

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

이전에 작성했던 키보드로 도형을 움직이는 코드를 도형 대신에 이미지로 변경해 봤습니다. (자바스크립트) HTML5 캔버스: 키보드로 도형 움직이기 HTML5의 요소를 이용해서 웹브라우저에 직접 그

gonyzany.tistory.com

 

728x90
반응형