Created
May 29, 2020 15:01
-
-
Save raphaelameaume/d1731132ef01efd948e67c0778770981 to your computer and use it in GitHub Desktop.
Simulate background:size cover in fragment 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
vec2 uvCover (vec2 uv, vec2 size, vec2 resolution) { | |
vec2 coverUv = uv; | |
vec2 s = resolution; // Screen | |
vec2 i = size; // 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; | |
coverUv = coverUv * s / new + offset; | |
return coverUv; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for this function, it helped me a lot in a personal project.
Here it is in WGSL, in case somebody else might find it useful: