<!DOCTYPE html>
<html>
<head>
  <style>
    #canvas {
      border: 1px solid #000;
    }
  </style>
</head>
<body>
  <canvas id='canvas' width='800' height='600'></canvas>
  <script>
    // SETUP
    let canvas = document.getElementById('canvas');
    let ctx = canvas.getContext('2d');
    let x = 50;
    let y = 50;
    let width = 20;
    let height = 20;
    let speed = 2;

    // DRAW
    function draw() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.fillRect(x, y, width, height);
    }
    draw();

    // CONTROLS
    document.onkeydown = function(e) {
      switch (e.keyCode) {
        case 37: // Left
          x -= speed;
          break;
        case 38: // Up
          y -= speed;
          break;
        case 39: // Right
          x += speed;
          break;
        case 40: // Down
          y += speed;
          break;
      }
      draw();
    };

  </script>
</body>
</html>
HTML Platformer Game Code - Simple Example

原文地址: https://www.cveoy.top/t/topic/lnRR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录