16. Three.js如何设置后期处理,而不影响scene.background背景图显示?

235 阅读1分钟

9.jpg

1. 介绍

  1. 在开始进行后期处理之前,保存当前的场景背景图内容。
let savedBackground = scene.background;
  1. 将场景背景图设置为null,以便在后期处理过程中不显示背景图。
scene.background = null;
  1. 执行后期处理过程,将后期处理效果应用于场景。
composer.render();
  1. 在后期处理完成后,将之前保存的场景背景图内容赋值回给场景背景图。
scene.background = savedBackground;

通过按照以上步骤,你可以在后期处理过程中保留场景背景图的显示。

首先保存当前的场景背景图内容,然后将场景背景图设置为null,执行后期处理过程,最后将之前保存的场景背景图内容赋值回给场景背景图。

这样,后期处理将不会影响背景图的显示。

2. 内容

sceneAnimation() {
    this.renderAnimation = requestAnimationFrame(() => this.sceneAnimation())
    // 将不需要处理辉光的材质进行存储备份
    this.scene.traverse((v) => {
        if (v instanceof THREE.Scene) {
            this.materials.scene = v.background
            v.background = null
        }
        if (!this.glowMaterialList.includes(v.name) && v.isMesh) {
            this.materials[v.uuid] = v.material
            v.material = new THREE.MeshBasicMaterial({ color: 'black' })
        }
    })
    this.glowComposer.render()
    // 在辉光渲染器执行完之后在恢复材质原效果
    this.scene.traverse((v) => {
        if (this.materials[v.uuid]) {
            v.material = this.materials[v.uuid]
            delete this.materials[v.uuid]
        }
        if (v instanceof THREE.Scene) {
            v.background = this.materials.scene
            delete this.materials.scene
        }
    })

    this.effectComposer.render()
}