1 月球绕地球旋转
材质贴图的颜色显示可能和原图看起来不一致,需要设置色彩空间:
- 线性色彩空间(LinearSRGBColorSpace):根据光照强度均匀分布
- sRGB色彩空间(SRGBColorSpace):根据人眼观察调整颜色
// 地球、月球半径
const earth_radius = 1
const moon_radius = 0.27//设置透视相机
const camera = new THREE.PerspectiveCamera(46, window.innerWidth/window.innerHeight, 0.1,200)
camera.position.set(10, 5, 20)const scene = new THREE.Scene()//创建方向光,方向光照射的整个区域接受的光照强度一样 光强为3
const dirLight = new THREE.DirectionalLight(0xffffff, 3 )
dirLight.position.set(0,0,1)
scene.add(dirLight)const earthGeometry = new THREE.SphereGeometry(earth_radius, 16, 16)
//光亮材质
const earthMaterial = new THREE.MeshPhongMaterial({specular: 0x333333, //材质的光亮程度和高光的颜色shininess: 5, //高光部分亮度map: textureLoader.load(), //加载地球贴图
})
// 设置色彩空间
earthMaterial.map.colorSpace = THREE.SRGBColorSpace
const earth = new Mesh(earthGeometry, earthMaterial)
scene.add(earth)//月球同理,不贴代码了//设置文字
const earthDiv = document.createElement('div')
earthDiv.className = 'label'
earthDiv.textContent = 'Earth'
earthDiv.style.backgroundColor = 'transparent'const earthLabel = new CSS2DObject(earthDiv)
earthLabel.position.set(1.5*earth_radius, 0, 0)
earthLabel.center.set(0,1)
earth.add(earthLabel)const render = new THREE.WebGLRenderer()
// 如果canvas画布输出模糊,需要设置像素比
render.setPixelRatio(window.devicePixelRatio)
render.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(render.domElement)// 文字渲染
const labelRender = new THREE.CSS2DRenderer()
labelRender.setSize(window.innerWidth, window.innerHeight)
labelRender.domElement.style.position = 'absolute'
labelRender.domELement.style.top = '0px'
document.body.appendChild(labelRender.domElement)//OrbitControls可以进行缩放、平移、旋转操作,实际上改变的是相机位置
//这里改变为render后无法旋转,不知道什么问题
const controls = new THREE.OrbitControls(camera, labelRender.domElement )window.addEventListener('resize', function() {camera.aspect = window.innerWidth / window.innerHeight camera.updateProjectionMatrix()renderer.setSize( window.innerWidth,window.innerHeight)labelRenderer.setSize( window.innerWidth,window.innerHeight)
})animate()
function animate(){requestAnimationFrame(animate)const elapsed = clock.getElapsedTime()moon.position.set(Math.sin(elapsed)*5,0,Math.cos(elapsed) * 5)\moon.rotation.x += 0.01;moon.rotation.y += 0.01;render.renderer(scene,camera)
}
2 正交相机
- CSS2DRenderer:仅支持平移变换,用于将3d物体和html元素结合
- CSS3DRenderer:通过transform属性将3d变换应用到dom元素上,不能使用材质和几何体
//设置相机前800高的内容
const frustumSize = 800
const aspect = window.innerWidth / window.innerHeight
const camera = new THREE.OrthographicCamera(frustumSize * aspect/-2,frustumSize*aspect/2, frustumSize/2,-frustumSize/2,1,1000)camera.position.set(-200,200,200)const scene = new THREE.Scene();
scene.background = new THREE.Color(0xf0f0f0);const material = new THREE.MeshBasicMaterial()