302chanwoo 블로그

Next.js 15로 만든 마크다운 블로그

3D position (x, y, z)를 2D position (x, y)로 변경

2017년 06월 05일
3D 객체 위에 태그를 따라다니게 하기

3D object 위에 그 object에 대한 설명이 달린 태그를 붙여서 object를 따라다니게 하려고 한다.

div로 만든 태그를 object 위에 붙여서 따라다니게 하려면 object의 position 값을 대입해야 되는데, positionx, y, z 값을 가지고 있고, divx, y 값만 가지고 있기 때문에 3D position(x, y, z)를 x, y로 변경해서 사용해야만 한다.


1. Cube 생성

var geo = new THREE.BoxBufferGeometry(10, 10, 10);
var mat = new THREE.MeshPhongMaterial({ color: 0xff0000 });
var cube = new THREE.Mesh(geo, mat);
cube.position.set(0, 5, 0);
scene.add(cube);

2. div 태그 생성

<div id="tag">TAG</div>
var tag = document.getElementById("tag");

3. Loop 함수에 좌표 변환 코드 추가

var canvasWidth = window.innerWidth; // 3D 캔버스의 넓이
var canvasHeight = window.innerHeight; // 3D 캔버스의 높이
var widthHalf = canvasWidth / 2; // 3D 캔버스의 넓이의 절반 값
var heightHalf = canvasHeight / 2; // 3D 캔버스의 높이의 절반 값

var pos = cube.position.clone(); // 큐브의 위치값 복사
pos.project(camera); // 3D 좌표를 2D 좌표로 변환
pos.x = pos.x * widthHalf + widthHalf;
pos.y = -(pos.y * heightHalf) + heightHalf;

// pos.x와 pos.y를 2D 상의 좌표로 사용
tag.style.top = pos.y + "px";
tag.style.left = pos.x + "px";

위 코드를 실행하면 div 태그가 3D 객체의 위치를 따라다니며 화면에 표시됩니다.

https://302chanwoo.com/lab/three/coordinate_three_to_two.html