Image Maintain Aspect Ratio + Fit to Screen

Hey, I have an image for the background of my game, and I cant get it to look good on all devices.

The image has an aspect ratio of 16: 19 (1920x1080). Currently, I’m setting the displayWidth to the canvas wdith, and the displayHeight to the canvas height.
It works well on my monitor, but when I resize the window, it appears to be very stretched and doesn’t look good.

I want to maintain the aspect ratio of the image, AND make sure it fits to the window. (once i tried using a bit of math to maintain aspect ratio, and if the window is too small there was a big black space below the image.)

So basically I want the image to zoom the middle of the image while preserving the aspect ratio. I don’t know how to do this, and if anyone could give me an idea it would be very helpful!

you can try something like this

const cameraWidth = this.cameras.main.width
const cameraHeight = this.cameras.main.height

const bg = this.add.image(0, 0, 'town2')
  .setOrigin(0)

bg.setScale(Math.max(cameraWidth / bg.width, cameraHeight / bg.height))
3 Likes

Thanks so much! I had to add this line of code to the bottom to make it center correctly:

this.bg.x = 0 - ((this.bg.displayWidth - cameraWidth)/2)