一、效果图:
二、渲染场景和物体的步骤
- 创建场景(Scene):在 three.js 中创建场景通过调用 THREE.Scene() 方法,然后将其赋值给变量。
var scene = new THREE.Scene();
- 创建相机(Camera):在 three.js 中创建相机通过调用 THREE.PerspectiveCamera() 方法,然后将其赋值给变量。需要设定相机的视角、宽高比、近截面和远截面。
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;
- 创建渲染器(Renderer):在 three.js 中创建渲染器通过调用 THREE.WebGLRenderer() 方法,然后将其赋值给变量。
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
- 创建物体(Object):在 three.js 中创建物体可以通过多种方式,比如通过调用 THREE.BoxGeometry()方法创建立方体,调用 THREE.Mesh() 方法将几何体(Geometry)转换为网格(Mesh),并设置不同的材质(Material)。
var geometry = new THREE.BoxGeometry(1, 1, 1);
var material = new THREE.MeshBasicMaterial( {color: 0xff0000} );
var cube = new THREE.Mesh( geometry, material );
scene.add( cube );
- 渲染场景(Render):最后通过调用 THREE.Render() 方法将场景和相机传入进行渲染。
function animate() {
requestAnimationFrame( animate );
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render( scene, camera );
}
animate();
三、完整代码如下
import * as THREE from 'three'
const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
camera.position.set(0, 0, 5)
scene.add(camera)
const geometry = new THREE.BoxGeometry(1, 1, 1)
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 })
const cube = new THREE.Mesh(geometry, material)
scene.add(cube)
const renderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight)
console.log(renderer)
document.body.appendChild(renderer.domElement)
function animate() {
requestAnimationFrame( animate );
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render( scene, camera );
}
animate();