# Scale camera to fit screen size unity

My background and gameobjects are 2d sprites not UI images ,I want to know how to make my background scale with screen size and positions of 2d sprits on it don't change after building game (webGl) like scale canvas with screen size and anchor points in UI elements .

Before building the game

After building

• It looks like your content has scaled perfectly to match the height of your display area. Would you like it to scale to match the width instead? Note that this will mean you show more area above and below the currentlt displayed content, which depending on your setup might reveal gaps or require letterboxing. Jan 21 '19 at 12:12
• I want to make it to match the width like it match the height of my display area. and don't display the blue area of the camera Jan 21 '19 at 12:29

You can adjust the camera's height so it scales with the width of the screen like so:

(Place this script on your Camera object)

[ExecuteInEditMode]
[RequireComponent(typeof(Camera))]
public class MatchWidth : MonoBehaviour {

// Set this to the in-world distance between the left & right edges of your scene.
public float sceneWidth = 10;

Camera _camera;
void Start() {
_camera = GetComponent<Camera>();
}

// Adjust the camera's height so the desired scene width fits in view
// even if the screen/window size changes dynamically.
void Update() {
float unitsPerPixel = sceneWidth / Screen.width;

float desiredHalfHeight = 0.5f * unitsPerPixel * Screen.height;

_camera.orthographicSize = desiredHalfHeight;
}
}


If you're using a perspective camera, then instead you'd use...

public float horizontalFoV = 90.0f;

// ...

void Update() {
float halfWidth = Mathf.Tan(0.5f * horizontalFoV * Mathf.Deg2Rad);

float halfHeight = halfWidth * Screen.height / Screen.width;

float verticalFoV = 2.0f * Mathf.Atan(halfHeight) * Mathf.Rad2Deg;

_camera.fieldOfView = verticalFoV;
}


If you want to shrink your viewport to add letterboxes instead of showing additional height above/below, you can use the technique described in this answer.

• Is there any drawback to using this script to always scale my camera rather than having to write flexible code all the time? I don't see why this isn't a built-in way to apply this technique in-engine. Aug 10 '20 at 19:05
• I'd suspect it's not built-in because it's trivial to write for ourselves in the rare instances when we need it. An event-based approach would be a bit more efficient than the update polling I show above, but overall the cost of this script should be very minor. Aug 10 '20 at 19:10
• I suspect you don't wanna do this in Update, but rather with every orientation change, window resize, etc.
– ecv
Feb 21 at 21:50

I think if you decrease the scale size to 1x from above the Game view, it will fit.