Skip to content

Instantly share code, notes, and snippets.

@supahfunk
Created June 22, 2021 14:56
Show Gist options
  • Save supahfunk/8784372b59a69a00eaa8554866f2016d to your computer and use it in GitHub Desktop.
Save supahfunk/8784372b59a69a00eaa8554866f2016d to your computer and use it in GitHub Desktop.
GLSL Background size cover - R3F
const Background = () => {
const { viewport } = useThree()
const scale = useMemo(() => ((40 + 15) / viewport.distance), [viewport])
const [bgTexture] = useTexture(['./bg.png'])
const shaderArgs = useMemo(() => ({
uniforms: {
uTexture: { value: bgTexture },
uResolution: { value: { x: viewport.width, y: viewport.height } },
uImageRegsolution: { value: { x: bgTexture.image.width, y: bgTexture.image.height } },
},
vertexShader: /* glsl */`
varying vec2 vUv;
void main() {
vUv = uv;
vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
gl_Position = projectionMatrix * mvPosition;
}
`,
fragmentShader: /* glsl */`
uniform sampler2D uTexture;
uniform vec2 uResolution;
uniform vec2 uImageRegsolution;
varying vec2 vUv;
void main() {
vec2 ratio = vec2(
min((uResolution.x / uResolution.y) / (uImageRegsolution.x / uImageRegsolution.y), 1.0),
min((uResolution.y / uResolution.x) / (uImageRegsolution.y / uImageRegsolution.x), 1.0)
);
vec2 uv = vec2(
vUv.x * ratio.x + (1.0 - ratio.x) * 0.5,
vUv.y * ratio.y + (1.0 - ratio.y) * 0.5
);
vec3 color = texture2D(uTexture, uv).rgb;
gl_FragColor = vec4(color, 1.);
}
`,
}), [viewport, bgTexture])
return (
<>
<mesh position={[0, 0, -40]}>
<planeBufferGeometry attach="geometry" args={[viewport.width * scale, viewport.height * scale, 1, 1]} />
<shaderMaterial args={[shaderArgs]} />
</mesh>
<Particles num={viewport.aspect > 1 ? 30 : 15} viewport={viewport} />
</>
)
}
export default Background
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment