廢話很少說直接貼代碼不懂私信:canvas
function addLabel(obj,[x,y,z],textContent){ var earthDiv = document.createElement( 'div' ); earthDiv.textContent = textContent; // earthDiv.style.marginTop = '-3em'; earthDiv.style.color = 'red'; // earthDiv.style.marginLeft = '-3em'; var earthLabel = new CSS2DObject( earthDiv ); earthLabel.position.set( x, y, z ); obj.add(earthLabel) render() } function screenToWorld(wrap,x,y){ let left = wrap.getBoundingClientRect().left; let top = wrap.getBoundingClientRect().top; let clientX = x - left; let clientY = y - top; var mv = new THREE.Vector3( (clientX / wrap.offsetWidth) * 2 - 1, -(clientY / wrap.offsetHeight) * 2 + 1, 0.5 ); mv.unproject(camera); return mv } function addAxis(){ let p1 = screenToWorld(document.querySelector("#canvas"),window.innerWidth-200,window.innerHeight - 100) let p2 = screenToWorld(document.querySelector("#canvas"),window.innerWidth-120,window.innerHeight - 100) var arrowLen = Number((p2.x - p1.x).toFixed(5)) arrowLen = arrowLen <= 0.0001 ? 0.0001 : arrowLen let pp1= p1.clone().project(camera) var toX = new THREE.Vector3( arrowLen, 0, 0 ); var fromX = new THREE.Vector3( 0, 0, 0 ); var directionX = toX.clone().sub(fromX); var lengthX = directionX.length(); var headLengthX = 0.1 * lengthX var headWidthX = 0.8 * headLengthX var arrowX = new THREE.ArrowHelper(directionX.normalize(), fromX, lengthX, 0xff0000, headLengthX, headWidthX); addLabel(arrowX.children[1],[0, 1,0],'X') var toY = new THREE.Vector3( 0, arrowLen, 0 ); var fromY = new THREE.Vector3( 0, 0, 0 ); var directionY = toY.clone().sub(fromY); var lengthY = directionY.length(); var headLengthY = 0.1 * lengthY var headWidthY = 0.8 * headLengthY var arrowY = new THREE.ArrowHelper(directionY.normalize(), fromY, lengthY, 0x00ff00,headLengthY, headWidthY ); addLabel(arrowY.children[1],[0, 1,0],'Y') var toZ = new THREE.Vector3( 0, 0, arrowLen ); var fromZ = new THREE.Vector3( 0, 0, 0 ); var directionZ = toZ.clone().sub(fromZ); var lengthZ = directionZ.length(); var headLengthZ = 0.1 * lengthZ var headWidthZ = 0.8 * headLengthZ var arrowZ= new THREE.ArrowHelper(directionZ.normalize(), fromZ, lengthZ, 0x0000ff, headLengthZ, headWidthZ ); addLabel(arrowZ.children[1],[0, 1,0],'Z') let axes = new THREE.Group(); axes.add(arrowX) axes.add(arrowY) axes.add(arrowZ) axes.position.set(p1.x,p1.y,p1.z) let proxy = new Proxy(axes,{ get:(target,name,property)=>{ let q1 = pp1.clone().unproject(camera); target.position.set(q1.x,q1.y,q1.z) return Reflect.get(target,name,property); } }); scene.add(proxy) }