onload не работает в классе - PullRequest
0 голосов
/ 30 июня 2018

Вот мой код (извините, он длинный):

class Vec {
  constructor(x = 0, y = 0) {
    this.x = x;
    this.y = y;
  }
}

class Enemy {
  constructor() {
    this.pos = new Vec;
    this.vel = new Vec;
    this.image = new Image();
    this.image.onload = () => {
      this.image.width /= 4;
      this.image.height /= 4;
    }
    this.image.src = "https://vignette.wikia.nocookie.net/scribblenauts/images/8/8d/Steel_Spike.png/revision/latest?cb=20130105173440";
    this.pos.x = WIDTH;
    this.pos.y = HEIGHT - GROUND_Y - this.image.height;
  }
}

// setup
const ctx = document.getElementById("canvas").getContext("2d");

const WIDTH = 600;
const HEIGHT = 400;
const GROUND_Y = 50;

let enemies = [];

let lastUpdate = 0;

function update(dt, now) {
  // create enemy
  if (now - lastUpdate > 2000) {
    lastUpdate = now;
    enemies.push(new Enemy);
  }

  for (let i = 0; i < enemies.length; i++) {
    // update enemy
    enemies[i].vel.x = -300;
    enemies[i].pos.x += enemies[i].vel.x * dt;

    if (enemies[i].pos.x + enemies[i].image.width < 0)
      enemies.splice(i, 1);
  }
}

function draw() {
  // draw background
  ctx.fillStyle = "#000";
  ctx.fillRect(0, 0, WIDTH, HEIGHT);

  // draw ground
  ctx.fillStyle = "#0f0";
  ctx.fillRect(0, HEIGHT - GROUND_Y, WIDTH, GROUND_Y);

  // draw enemy
  ctx.fillStyle = "#f00";
  for (let i = 0; i < enemies.length; i++) {
    ctx.drawImage(enemies[i].image, enemies[i].pos.x, enemies[i].pos.y, enemies[i].image.width, enemies[i].image.height);
  }
}

// game loop (not important for this question)
const TIMESTEP = 1 / 60;
let accumulator = 0;
let lastRender = 0;

function loop(timestamp) {
  accumulator += (timestamp - lastRender) / 1000;
  lastRender = timestamp;
  while (accumulator >= TIMESTEP) {
    update(TIMESTEP, timestamp);
    accumulator -= TIMESTEP;
  }
  draw();

  requestAnimationFrame(loop);
}

requestAnimationFrame(loop);
<!DOCTYPE html>
<html>

<head>
  <title>Jump_Over_It</title>
  <link href="css/default.css" rel="stylesheet" />
</head>

<body>
  <canvas id="canvas" width="600" height="400"></canvas>
  <script src="js/main.js"></script>
</body>

</html>

Когда я запускаю этот код, позиция у шипа портится (запустите код, чтобы понять, что я имею в виду). Предполагается, что шип находится на земле.

Я знаю, что это так:

this.image.onload = () => { this.image.width /= scale; this.image.height /= scale; }

часть кода, которая не работает, но я не понимаю, почему она не работает. Здесь я пытаюсь добиться того, чтобы изображения были меньше по размеру. Причина, по которой я добавил this.image.onload, заключается в том, что загрузка изображения выполняется асинхронно, поэтому мне нужно подождать, пока изображение загрузится, чтобы изменить ширину и высоту изображения.

Как я могу сделать эту работу?

...