Skip to content

Instantly share code, notes, and snippets.

@mattdesl
Created April 26, 2017 18:02
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattdesl/6024dfb256406e7d325dd9d4c6e64c13 to your computer and use it in GitHub Desktop.
Save mattdesl/6024dfb256406e7d325dd9d4c6e64c13 to your computer and use it in GitHub Desktop.
Like CSS background-size: contain but in GLSL
vec2 backgroundUV (vec2 uv, vec2 resolution, vec2 texResolution) {
float tAspect = texResolution.x / texResolution.y;
float pAspect = resolution.x / resolution.y;
float pwidth = resolution.x;
float pheight = resolution.y;
float width = 0.0;
float height = 0.0;
if (tAspect > pAspect) {
height = pheight;
width = height * tAspect;
} else {
width = pwidth;
height = width / tAspect;
}
float x = (pwidth - width) / 2.0;
float y = (pheight - height) / 2.0;
vec2 nUv = uv;
nUv -= vec2(x, y) / resolution;
nUv /= vec2(width, height) / resolution;
return nUv;
}
#pragma glslify: export(backgroundUV)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment