Source: "Dark Horse Front-end Web Application 3D Technology, Three.js Realizes 3D Car Showroom_Quickly Master the Basic Concepts of Three.js"
1. Background
- Three.js is an API library based on WebGL, using Three.js in javascript and implement 3D scenes
2. Introduction
- index.html introduces js files
<script src="./three_exercise.js" type="module"></script>
npm install three --s
import * as THREE from "three";
2. Elements
(1) Three basic elements
- Scene, camera, renderer, the combination of the three can render visible content
1、scene
- Scene: 3D content container
import {
Scene } from "three";
let scene;
function initScene(){
scene = new Scene()
}
initScene()
2、camera
- Camera: human eye viewing angle
let camera;
function initCamera(){
camera = new PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000)
camera.position.z = 10
}
3、renderer
let renderer;
function initRenderer(){
renderer = new WebGLRenderer({
antialias: true
})
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)
}
initScene()
auxiliary conditions
import {
AxesHelper } from "three";
function initAxesHelper(){
const axesHelper = new AxesHelper(3)
scene.add(axesHelper)
}
initAxesHelper()
import {
OrbitControls} from 'three/examples/jsm/controls/OrbitControls'
let controls;
function initOrbitControls(){
controls = new OrbitControls(camera, renderer.domElement)
}
initOrbitControls()
import {
GridHelper } from "three";
let grid;
function initGridHelper(){
grid = new GridHelper(20, 40, 'red', '0xffffff')
grid.material.opacity = 0.2
grid.material.transparent = true
scene.add(grid)
}
initGridHelper()
function render(time){
renderer.render(scene, camera)
requestAnimationFrame(render)
TWEEN.update(time)
}
render()
window.addEventListener('resize', function(){
camera.aspect = window.innerWidth / window.innerHeight
camera.updateProjectionMatrix()
renderer.setSize(window.innerWidth, window.innerHeight)
})
(2) mesh
import {
Mesh } from "three";
let mesh;
function initMesh(){
const geometry = new BoxGeometry(1, 1, 1)
const texture = new TextureLoader().load(dream)
const materal = new MeshBasicMaterial({
color: 'white',
map: texture
})
mesh = new Mesh(geometry, materal)
scene.add(mesh)
}
initMesh()
(3) light
- Light source: light effect
let spotLight;
spotLight = new SpotLight( 0xffffff );
spotLight.position.set( -40, 60, -10 );
scene.add( spotLight )