一般场景的物体都是用WebGLRenderer来渲染,而标签文字因为涉及到dom,因此需要使用CSS3DRenderer来单独渲染。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="http://www.yanhuangxueyuan.com/threejs/build/three.min.js"></script>
<script src="http://www.yanhuangxueyuan.com/threejs/examples/js/controls/OrbitControls.js"></script>
<script src="http://www.yanhuangxueyuan.com/threejs/examples/js/renderers/CSS3DRenderer.js"></script>
<style>
.tag {
width: 200px;
padding: 10px;
color: #fff;
background-color: rgb(20, 143, 211, 0.68);
box-shadow: 0 0 12px rgba(0, 128, 255, 0.75);
border: 1px solid rgba(127, 177, 255, 0.75);
}
</style>
</head>
<body>
<div id="webgl"></div>
</body>
</html>
<script>
var scene, camera, renderer,renderer2;
init();
function init() {
//场景
scene = new THREE.Scene();
//相机设置为世界坐标原点
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(0, 0, 100);
scene.add(camera);//添加相机
//添加坐标轴
var axes = new THREE.AxesHelper(500);//500表示xyz轴的长度,红:x,绿:y,蓝:z
scene.add(axes);
//创建物体
createBox(scene);
//添加标签文字
createTag(scene);
render();
animate();
}
function createBox(scene) {
var geometry = new THREE.BoxGeometry(10, 10, 10);//几何体
var material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });//材质
var cube = new THREE.Mesh(geometry, material);//渲染管线
cube.position.set(0, 0, -10);
scene.add(cube);
}
function createTag(scene) {
const element = document.createElement('div');
element.className = 'tag';
element.innerHTML = `<p>名称:一个箱子</p><p>材质:绿色</p>`;
const tag = new THREE.CSS3DObject(element);
//缩放比例
tag.scale.set(0.2, 0.2, 0.2);
//指定摆放位置
tag.position.set(0, 16, -10);
scene.add(tag);//添加到指定的场景里
}
function render() {
renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true
});//画布
renderer.setSize(window.innerWidth, window.innerHeight);//设置渲染区域尺寸
renderer.setClearColor(0xb9d3ff, 1); //设置背景颜色
var cont = document.getElementById('webgl');
cont.appendChild(renderer.domElement);
//设置dom元素的渲染
renderer2 = new THREE.CSS3DRenderer();
renderer2.setSize(window.innerWidth, window.innerHeight);
renderer2.domElement.style.position = 'absolute';
renderer2.domElement.style.top = 0;
cont.appendChild(renderer2.domElement);
var controls = new THREE.OrbitControls(camera, renderer2.domElement);
}
function animate() {
renderer.render(scene, camera);//开始渲染
renderer2.render(scene, camera);
requestAnimationFrame(animate);
}
</script>
网友评论