簡述:three.js封裝了WebGL的底層細節(jié),是一款運行在瀏覽器中的 3D 引擎,可以用它創(chuàng)建各種三維場景,包括了攝影機、光影、材質(zhì)等各種對象,目前在Git上已經(jīng)擁有90k+的star,今天用three.js來構(gòu)建一個三維模型;
1、首先,在項目中需要下載threejs的相關(guān)依賴;
npm install three
2、在js頁面引入使用;
方式 1: 導(dǎo)入整個 three.js核心庫
import * as THREE from 'three';
使用
const scene = new THREE.Scene();
方式 2: 僅導(dǎo)入你所需要的部分
import { Scene } from 'three';
使用
const scene = new Scene();
3、具體使用詳細;
引入threejs
import * as three from "three";
引入控制器 控制元素
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
創(chuàng)建場景
const scene = new three.Scene();
創(chuàng)建相機
const camera = new three.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
設(shè)置相機位置
camera.position.set(0, 0, 10);
場景綁定相機
scene.add(camera);
創(chuàng)建幾何體和材質(zhì)
const cubeGeometry = new three.BoxGeometry(1, 1, 1);
const subeMaterial = new three.MeshBasicMaterial({ color: 0xffff00 });
根據(jù)幾何體和材質(zhì)創(chuàng)建物體
const cube = new three.Mesh(cubeGeometry, subeMaterial);
把物體添加到場景中
scene.add(cube);
初始化渲染器
const renderer = new three.WebGLRenderer();
設(shè)置渲染器尺寸大小
renderer.setSize(window.innerWidth, window.innerHeight);
將渲染內(nèi)容添加到body
document.body.appendChild(renderer.domElement);
//使用渲染器將相機里的場景渲染出來
//renderer.render(scene,camera);
創(chuàng)建控制器
const controls = new OrbitControls(camera, renderer.domElement);
創(chuàng)建添加坐標軸線體
const axesHelper = new three.AxesHelper(5);
scene.add(axesHelper);
定義函數(shù),實時渲染
function render() {
物體添加動畫
cube.position.x += 0.05;
if (cube.position.x > 5) {
cube.position.x = 0
}
在函數(shù)中調(diào)用渲染器
renderer.render(scene, camera);
實時渲染函數(shù)
requestAnimationFrame(render);
}
render();
4、實現(xiàn)的3d效果;
?文章來源地址http://www.zghlxwxcb.cn/news/detail-817834.html
文章來源:http://www.zghlxwxcb.cn/news/detail-817834.html
到了這里,關(guān)于THREE.JS使用詳細(three.js創(chuàng)建3d物體,three.js的使用方式)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!