app.js 982 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. function loadTexture(path) {
  2. return new Promise((resolve) => {
  3. const img = new Image();
  4. img.src = path;
  5. img.onload = () => {
  6. resolve(img);
  7. };
  8. });
  9. }
  10. function createEnemies(ctx, canvas, enemyImg) {
  11. const MONSTER_TOTAL = 5;
  12. const MONSTER_WIDTH = MONSTER_TOTAL * 98;
  13. const START_X = (canvas.width - MONSTER_WIDTH) / 2;
  14. const STOP_X = START_X + MONSTER_WIDTH;
  15. for (let x = START_X; x < STOP_X; x += 98) {
  16. for (let y = 0; y < 50 * 5; y += 50) {
  17. ctx.drawImage(enemyImg, x, y);
  18. }
  19. }
  20. }
  21. window.onload = async () => {
  22. canvas = document.getElementById("canvas");
  23. ctx = canvas.getContext("2d");
  24. const heroImg = await loadTexture("assets/player.png");
  25. const enemyImg = await loadTexture("assets/enemyShip.png");
  26. ctx.fillStyle = "black";
  27. ctx.fillRect(0, 0, canvas.width, canvas.height);
  28. ctx.drawImage(
  29. heroImg,
  30. canvas.width / 2 - 45,
  31. canvas.height - canvas.height / 4
  32. );
  33. createEnemies(ctx, canvas, enemyImg);
  34. };