使用three.js创建一个最基础的3d场景
·5 字·1 分钟阅读
three.js
效果图

代码
import * as THREE from 'three';
const width = document.documentElement.clientWidth
const height = document.documentElement.clientHeight
// 创建3d场景
const scene = new THREE.Scene()
// 创建相机
const camera = new THREE.PerspectiveCamera()
camera.position.z = 7
camera.position.y = 3
// 创建立方体
const boxGeometry = new THREE.BoxGeometry(0.5,0.5,0.5)
// 基础材质
const material = new THREE.MeshBasicMaterial({ color: "#70a1ff" })
// 网格
const mesh = new THREE.Mesh(boxGeometry,material)
mesh.position.set(0, 3, 0)
scene.add(mesh)
// 创建渲染器
const renderer = new THREE.WebGLRenderer({ antialias: true })
// 调整渲染器大小
renderer.setSize(width, height)
// 添加动画
renderer.setAnimationLoop(animate)
document.body.appendChild(renderer.domElement)
// 添加网格地面
const gridHelper = new THREE.GridHelper(10, 10)
scene.add(gridHelper)
// 动画函数
function animate(time) {
mesh.rotation.x = time / 2000;
mesh.rotation.y = time / 1000;
renderer.render( scene, camera );
}