1.在html声明webgl变量
<script type="x-shader/x-vertex" id="vertexShader">
varying vec3 vWorldPosition;
void main() {
vec4 worldPosition = modelMatrix * vec4( position, 1.0 );
vWorldPosition = worldPosition.xyz;
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}
</script>
<script type="x-shader/x-fragment" id="fragmentShader">
uniform vec3 topColor;
uniform vec3 bottomColor;
uniform float offset;
uniform float exponent;
varying vec3 vWorldPosition;
void main() {
float h = normalize( vWorldPosition + offset ).y;
gl_FragColor = vec4( mix( bottomColor, topColor, max( pow( max( h, 0.0 ), exponent ), 0.0 ) ), 1.0 );
}
</script>
2.初始化3d环境
let camera, scene, renderer;
camera = new THREE.PerspectiveCamera( 40, SCREEN_WIDTH / SCREEN_HEIGHT, 1, 10000 );
camera.position.set( 700, 200, - 500 );
// SCENE
scene = new THREE.Scene();
// LIGHTS
const light = new THREE.DirectionalLight( 0xaabbff, 0.3 );
light.position.x = 300;
light.position.y = 250;
light.position.z = - 500;
scene.add( light );
##3.创建天空
使用一个球体模拟天空
const vertexShader = document.getElementById( 'vertexShader' ).textContent;
const fragmentShader = document.getElementById( 'fragmentShader' ).textContent;
const uniforms = {
topColor: { value: new THREE.Color( 0x0077ff ) },
bottomColor: { value: new THREE.Color( 0xffffff ) },
offset: { value: 400 },
exponent: { value: 0.6 }
};
uniforms.topColor.value.copy( light.color );
const skyGeo = new THREE.SphereGeometry( 4000, 32, 15 );
const skyMat = new THREE.ShaderMaterial( {
uniforms: uniforms,
vertexShader: vertexShader,
fragmentShader: fragmentShader,
side: THREE.BackSide
} );
const sky = new THREE.Mesh( skyGeo, skyMat );
scene.add( sky );
4.渲染
// RENDERER
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT );
container.appendChild( renderer.domElement );
renderer.outputEncoding = THREE.sRGBEncoding;
function animate() {
requestAnimationFrame( animate );
renderer.render( scene, camera );
stats.update();
}
animate()