Fragment shaders can render out textures using GLSL sampler2D
and texture2D
objects. The first step to get a texture rendered is to pass through your texture as a uniform
from your Three.js code.
A uniform can be thought of as a "prop" from Vue or React, it's simply something that we pass down from a JavaScript file into our vertex or fragment shader. In this case, we're passing down the loaded texture we'd like to reference using Three.js' TextureLoader
object:
new THREE.ShaderMaterial({
new THREE.SphereGeometry(5, 50, 50),
new THREE.ShaderMaterial({
vertexShader,
fragmentShader,
uniforms: {
globeTexture: {
value: new THREE.TextureLoader().load('./img/globe.jpeg')
}
}
})
)
To pass a uniform
through to the shader successfully, you must declare you are receiving a uniform
near the top of your vertex or fragment shader file with:
uniform sampler2D globeTexture;
Note, the name globeTexture
matches the name we gave our uniform
in the Three.js code above. We also must declare its type, sampler2D
prior to its use.
Given that we have a texture uniform
called globeTexture
declared within our Three.js code, import a uniform
sampler2D
below: