Created
November 27, 2016 18:14
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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