Three.js程序基本框架结构和API说明
1.基本框架结构代码
一个基本的Three.js程序,基本都需要设置场景、渲染器、相机、灯光等等通用操作,因而我们可以把Three.js基本程序框架进行整理,如下。其中,我们可以用Three.js提供的OrbitControls拓展库对Three.js场景进行鼠标操作。代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Three框架</title>
<script src="../three.js-master/build/three.js"></script>
<script src="../three.js-master/examples/js/controls/OrbitControls.js"></script>
<style type="text/css">
body{
margin: 0;
padding: 0;
overflow-y: hidden;
overflow-x: hidden;
}
div#webgl {
width: 100vw;
height: 100vh;
}
</style>
<script>
var renderer;
function initThree() {
let dom = document.getElementById('webgl');
width = dom.clientWidth;
height = dom.clientHeight;
renderer = new THREE.WebGLRenderer({
antialias : true
});
renderer.setSize(width, height);
dom.appendChild(renderer.domElement);
renderer.setClearColor(0xFFFF00, 1.0);
}
var camera;
function initCamera() {
camera = new THREE.PerspectiveCamera(45, width / height, 1, 10000);
camera.position.x = 0;
camera.position.y = 1000;
camera.position.z = 0;
camera.up.x = 0;
camera.up.y = 0;
camera.up.z = 1;
camera.lookAt({
x : 0,
y : 0,
z : 0
});
}
var scene;
function initScene() {
scene = new THREE.Scene();
}
var light;
function initLight() {
light = new THREE.DirectionalLight(0xFF0000, 1.0, 0);
light.position.set(100, 100, 200);
scene.add(light);
}
var cube;
function initObject() {
var geometry = new THREE.CubeGeometry(100,100,100);
var material = new THREE.MeshBasicMaterial({color: 0x00ff00});
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);
console.log("1111");
}
function threeStart() {
initThree(); //初始化Three.js渲染器等初始操作
initCamera(); //初始化相机
initScene(); //初始化场景
initLight(); //初始化灯光
initControls(); //初始化控制器
initObject(); //初始化渲染物体
render(); //执行渲染
}
function initControls(){
// 设置相机控件轨道控制器OrbitControls
const controls = new THREE.OrbitControls(camera, renderer.domElement);
// 如果OrbitControls改变了相机参数,重新调用渲染器渲染三维场景
controls.addEventListener('change', function () {
renderer.render(scene, camera); //执行渲染操作
});//监听鼠标、键盘事件
}
function render() {
renderer.render(scene, camera);
requestAnimationFrame(render);
}
</script>
</head>
<body onload="threeStart();">
<div id="webgl"></div>
</body>
</html>
视频演示地址:https://www.bilibili.com/video/BV1AXmKYUEFP/?vd_source=0f4eae2845bd3b24b877e4586ffda69a