1,three.js是通过canvas去展示一个三维的立体,而展示需要有以下几个步骤:
1)创建一个scene(场景)
const scene = new THREE.Scene();//这里Scene首字符记得大写
2)创建一个透明摄像头(perspectiveCamera)
const peispectiveCamera = new THREE.PerspectiveCamera(75,window.innerWidth/window.innerHeight,0.1,1000)
这里有4个参数(视野角度,长宽比,近截面,远截面)
3)创建一个渲染器(WebGLRenderer)
const render = new THREE.WebGLRenderer()
4)配置渲染器setSize(长,宽,是否使用现分辨率渲染(true/false))
render.setSize(window.innerWidth,window.innerHight,true)
到这里,就是创建好了场景,接下来在场景里创建物体
5)定义一个正方体(boxGeometry)
const boxGeometry = new THREE.BoxGeometry(1,1,1);//三个参数是长宽高
6)给物体加上材质(meshBasicMetarial)
const meshBasicMetarial = new THREE.MeshBasicMetarial({color:0x00ff00});//这里颜色需要使用十六进制表示
7)创建网格(mesh)
const mesh = new THREE.Mesh(boxGeometry,meshBasicMetarial);//将上面创建的物体和材质放入网格中
8)将我们创建的物体放入场景
scene.add(mesh)
9)选择放置相机的高度
perspectiveCamera.position.z = 5
10)所有的东西创建完毕,渲染
function animate(){
requestAnimationFrame(animate)
mesh.rotation.x +=0.1
mesh.rotation.y +=0.1
WebGLRenderer.render(scene,perspectiveCamera)
}
animate()
这就完成了
完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body{
margin:0
}
</style>
</head>
<body>
<script src="./three.js"></script>
<script>
//创建场景,相机和渲染器
const scene = new THREE.Scene();//创建一个场景
const perspectiveCamera = new THREE.PerspectiveCamera(75,window.innerWidth/window.innerHeight,0.1,1000);//创建一个透视相机
const WebGLRender = new THREE.WebGLRenderer();//创建一个渲染器
WebGLRender.setSize(window.innerWidth,window.innerHeight);
document.body.appendChild(WebGLRender.domElement)
const boxGeometry = new THREE.BoxGeometry(1,1,1);//创建一个立方体
const meshBasicMaterial = new THREE.MeshBasicMaterial({color:0x00ffff});//创建一个基本材质
const mesh = new THREE.Mesh(boxGeometry,meshBasicMaterial);//创建一个网格
scene.add(mesh)
perspectiveCamera.position.z = 5;
function animate(){
requestAnimationFrame(animate);
mesh.rotation.x +=0.01
mesh.rotation.y +=0.01
WebGLRender.render(scene,perspectiveCamera)
}
animate()
</script>
</body>
</html>