Last active
January 7, 2024 13:16
-
-
Save dghez/1f6b401cf3e2927c20f0b95cff8f55a7 to your computer and use it in GitHub Desktop.
Emulate the cover css property in a shader
This file contains hidden or 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 | |
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); | |
// 07.01.2024 - Naples Jesper | |
vec2 background(vec2 res, vec2 size, vec2 uv) { | |
float resRatio = res.x / res.y; | |
float imageRatio = size.x / size.y; | |
vec2 newSize = resRatio < imageRatio | |
? vec2(size.x * (res.y / size.y), res.y) | |
: vec2(res.x, size.y * (res.x / size.x)); | |
vec2 newOffset = (resRatio < imageRatio | |
? vec2((newSize.x - res.x) / 2.0, 0.0) | |
: vec2(0.0, (newSize.y - res.y) / 2.0)) / newSize; | |
return uv * res / newSize + newOffset; | |
} | |
// WORKING | |
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; | |
} | |
// NOT TESTED | |
vec2(vec2 screenSize, vec2 bgSize, vec2 textCoord) { | |
vec2 s = screenSize; // Screen | |
vec2 i = bgSize; // 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 = textCoord * s / new + offset; | |
return uv; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment