I am using three.js to develop 3D games on the WeChat, but I have a problem, how three.js set the background color of the gradient. I see the background color on the document, but there is no background color of the gradual change. Please make clear that I am Chinese bad English.
For advanced effects, try using https://github.com/mattdesl/three-vignette-background or see how it works. For something simple, make a CSS gradient and put it behind the canvas. You can use CSS to make the gradient and then make the threejs canvas transparent.
Here is reusable function with ESM
import {
Mesh,
BackSide,
SphereGeometry,
ShaderMaterial,
Color
} from 'three'
const SKY_COLOR = 0x999999
const GROUND_COLOR = 0x242424
const SKY_SIZE = 1000000
function addSkyGradient(scene) {
const vertexShader = `
varying vec3 vWorldPosition;
void main() {
vec4 worldPosition = modelMatrix * vec4( position, 1.0 );
vWorldPosition = worldPosition.xyz;
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`
const fragmentShader = `
uniform vec3 topColor;
uniform vec3 bottomColor;
varying vec3 vWorldPosition;
void main() {
float h = normalize( vWorldPosition).z;
gl_FragColor = vec4( mix( bottomColor, topColor, max( h, 0.0 ) ), 1.0 );
}`
const uniforms = {
topColor: { value: new Color(SKY_COLOR) },
bottomColor: { value: new Color(GROUND_COLOR) }
}
const skyGeo = new SphereGeometry(SKY_SIZE, 32, 15)
const skyMat = new ShaderMaterial({
uniforms,
vertexShader,
fragmentShader,
side: BackSide
})
const sky = new Mesh(skyGeo, skyMat)
scene.add(sky)
}
My Document
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With