ThreeJs 导入外部三维模型,并实现鼠标滚动放大缩小旋转效果

时间:2024-07-01 20:07:32
let i = ;
function init() {
// create a scene, that will hold all our elements such as objects, cameras and lights.
var scene = new THREE.Scene();
// create a camera, which defines where we're looking at.
var camera = new THREE.PerspectiveCamera(, window.innerWidth / window.innerHeight, 0.1, );
var renderer = new THREE.WebGLRenderer();
var axes = new THREE.AxesHelper();
var controls = new THREE.TrackballControls(camera); //创建场景旋转缩放事件 camera.position.set(-, , );
camera.lookAt(scene.position); renderer.setClearColor(new THREE.Color(0xcccccc)); // 设置渲染面板颜色
renderer.setSize(window.innerWidth, window.innerHeight); // 设置渲染面板长宽 // // show axes in the screen
// 显示三维坐标轴
scene.add(axes); controls = new THREE.TrackballControls(camera); //创建场景旋转缩放事件
controls.rotateSpeed = 2.5;
controls.zoomSpeed = 1.2;
controls.panSpeed = 0.8;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = true;
controls.dynamicDampingFactor = 0.3;
// create a render and set the size
// 设置渲染面板属性 // create the ground plane
// var planeGeometry = new THREE.PlaneGeometry(60, 20);
// var planeMaterial = new THREE.MeshBasicMaterial({
// color: 0xAAAAAA
// });
// var plane = new THREE.Mesh(planeGeometry, planeMaterial); // // rotate and position the plane
// plane.rotation.x = -0.5 * Math.PI;
// plane.position.set(15, 0, 0); // // add the plane to the scene
// scene.add(plane); // create a cube // position the cube
// cube.position.set(-4, 3, 0);
// add the cube to the scene // create a sphere
// var sphereGeometry = new THREE.SphereGeometry(4, 20, 20);
// var sphereMaterial = new THREE.MeshBasicMaterial({
// color: 0x7777FF,
// wireframe: true
// });
// var sphere = new THREE.Mesh(sphereGeometry, sphereMaterial); // // position the sphere
// sphere.position.set(20, 4, 2); // // add the sphere to the scene
// scene.add(sphere); // position and point the camera to the center of the scene // add the output of the renderer to the html element // render the scene
let addT = null;
let redt = null;
let timeAdd = null;
let timeDel = null;
let step = ;
let frequ = ;
// 数值增加到制定数字
function add (dis) {
clearInterval(timeDel);
timeAdd = setInterval(() => {
if (i < dis) {
i++;
intCub();
} else {
clearInterval(timeAdd);
// del(0);
}
console.log(i);
}, frequ);
};
// 数值减少到制定数字
function del (dis) {
clearInterval(timeAdd);
timeDel = setInterval(() => {
if (i > dis) {
i--;
intCub();
} else {
val = dis;
clearInterval(timeDel);
add()
}
console.log(i);
}, frequ);
}; function intCub () {
let random = parseInt( + ( - ) * (Math.random())); // 随机数用于正方体的长宽高
let randomC = parseInt( + ( - ) * (Math.random())); // 随机数用于球形的半径
let colorRandomNum = parseInt( + ( - ) * (Math.random())); // 随机数用于赋值后续的物体的材质颜色
let randomColor = [0xF7CE18, 0x2550EC, 0x57E10C, 0xEB6F0A, 0xEB0AE9, 0x820745, 0x8D11D8]; // 配置灯光
let light = new THREE.AmbientLight(0x820745);
light.position.set(, , ); // 生成正方体
var cubeGeometry = new THREE.BoxGeometry(random, random, random); // 长宽高
// 给正方体网格添加材质
var cubeMaterial = new THREE.MeshBasicMaterial({
color: randomColor[colorRandomNum],
wireframe: false // 是否显示网格状态
});
var cube = new THREE.Mesh(cubeGeometry, cubeMaterial); // 将材质贴到模型上 // 生成原型
var sphereGeometry = new THREE.SphereGeometry(randomC, , ); // 半径和网格数,网格数表示球体的粗糙程度
var sphereMaterial = new THREE.MeshBasicMaterial({
color: randomColor[colorRandomNum],
wireframe: false // 是否显示网格状态
});
var sphere = new THREE.Mesh(sphereGeometry, sphereMaterial); // 将材质贴到模型上 // position the sphere
// 设置球体的位置
sphere.position.set(parseInt(- + ( - ) * (Math.random())), parseInt(- + ( - ) * (Math.random())), parseInt(- + ( - ) * (Math.random()))); // 设置正方体的位置
cube.position.set(parseInt(- + ( - ) * (Math.random())), parseInt(- + ( - ) * (Math.random())), parseInt(- + ( - ) * (Math.random())));
// add the sphere to the scene
// 将贴好材质的模型和灯光添加到场景
scene.add(sphere);
scene.add(cube);
scene.add(light);
//声明raycaster和mouse变量
var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
// 绑定点击事件
function onMouseClick( event ) {
//通过鼠标点击的位置计算出raycaster所需要的点的位置,以屏幕中心为原点,值的范围为-1到1.
mouse.x = ( event.clientX / window.innerWidth ) * - ;
mouse.y = - ( event.clientY / window.innerHeight ) * + ; // 通过鼠标点的位置和当前相机的矩阵计算出raycaster
raycaster.setFromCamera( mouse, camera );
// 获取raycaster直线和所有模型相交的数组集合
var intersects = raycaster.intersectObjects(scene.children);
console.log(intersects);
//将所有的相交的模型的颜色设置为红色,如果只需要将第一个触发事件,那就数组的第一个模型改变颜色即可
for ( var i = ; i < intersects.length; i++ ) {
intersects[i].object.material.color.set(0x000000);
let msg = JSON.stringify(intersects[i]);
document.querySelector('.msg .content').innerHTML = msg;
}
// alert('我点击了对象,对象信息已经在控制台打印出来');
renderer.render(scene, camera); // 渲染场景中的模型
}
// // window.removeEventListener('click', onMouseClick);
// document.onmousedown = function(event) {
// document.onmousemove = function () {
// controls.update();
// renderer.render(scene, camera); // 渲染场景中的模型
// }
// }
// document.onmouseup = function(event) {
// document.onmousemove = null
// }
document.getElementById("webgl-output").appendChild(renderer.domElement);
// 定时鼠标点击移动或者滚轮滚动的时候要触发渲染事件,画面是不会跟着放大缩小旋转
setInterval(() => {
controls.update();
renderer.render(scene, camera); // 渲染场景中的模型
}, );
// renderer.render(scene, camera); // 渲染场景中的模型 /**************加载模型************** */
var loader = new THREE.OBJLoader();//在init函数中,创建loader变量,用于导入模型
let i = 0.04;
let step = 0.02;
let v = ;
loader.load(
// 资源链接
'http://10.1.252.90:8080/src/chapter-01/models/man.obj',
// 资源加载完成后的回调函数
function (object) {
console.log(object);
object.position.set(, , );
object.rotation.z = 3.1415927; // 纠正导入
var ms = new THREE.MeshBasicMaterial({
color: 0xcccccc,
wireframe: true // 是否显示网格状态
});
scene.add(object); renderer.render(scene, camera); // 渲染场景中的模型
window.addEventListener('click', onMouseClick, false);
// // var sphere = new THREE.Mesh(object, ms); // 将材质贴到模型上
setInterval(() => {
i += step;
object.rotation.y = i;
scene.add(object);
// renderer.render(scene, camera); // 渲染场景中的模型
}, );
}
);
/**************加载模型************** */
};
// 运行渲染
add ();
intCub(); }
<!DOCTYPE html>

<html>

<head>
<title>Example 01.02 - First Scene</title>
<meta charset="UTF-8" />
<script type="text/javascript" charset="UTF-8" src="../../libs/three/three.js"></script>
<script type="text/javascript" charset="UTF-8" src="../../libs/three/loaders/OBJLoader.js"></script>
<script type="text/javascript" charset="UTF-8" src="../../libs/three/controls/TrackballControls.js"></script>
<script type="text/javascript" charset="UTF-8" src="../../libs/three/controls/DragControls.js"></script> <link rel="stylesheet" href="../../css/default.css">
<style>
#render{
position: fixed;
left: 20px;
top: 30px;
height: 40px;
width: 120px;
}
.msg{
position: absolute;
left: 10px;
top: 10px;
height: 600px;
min-height: 550px;
overflow:scroll;
width: 500px;
background: #fff;
border: 2px solid #eee;
}
h3{
padding: ;
margin: ;
text-align: center;
}
</style>
</head> <body> <!-- Div which will hold the Output -->
<div id="webgl-output"></div>
<div class="msg">
<h3>鼠标点击的对象信息</h3>
<div class="content"></div>
</div>
<script type="text/javascript" src="./js/01-02.js"></script>
<!-- Javascript code that runs our Three.js examples -->
<script type="text/javascript">
(function () {
// your page initialization code here
// the DOM will be available here
init();
})();
</script> </body> </html>