效果:
中文网three.js docs
1.搭建环境 安装three
首先我们需要新建一个项目 vue/react都可 这里以vue为演示
npm i three
找到一个新的页面 在页面script的地方导入three
import * as THREE from "three"
或者自己逐个导入
import {PerspectiveCamera,Scene,WebGLRenderer,
} from "three";
import * as THREE from "three"
2.搭建场景
<script>
import {PerspectiveCamera,Scene,WebGLRenderer,
} from "three";
import * as THREE from "three"
export default {mounted() {const scene = new Scene()const camera = new PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );const renderer = new WebGLRenderer();renderer.setSize( window.innerWidth, window.innerHeight );document.body.appendChild( renderer.domElement );}
</script>
简单介绍:
scence:场景-画布
camera:相机-PerspectiveCamera(投影摄像机:模拟人眼)-类似于模拟人的眼睛
render:渲染器-(画布+人=画) 这里就是一整幅画
将这一整幅画插入到body中
3.新建一个立方体
import {PerspectiveCamera,Scene,WebGLRenderer,
} from "three";
import * as THREE from "three"
export default {mounted() {const scene = new Scene()const camera = new PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );const renderer = new WebGLRenderer();renderer.setSize( window.innerWidth, window.innerHeight );document.body.appendChild( renderer.domElement );const geometry = new THREE.BoxGeometry( 1, 1,1 );const material = new THREE.MeshBasicMaterial( {wireframe:true,color: 0x42b983} );const cube = new THREE.Mesh( geometry, material );scene.add( cube );camera.position.z = 5;},}
简单介绍:
BoxGeometry:three提供的正方体 xyz
MeshBasicMaterial:基础材料 wireframe:true:将材料以线条的方式显示
Mesh:将形状+材料合并
创造一个立方体 设置好材料 形成一个完整的正方体 将这个完整的正方体添加到场景中
并且将相机拿远一点 就是camera.postion.z=5
如果不拿远 我们的视角就在相机内部 如下图
4.将正方体运动起来
function animate() {requestAnimationFrame( animate );cube.rotation.x += 0.01;cube.rotation.y += 0.01;renderer.render( scene, camera );}animate();
requestAinmationFrame:动画针 重复调用animate函数
cube.rotation.y += 0.01:将正方体沿着x轴y轴旋转0.1
renderer.render( scene, camera ):重新渲染
按照浏览器的刷新频率去让正方体沿xy旋转 并且重新渲染
这样肉眼看起来就像立方体动了起来
5.完整代码
import {PerspectiveCamera,Scene,WebGLRenderer,
} from "three";
import * as THREE from "three"
export default {mounted() {const scene = new Scene()const camera = new PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );const renderer = new WebGLRenderer();renderer.setSize( window.innerWidth, window.innerHeight );document.body.appendChild( renderer.domElement );const geometry = new THREE.BoxGeometry( 1, 1,1 );const material = new THREE.MeshBasicMaterial( {wireframe:true,color: 0x42b983,} );const cube = new THREE.Mesh( geometry, material );scene.add( cube );camera.position.z = 5;function animate() {requestAnimationFrame( animate );cube.rotation.x += 1;cube.rotation.y += 0.01;renderer.render( scene, camera );}animate();},}