Created
February 20, 2019 12:24
-
-
Save polyclick/e952efb09776b049bb46221d44620ac9 to your computer and use it in GitHub Desktop.
map uv coordinates to do a background-position: cover in screen space
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 backgroundCoverUV(vec2 uv, vec2 resolution, vec2 texResolution) { | |
vec2 s = resolution; | |
vec2 i = texResolution; | |
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; | |
return uv * s / new + offset; | |
} | |
// | |
// use like this: | |
// | |
uniform vec2 screenReso; | |
uniform vec2 mapReso; | |
uniform sampler2D map; | |
// map fragment screen coordinate to 0,0 / 1,1 space | |
vec2 st = gl_FragCoord.xy / screenReso.xy; | |
// get uv applying the background-position: cover logic | |
vec2 uv = backgroundCoverUV(st, screenReso, mapReso); | |
// get texture color | |
gl_FragColor = texture2D(map, uv); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment