threejs 设置背景透明效果

js yekong

Three.js背景完全透明(模型悬浮在网页上)

通过Three.js渲染器WebGLRenderer的alpha属性值设置为true就可以,WebGL渲染器的alpha属性默认值是false。

// 在构造函数参数中设置alpha属性的值
var renderer = new THREE.WebGLRenderer({
  alpha: true
});

注意设置.alpha=true的时候,不要设置.background属性的值,或者通过.setClearColor()方法设置threejs背景颜色。如果通过.setClearColor()方法设置背景颜色,在把该方法的参数2设置为0.0情况下是不影响canvas画布完全透明效果的。

<template>
  <div ref='canvasGLTF' class="canvasGLTF">
  </div>
</template>

<script>
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'

export default {
  name: 'GLTFCanvas',
  data: function () {
    const scene = new THREE.Scene()
    const camera = new THREE.PerspectiveCamera(
        45,
        1900 / 822,
        1,
        1000
    )
    const renderer = new THREE.WebGLRenderer({
      antialias: true,
      alpha: true
    })
    const loader = new GLTFLoader()
    const hemiLight = new THREE.HemisphereLight(0xffffff, 0xffffff, 0.6)
    const controls = new OrbitControls(camera, renderer.domElement)
    return {
      sceneGLTF: scene,
      cameraGLTF: camera,
      rendererGLTF: renderer,
      loader: loader,
      hemiLight: hemiLight,
      controls: controls,
      speed: 0.01
    }
  },
  created: function () {
    //se definen propiedades del render
    this.rendererGLTF.setSize(1900, 822)
    this.rendererGLTF.toneMapping = THREE.ACESFilmicToneMapping
    this.rendererGLTF.toneMappingExposure = 1
    this.rendererGLTF.outputEncoding = THREE.sRGBEncoding
    //posicionando la Camara
    this.cameraGLTF.position.set(5, 3, 8)
    //Definicion de las luces del entorno.
    this.hemiLight.color.setHSL(0.6, 1, 0.6)
    this.hemiLight.groundColor.setHSL(0.095, 1, 0.75)
    this.hemiLight.position.set(0, 0, 0)
    // Agrega propiedades a la escena
    this.sceneGLTF.add(this.hemiLight)
    // this.sceneGLTF.background = new THREE.Color('hsl(0, 100%, 100%)')
    //Carga el asset.
    this.loader.load('assets/立库 测试.gltf', (gltf) => {
      const model = gltf.scene
      model.position.set(0, 0, 0)
      model.rotation.set(0, 0, 0)
      model.scale.set(0.1, 0.1, 0.1)
      this.sceneGLTF.add(model)
    })
    //Definicion de controles:
    this.controls.minDistance = 1
    this.controls.maxDistance = 40
    this.controls.target.set(0, 0, 0)
    this.controls.enableZoom = false
    this.controls.update()
  },
  mounted: function () {
    this.renderGLTF()
    this.$refs.canvasGLTF.appendChild(this.rendererGLTF.domElement)
  },
  methods: {
    renderGLTF: function () {
      requestAnimationFrame(this.renderGLTF.bind(this))
      this.rendererGLTF.render(this.sceneGLTF, this.cameraGLTF)
    }
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.canvasGLTF {
  position: relative;
  width: 100%;
  height: 100%;
}
</style>

参考地址

参考地址

喜欢