编程

three.js — 一款基于 Javascript 的开源 WebGL 3D 库

574 2023-05-26 19:51:00

Three.js 是一款轻量级、易于使用、跨浏览器的通用 3D 库。

使用

这段代码创建一个场景、一个相机和一个几何立方体,并将立方体添加到场景中。然后,它为场景和相机创建一个 WebGL 渲染器,并将该视口添加到 document.body 元素中。最后,它为摄影机设置场景中立方体的动画

import * as THREE from 'three';

// init

const camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 10 );
camera.position.z = 1;

const scene = new THREE.Scene();

const geometry = new THREE.BoxGeometry( 0.2, 0.2, 0.2 );
const material = new THREE.MeshNormalMaterial();

const mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );

const renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setAnimationLoop( animation );
document.body.appendChild( renderer.domElement );

// animation

function animation( time ) {

	mesh.rotation.x = time / 2000;
	mesh.rotation.y = time / 1000;

	renderer.render( scene, camera );

}