简书链接:threejs简单demo测试a放到b的中间
文章字数:436,阅读全文大约需要1分钟
image.png
经过测试 进行缩放并不会影响中心点的定位,但是实际项目无法居中,搞不懂

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105

<html>

<head>
<script type="importmap">
{
"imports": {
"three": "https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js",
"three/addons/": "https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/"
}
}



</script>
<!-- {
"imports": {
"three": "../build/three.module.js",
"three/addons/": "./jsm/"
}
} -->



<script type="module">
import * as THREE from "three";
// 导入轨道控制器

// import { OrbitControls } from 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/controls/OrbitControls.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
// console.log(THREE);

// 目标:使用控制器查看3d物体

// 1、创建场景
const scene = new THREE.Scene();

// 2、创建相机
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);

// 设置相机位置
camera.position.set(0, 0, 10);
scene.add(camera);


// 创建物体 A
const geometryA = new THREE.BoxGeometry(10, 1, 1); // 举例:使用盒子几何体
const materialA = new THREE.MeshBasicMaterial({ color: 0xff0000 });
const objectA = new THREE.Mesh(geometryA, materialA);
scene.add(objectA); // 将物体 A 添加到场景
objectA.position.set(-2,0,0)//故意把A不妨到世界原点
// 创建物体 B
const geometryB = new THREE.BoxGeometry(1, 1, 10); // 举例:使用盒子几何体
const materialB = new THREE.MeshBasicMaterial({ color: 0x00FF00 }); // 设置颜色为红色
const objectB = new THREE.Mesh(geometryB, materialB);

// 计算物体 B 相对于物体 A 的位置,使其居中
const relativePositionB = new THREE.Vector3(0, 0, 0); // 通过调整这些值来设置 B 相对于 A 的位置
objectB.position.set(5,0,0)//故意把设置到其他为止
objectB.scale.set(0.01,1,1)
// 设置物体 B 的位置中间
objectB.position.copy(relativePositionB);

// 将物体 B 添加为物体 A 的子物体
objectA.add(objectB);

// 初始化渲染器
const renderer = new THREE.WebGLRenderer();
// 设置渲染的尺寸大小
renderer.setSize(window.innerWidth, window.innerHeight);
// console.log(renderer);
// 将webgl渲染的canvas内容添加到body
document.body.appendChild(renderer.domElement);

// // 使用渲染器,通过相机将场景渲染进来
// renderer.render(scene, camera);

// 创建轨道控制器
const controls = new OrbitControls(camera, renderer.domElement);

// 添加坐标轴辅助器
const axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);

function render() {
renderer.render(scene, camera);
// 渲染下一帧的时候就会调用render函数
requestAnimationFrame(render);
}

render();
</script>
</head>

<body>

</body>

</html>