Skip to content

Instantly share code, notes, and snippets.

@raphaelameaume
Created May 29, 2020 15:02
Show Gist options
  • Save raphaelameaume/40c945362ab4ec26b25b98558488d367 to your computer and use it in GitHub Desktop.
Save raphaelameaume/40c945362ab4ec26b25b98558488d367 to your computer and use it in GitHub Desktop.
Simulate background-size contain in fragment shader
vec2 uvContain(vec2 baseUv, vec2 size, vec2 resolution) {
float tAspect = size.x / size.y;
float pAspect = resolution.x / resolution.y;
float pWidth = resolution.x;
float pHeight = resolution.y;
float width = 0.;
float height = 0.;
if ( tAspect < pAspect ) {
height = pHeight;
width = height * tAspect;
} else {
width = pWidth;
height = width / tAspect;
}
float x = ( pWidth - width ) / 2.;
float y = ( pHeight - height ) / 2.;
vec2 uv = baseUv;
uv -= vec2(x, y) / resolution;
uv /= vec2(width, height) / resolution;
return uv;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment