<template>
<div ref="threeRef"></div>
</template>
<script setup>
import {onMounted, ref} from "vue";
import Stats from 'three/examples/jsm/libs/stats.module.js'
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
let stats = new Stats()
stats.setMode(0)
document.body.appendChild(stats.domElement)
let threeRef=ref()
const scene=new THREE.Scene()
scene.background=new THREE.Color('#2fa799')
const camera=new THREE.PerspectiveCamera(75,window.innerWidth/window.innerHeight,0.1,1000)
camera.position.y=200
camera.position.x=0
camera.position.z=100
camera.lookAt(scene.position)
const axes=new THREE.AxesHelper(50)
scene.add(axes)
const renderer=new THREE.WebGLRenderer({antialias:true})
renderer.setSize(window.innerWidth,window.innerHeight)
renderer.render( scene, camera );
renderer.outputEncoding=THREE.sRGBEncoding
window.addEventListener('resize',()=>{
camera.aspect=window.innerWidth/window.innerHeight
camera.updateProjectionMatrix()
renderer.setSize(window.innerWidth,window.innerHeight)
},false)
const controls=new OrbitControls(camera,renderer.domElement)
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);
const pointLight = new THREE.PointLight(0xffffff, 0.5);
pointLight.position.set(0, 3, 0);
scene.add(pointLight);
const pieceJ=new THREE.BoxGeometry(80,80,80)
const pieceC=new THREE.MeshBasicMaterial({color:'#808080'})
const pieceW=new THREE.Mesh(pieceJ,pieceC)
pieceW.position.x=50
pieceW.position.y=50
pieceW.position.z=50
scene.add(pieceW)
const highlightMaterial = new THREE.MeshBasicMaterial({
color: '#1ea6b9'
});
let currentIntersected;
let tooltip = document.createElement('div');
tooltip.style.position = 'absolute';
tooltip.style.zIndex = '999';
tooltip.style.background = '#e0e7e8';
tooltip.style.padding = '4px';
tooltip.style.border = '1px solid #ccc';
tooltip.style.visibility = 'hidden';
document.body.appendChild(tooltip);
renderer.domElement.addEventListener('mousemove', function(event) {
let mouse = new THREE.Vector2();
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
let raycaster = new THREE.Raycaster();
raycaster.setFromCamera(mouse, camera);
let intersects = raycaster.intersectObjects(scene.children, true);
if (currentIntersected) {
currentIntersected.material = pieceW;
currentIntersected = null;
}
if (intersects.length > 0) {
tooltip.style.visibility = 'visible';
tooltip.style.left = (event.clientX + 20) + 'px';
tooltip.style.top = (event.clientY - 20) + 'px';
tooltip.innerHTML=`
<h1>哇!!!<h1>
`
currentIntersected = intersects[0].object;
currentIntersected.material = highlightMaterial;
} else {
tooltip.style.visibility = 'hidden';
}
});
const init=()=>{
threeRef.value?.appendChild(renderer.domElement)
stats.update()
controls.update()
requestAnimationFrame(init)
renderer.render( scene, camera );
}
onMounted(()=>{
init()
})
</script>
<style scoped lang="less">
</style>