Untitled

mail@pastecode.io avatar
unknown
javascript
2 years ago
1.1 kB
31
Indexable
Never
const main = {
  state: {
    ctx: initializeCanvasContext(),
    player: initializePlayer(),
  },
};

function initializePlayer() {
  return {
    image: new Image("/assets/images/player.png"),
    x: 0,
    y: 0,
    width: 50,
    height: 48,
  };
}

function initializeCanvasContext() {
  const canvasElement = document.querySelector("canvas#game");
  const ctx = canvasElement.getContext("2d");
  const canvas = ctx.canvas;
  canvas.width = 600;
  canvas.height = 600;
  return ctx;
}

function drawPlayer(player) {
  main.state.ctx.drawImage(
    player.image,
    player.x,
    player.y,
    player.width,
    player.height
  );
}

function drawBackground(image) {
  const { canvas } = main.state.ctx;
  main.state.ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
}

function play() {
  const { player } = main.state;
  const backgroundImage = new Image("/assets/images/space.png");
  requestAnimationFrame(function draw() {
    drawBackground(backgroundImage);
    drawPlayer(player);
    requestAnimationFrame(draw);
  });
}

play();