有时我们想给物体添加一个标签效果,我们习惯用html来实现,那如何将html元素添加到场景中呢?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="http://www.yanhuangxueyuan.com/versions/threejsR92/build/three.js"></script>
<script src="http://www.yanhuangxueyuan.com/threejs/examples/js/renderers/CSS2DRenderer.js"></script>
<title>Document</title>
<style>
.title {
display: flex;
align-items: center;
justify-content: center;
padding: 10px;
color: red;
background: #ffff00;
}
</style>
</head>
<body>
<div id="webgl"></div>
</body>
</html>
<script>
var scene = new THREE.Scene();
var axes = new THREE.AxesHelper(50);//添加辅助坐标系
scene.add(axes);
//================================地面================================================//
var plane = new THREE.PlaneGeometry(150, 50);
var materialPlane = new THREE.MeshBasicMaterial({
color: 0xcccccc
});
var planeMesh = new THREE.Mesh(plane, materialPlane);
planeMesh.rotation.x = -0.5 * Math.PI; //沿x轴翻转90°,即为展平效果
planeMesh.position.set(0, 0, 0);
scene.add(planeMesh);
//几何体
var boxGeometry = new THREE.BoxGeometry(20, 20, 20);
var boxMaterial = new THREE.MeshLambertMaterial({ color: 0x7777ff });
var box = new THREE.Mesh(boxGeometry, boxMaterial);
box.position.x = 20;
box.position.y = 4;
box.position.z = 2;
scene.add(box);
//===============================光源================================================//
var light = new THREE.DirectionalLight(0xffffff);
light.position.set(50, 50, 10);
scene.add(light);
//================================html==============================================//
const div = document.createElement('div');
div.className = 'title';
div.textContent = '立方体在转动';
const labelObj = new THREE.CSS2DObject(div);//声明html元素
labelObj.position.set(0, 5, 10);//设定html元素位置
box.add(labelObj);//注意是添加到物体上,而不是场景
//=============================相机=============================================//
var camera = new THREE.PerspectiveCamera(45, 2, 0.1, 2000);
camera.position.set(50, 50, 50);
camera.lookAt(scene.position);
/**
* 创建渲染器对象
*/
var renderer = new THREE.WebGLRenderer({
antialias: true //消除锯齿
});
renderer.setSize(1000, 500);
renderer.setClearColor(0xb9d3ff, 1);
// renderer.render(scene, camera);
var cont = document.getElementById('webgl');
cont.appendChild(renderer.domElement);
labelRenderer = new THREE.CSS2DRenderer();//使用HTML渲染器
labelRenderer.setSize(1000, 500);
labelRenderer.domElement.style.position = 'absolute';
labelRenderer.domElement.style.top = '0px';
cont.appendChild(labelRenderer.domElement);
render();
function render() {
renderer.render(scene, camera);//渲染必须有场景和相机两个对象
box.rotateY(0.01);
labelRenderer.render(scene, camera);
requestAnimationFrame(render);//递归调用
}
</script>