window.onload = function () {
let scene, camera, renderer, controls;
let rootGroup;
init();
createCableSet();
document.getElementById("updateModel").onclick = createCableSet;
// -----------------------------------------------
// 初始化
// -----------------------------------------------
function init() {
const container = document.getElementById("preview3D");
scene = new THREE.Scene();
// 相机更高一点,避免看不见
camera = new THREE.PerspectiveCamera(
45,
container.clientWidth / container.clientHeight,
0.1,
5000
);
camera.position.set(300, 200, 300);
// renderer 支持透明背景
renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(container.clientWidth, container.clientHeight);
renderer.setClearColor(0x000000, 0); // 完全透明
container.appendChild(renderer.domElement);
// 光源
const ambient = new THREE.AmbientLight(0xffffff, 1);
scene.add(ambient);
const dirLight = new THREE.DirectionalLight(0xffffff, 1);
dirLight.position.set(150, 150, 150);
scene.add(dirLight);
// 控件
controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.maxDistance = 2000;
controls.minDistance = 50;
animate();
}
// -----------------------------------------------
// 创建电缆 + M12
// -----------------------------------------------
function createCableSet() {
// 清除旧模型
if (rootGroup) {
scene.remove(rootGroup);
}
rootGroup = new THREE.Group();
// 用户参数
const len = Number(document.getElementById("cableLength").value) || 1000;
const color = document.getElementById("cableColor").value;
const cores = Number(document.getElementById("coreCount").value);
// 电缆半径
const radius = 4 + cores * 0.6;
// three.js 中缩小 10 倍显示
const dispLen = len / 10;
// 电缆本体
const cableGeom = new THREE.CylinderGeometry(radius, radius, dispLen, 32);
const cableMat = new THREE.MeshStandardMaterial({
color: color,
roughness: 0.4,
metalness: 0.1
});
const cable = new THREE.Mesh(cableGeom, cableMat);
cable.rotation.z = Math.PI / 2;
rootGroup.add(cable);
// M12 连接器简化模型
function createM12() {
const g = new THREE.CylinderGeometry(radius + 3, radius + 3, 18, 32);
const m = new THREE.MeshStandardMaterial({
color: "#bbbbbb",
metalness: 0.7,
roughness: 0.2
});
const mesh = new THREE.Mesh(g, m);
return mesh;
}
const head1 = createM12();
head1.position.x = -dispLen / 2 - 12;
const head2 = createM12();
head2.position.x = dispLen / 2 + 12;
rootGroup.add(head1);
rootGroup.add(head2);
scene.add(rootGroup);
// 居中
rootGroup.position.set(0, 0, 0);
}
// -----------------------------------------------
// 动画循环
// -----------------------------------------------
function animate() {
requestAnimationFrame(animate);
controls.update();
renderer.render(scene, camera);
}
};