Home > database >  How do you layer an image in a game JS?
How do you layer an image in a game JS?

Time:10-05

I'm making an RPG game, and the character inconsistently loads in front of the background image. So how do you make the image render infront of another? I'm new to the coding community so please understand that I don't know what I'm doing. the HTML looks like this:

<div >
  <canvas  width="352" height="198">     
  </canvas>
</div>

Then the JS

function init() {
  const image = new Image();
  image.onload = () => {
    this.ctx.drawImage(image, 0, 0);
  };
  image.src = "MyMap.png";
  const x = 5;
  const y = 6;

  const hero = new Image();
  hero.onload = () => {
    this.ctx.drawImage(
      hero,
      0, //left cut
      0, //top cut
      27,
      29,
      x * 26 - 15,
      y * 26 - 4,
      32,
      32
    );
  };
  hero.src = "/MyHero.png";
}

CodePudding user response:

The issue is that your hero image might load faster than the background so it will be added to the canvas first.

I would recommend working with promises to make your asynchronous code easier to organise

// Returns a promise that resolves with a loaded Image
const loadImage = async (url) => {
  const image = new Image();
  image.src = url;
  await image.decode();
  return image;
};

async function init() {
  // Draw the background first
  this.ctx.drawImage(await loadImage("MyMap.png"), 0, 0);

  // Now for the hero
  const x = 5;
  const y = 6;

  this.ctx.drawImage(
    await loadImage("/MyHero.png"),
    0, //left cut
    0, //top cut
    27,
    29,
    x * 26 - 15,
    y * 26 - 4,
    32,
    32
  );
}

See https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/decode

  • Related