/**
arr1 = [
1,1,2, //x,y,z 点1
3,4,5, //x,y,z 点2
3,2,3] //x,y,z 点3
colors=[
1,0,0, //点1的颜色
0,1,0, //点2的颜色
0,0,1 //点3的颜色
]
*/
function setDotCloud(arr1,colors) {
// 获取画布容器并创建渲染器
const container = document.getElementById('box4');
const renderer = new THREE.WebGLRenderer({ antialias: true });
// 设置渲染器参数
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.sortObjects = false;
renderer.setClearColor(0x000000);
// 将渲染结果添加到画布容器中
container.appendChild( renderer.domElement );
// 创建场景和相机
const scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
camera.position.z = 100;
// 创建点云集合
const pointCloud = new THREE.Group();
// 创建点云材质
const pointMaterial = new THREE.PointsMaterial({
// color: "#ff6666",
vertexColors: true,
transparent: true, // 开启透明度
size: 0.001
});
// 创建点云几何体并添加到点云集合中
const pointGeometry = new THREE.BufferGeometry();
const positions = [];
pointGeometry.setAttribute( 'position', new THREE.Float32BufferAttribute( arr1, 3 ) );
pointGeometry.setAttribute( 'color', new THREE.Float32BufferAttribute( colors, 3 ) );
const points = new THREE.Points( pointGeometry, pointMaterial );
pointCloud.add( points );
// 将点云集合添加到场景中
scene.add( pointCloud );
const controls = new OrbitControls(camera, renderer.domElement);
camera.position.set( 0, 0, -150 );
// controls.reset()
controls.update();
// 创建动画循环
const animate = function () {
requestAnimationFrame( animate );
// pointCloud.rotation.x += 0.001;
// pointCloud.rotation.y += 0.002;
controls.update();
renderer.render( scene, camera );
};
Start the animation loop
animate();
}
下图是我项目数据渲染出来的图
image.png
点击创建的点的事件,获取x,y,z轴的数据(写在setDotCloud函数中,因为有需要的变量)
window.addEventListener('click', onMouseClick, false);
// 创建射线投射器
var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
function onMouseClick(event) {
// 将鼠标点击位置归一化到-1到1的范围
var width = document.getElementById("box4").clientWidth;
var height = document.getElementById("box4").clientHeight;
// 将鼠标点击位置归一化到-1到1的范围
mouse.x = (event.clientX / width) * 2 - 1;
mouse.y = -(event.clientY / height) * 2 + 1;
// 通过射线投射器从相机发射射线
raycaster.setFromCamera(mouse, camera);
// 计算射线与点云的交互
var intersections = raycaster.intersectObject(pointCloud);
if (intersections.length > 0) {
// 获取点击的点的索引
var index = intersections[0].index;
// 获取原始的 XYZ 坐标数据
var positions = pointGeometry.getAttribute('position').array;
var x = positions[index * 3];
var y = positions[index * 3 + 1];
var z = positions[index * 3 + 2];
console.log("点击的位置:",x,y,z)
}
}