THREE.JS辉光设定和解决辉光导致背景变暗的问题
- THREE.JS 辉光设定
- THREE.JS 辉光导致背景变暗的问题
- 1.设定背景图片
- 2.初始化辉光
- 3. animate 一直渲染辉光
THREE.JS 辉光设定
给我的设计好的fbx模型,已经设定好了模型发光材质,所以直接添加辉光效果,就可以自动发光
blender模型生成器里的发光只是生成器里的发光效果,导入到three里并不生效,需要用代码生成辉光效果
1.引入辉光参数
import { EffectComposer } from "three/examples/jsm/postprocessing/EffectComposer.js";
import { RenderPass } from "three/examples/jsm/postprocessing/RenderPass.js";
import { UnrealBloomPass } from "three/examples/jsm/postprocessing/UnrealBloomPass";
2.添加辉光方法
//添加辉光效果
initBollmPass() {let renderScene = new RenderPass(scene, camera);let bloomPass = new UnrealBloomPass(new THREE.Vector2(window.innerWidth, window.innerHeight), 0.3, 0.5, 1); //辉光阀值,辉光半径,辉光强度bloomPass.renderToScene = TreeWalker;bloomPass.samples = 7; //采样次数composer = new EffectComposer(renderer);composer.setSize(window.innerWidth, window.innerHeight);composer.addPass(renderScene);composer.addPass(bloomPass);// 设置场景背景颜色scene.background = new THREE.Color("#182238");
},
3.动画执行
要想辉光一直有效,需要一直执行composer.render()方法:
animate方法中增加 composer.render();
THREE.JS 辉光导致背景变暗的问题
1.设定背景图片
scene.background = new THREE.TextureLoader().load("three/work-shop-bg.png");
2.初始化辉光
//初始化辉光
initEffectComposer() {// 场景渲染器effectComposer = new EffectComposer(renderer);const renderPass = new RenderPass(scene, camera);effectComposer.addPass(renderPass);//创建辉光效果unrealBloomPass = new UnrealBloomPass(new THREE.Vector2(window.innerWidth, window.innerHeight), 0.3, 0.5, 1);unrealBloomPass.renderToScreen = false;// 辉光合成器glowComposer = new EffectComposer(renderer);glowComposer.renderToScreen = false;glowComposer.addPass(new RenderPass(scene, camera));glowComposer.addPass(unrealBloomPass);// 着色器let shaderPass = new ShaderPass(new THREE.ShaderMaterial({uniforms: {baseTexture: { value: null },bloomTexture: { value: glowComposer.renderTarget2.texture },tDiffuse: {value: null,},},vertexShader:"\t\t\tvarying vec2 vUv;\n" +"\n" +"\t\t\tvoid main() {\n" +"\n" +"\t\t\t\tvUv = uv;\n" +"\n" +"\t\t\t\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n" +"\n" +"\t\t\t}",fragmentShader:"\t\t\tuniform sampler2D baseTexture;\n" +"\t\t\tuniform sampler2D bloomTexture;\n" +"\n" +"\t\t\tvarying vec2 vUv;\n" +"\n" +"\t\t\tvoid main() {\n" +"\n" +"\t\t\t\tgl_FragColor = ( texture2D( baseTexture, vUv ) + vec4( 1.0 ) * texture2D( bloomTexture, vUv ) );\n" +"\n" +"\t\t\t}",defines: {},}),"baseTexture");shaderPass.renderToScreen = true;shaderPass.needsSwap = true;effectComposer.addPass(shaderPass);
},
3. animate 一直渲染辉光
执行辉光效果器渲染:glowComposer.render();
执行场景效果器渲染:effectComposer.render();