写一个完整的html代码 关于Three.js 中实现点击按钮切换模型的
时间: 2024-02-26 18:53:29 浏览: 176
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Three.js 切换模型</title>
<style>
body {
margin: 0;
}
canvas {
display: block;
}
button {
margin: 10px;
padding: 10px;
font-size: 16px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
</style>
</head>
<body>
<button id="btn1">模型1</button>
<button id="btn2">模型2</button>
<div id="container"></div>
<script src="https://cdn.jsdelivr.net/npm/three@0.132.2/build/three.min.js"></script>
<script>
var renderer, scene, camera, mesh1, mesh2;
init();
animate();
function init() {
// 创建渲染器
renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.getElementById('container').appendChild(renderer.domElement);
// 创建场景
scene = new THREE.Scene();
// 创建相机
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(0, 0, 5);
// 创建模型1
var geometry1 = new THREE.BoxGeometry();
var material1 = new THREE.MeshBasicMaterial({ color: 0xff0000 });
mesh1 = new THREE.Mesh(geometry1, material1);
scene.add(mesh1);
// 创建模型2
var geometry2 = new THREE.SphereGeometry();
var material2 = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
mesh2 = new THREE.Mesh(geometry2, material2);
mesh2.visible = false;
scene.add(mesh2);
// 创建按钮1
var btn1 = document.getElementById('btn1');
btn1.onclick = function() {
mesh1.visible = true;
mesh2.visible = false;
};
// 创建按钮2
var btn2 = document.getElementById('btn2');
btn2.onclick = function() {
mesh1.visible = false;
mesh2.visible = true;
};
}
function animate() {
requestAnimationFrame(animate);
mesh1.rotation.x += 0.01;
mesh1.rotation.y += 0.02;
mesh2.rotation.x += 0.02;
mesh2.rotation.y += 0.01;
renderer.render(scene, camera);
}
</script>
</body>
</html>
阅读全文