<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>设置背景透明度</title>
<style>
body {
margin: 0;
overflow: hidden;
}
</style>
</head>
<body>
<div style="position: relative;">
<img src="../assets/img/01.jpg" style="position: absolute;"/>
<div id="container" style="position: absolute;">
<input type="button" id="btn1" style="position: absolute; margin-top: 10px; margin-left: 10px;" value="去除背景"/>
</div>
</div>
<script type="module">
import * as THREE from "../node_modules/three/build/three.module.js";
import { OrbitControls } from '../node_modules/three/examples/jsm/controls/OrbitControls.js';
import { GLTFLoader } from '../node_modules/three/examples/jsm/loaders/GLTFLoader.js';
let camera, orbitControls, scene, renderer;
init();
animate();
document.getElementById("btn1").onclick = () => {
scene.background = null;
};
function init() {
scene = new THREE.Scene();
scene.background = new THREE.Color(0x00ffff);
renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearAlpha(0.3);
document.getElementById("container").appendChild(renderer.domElement);
camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.1, 100000);
camera.position.set( 0, 50, 50 );
orbitControls = new OrbitControls(camera, renderer.domElement);
orbitControls.enableDamping = true;
orbitControls.dampingFactor = 0.05;
orbitControls.screenSpacePanning = false;
orbitControls.maxPolarAngle = Math.PI / 2;
const ambientLight = new THREE.AmbientLight(0xffffff, 0.4);
scene.add(ambientLight);
let directionalLight = new THREE.DirectionalLight("#ffffff");
directionalLight.position.set(0, 30, 0);
scene.add(directionalLight);
const loader = new GLTFLoader();
loader.load("../assets/models/group.glb", gltf => {
const gltfScene = gltf.scene || gltf.scenes[0];
gltfScene.position.set(0, 0, 0);
gltfScene.scale.set(5, 5, 5);
const box = new THREE.Box3().setFromObject(gltfScene);
const center = box.getCenter(new THREE.Vector3());
gltfScene.translateX(-center.x);
gltfScene.translateY(-center.y);
gltfScene.translateZ(-center.z);
scene.add(gltfScene);
});
window.addEventListener('resize', onWindowResize, false);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function animate() {
requestAnimationFrame(animate);
orbitControls.update();
render();
}
function render() {
renderer.render(scene, camera);
}
</script>
</body>
</html>
注:
- 如果设置了场景的背景,包括背景颜色、背景图片以及环境贴图,则背景透明度设置会失效,因此要想设置背景的透明度,需要清除场景的背景设置;
- 在创建WebGLRenderer时,需要把alpha属性设为true,否则背景透明不生效;
- 不要直接设置挂载threejs的canvas的透明度,这样会使场景中所有的模型都具有和canvas相同的透明度;
网友评论