Skip to content

Instantly share code, notes, and snippets.

@statico
Created November 27, 2016 18:14
Show Gist options
  • Star 23 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save statico/df64c5d167362ecf7b34fca0b1459a44 to your computer and use it in GitHub Desktop.
Save statico/df64c5d167362ecf7b34fca0b1459a44 to your computer and use it in GitHub Desktop.
CSS-style `background-size: cover` for an image texture in a GLSL shader
// An implementation of CSS `background-size: cover`
// using http://stackoverflow.com/a/6565988 and my own crappy math
vec2 s = uScreenSize; // Screen
vec2 i = uBGSize; // Image
float rs = s.x / s.y;
float ri = i.x / i.y;
vec2 new = rs < ri ? vec2(i.x * s.y / i.y, s.y) : vec2(s.x, i.y * s.x / i.x);
vec2 offset = (rs < ri ? vec2((new.x - s.x) / 2.0, 0.0) : vec2(0.0, (new.y - s.y) / 2.0)) / new;
vec2 uv = vTexCoord * s / new + offset;
gl_FragColor = texture2D(uBGTex, uv);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment