4

I'm making a kaboom.js game and I want to set the background of a scene to an image. I can only find solutions on changing the background to a colour. I hope someone can help!

1 Answers1

9

In Kaboom.js there is no special support for background images. However you can use a regular game object with a sprite component as a background image. Here's a simple example:

async function init() {
  kaboom();
  let bgImage = await loadSprite("background", "https://www.paulwheeler.us/files/windows-95-desktop-background.jpg");

  let background = add([
    sprite("background"),
    // Make the background centered on the screen
    pos(width() / 2, height() / 2),
    origin("center"),
    // Allow the background to be scaled
    scale(1),
    // Keep the background position fixed even when the camera moves
    fixed()
  ]);
  // Scale the background to cover the screen
  background.scaleTo(Math.max(
    width() / bgImage.tex.width,
    height() / bgImage.tex.height
  ));
}

init();
<script src="https://cdn.jsdelivr.net/npm/kaboom@2000.1.8/dist/kaboom.js"></script>
Paul Wheeler
  • 18,988
  • 3
  • 28
  • 41