three.js如何使用渐变颜色作为背景

时间:2018-05-08 04:56:38

标签: three.js

我使用three.js在微信上开发3D游戏,但我有一个问题,three.js如何设置渐变的背景颜色。我看到文档上的背景颜色,但没有逐渐变化的背景颜色。请说明我是中国人的英语不好。

3 个答案:

答案 0 :(得分:1)

对于高级效果,请尝试使用https://github.com/mattdesl/three-vignette-background或查看其工作原理。对于简单的事情,制作一个CSS渐变并将其放在画布后面。您可以use CSS to make the gradient然后make the threejs canvas transparent

答案 1 :(得分:0)

使用着色器

执行此操作非常简单
var myGradient = new THREE.Mesh(
  new THREE.PlaneBufferGeometry(2,2,1,1),
  new THREE.ShaderMaterial({
    uniforms: {
      uColorA: { value: new THREE.Color },
      uColorB: { value: new THREE.Color }
    },
    vertexShader: require('./gradient.vert'),
    fragmentShader: require('./gradient.frag')
  })
)

现在我曾经这样渲染过:

myGradient.material.depthWrite = false
myGradient.renderOrder = -99999

这将导致此网格首先渲染,然后是整个渲染。但实际上这可能不是最好的解决方案,最好将其渲染到最后,而不是其他所有东西?

gradient.vert:

varying vec2 vUv;
void main(){
  vUv = uv;
  float depth = -1.; //or maybe 1. you can experiment
  gl_Position = vec4(position.xy, depth, 1.);
}

gradient.frag:

varying vec2 vUv;
uniform vec3 uColorA;
uniform vec3 uColorB;
void main(){
  gl_FragColor = vec4(
    mix( uColorA, uColorB, vec3(vUv.y)),
    1.
  );
}

答案 2 :(得分:0)

这是带有 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