版本:108
非常基礎的代碼,能瞭解ThreeJs各個基礎參數
代碼解釋直接看註釋
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>第一章-畫面</title>
<style>
//以下CSS根據自己的需求來寫
body{
color: #FF8C00;
font-family: monospace;
font-size: 13px;
text-align: center;
padding: 0;
margin: 0;
}
#info{
position: absolute;
top: 0px;
width: 100%;
padding: 5px;
}
#container{
width: 100%;
height: 800px;
}
a{
color: red;
}
</style>
</head>
<body>
//此DIV作爲ThreeJs畫圖的容器
<div id="container"></div>
<div id="info">webgl-threeJs</div>
<script src="../../js/three.js"></script>
<!-- <script src="../../js/WEBGL.js"></script>-->
<script>
//判斷瀏覽器是否支持WEBGL
/*if ( !WEBGL.isWebGLAvailable() ) {
alert("瀏覽器不支持WEBGL!");
}*/
//渲染器、相機、場景、燈光、幾何圖形
var renderer,camera,scene,light;
var cube;
//渲染器函數
function initRenderer() {
//獲取容器的長寬
width = document.getElementById("container").clientWidth;
height = document.getElementById("container").clientHeight;
// alert(width+'--'+height);
//實例化渲染器
renderer = new THREE.WebGLRenderer({
//抗鋸齒(消耗性能,效果好)
antialias:true
});
//設置渲染器大小
renderer.setSize(width,height);
//渲染進容器中
document.getElementById('container').appendChild(renderer.domElement);
//設置顏色及其透明度(0-1之間的浮點數)
renderer.setClearColor('#7fffa7',1.0);
}
//相機
function initCamera() {
//實例化相機(參數:fov(視野角度)、aspect(長/高比例)、near(攝像機視近端面距離)、far:(攝像機視遠端面距離))
camera = new THREE.PerspectiveCamera(45,width / height ,0.1 ,2000);
//設置相機位置
//相機中心位置
camera.position.x = 0;
camera.position.y = 0;
camera.position.z = 50;
//相機快門位置
camera.up.x = 0;
camera.up.y = 1;
camera.up.z = 0;
//相機鏡頭的朝向
camera.lookAt(1,0,0);
}
//場景
function initScene() {
scene = new THREE.Scene();
}
//燈光,這裏使用環境光
function initLight() {
//參數:顏色、強度
light = new THREE.AmbientLight('#446cff',1.0);
//添加到場景中
scene.add(light);
}
function initObject() {
//實例化一個正方式,參數:長、寬
var geometry = new THREE.BoxGeometry(10,10);
//實例化基礎網格材質(這種材質不受光照的影響),參數:顏色
var material = new THREE.MeshBasicMaterial({color:'#FF8C00'});
//實例化mesh構造器,參數:geometry、material
cube = new THREE.Mesh(geometry,material);
//添加到場景中
scene.add(cube);
}
function animation() {
//告訴渲染器清除顏色、深度或模板緩存
renderer.clear();
//像渲染器中添加場景和相機
renderer.render(scene,camera);
}
function start() {
initRenderer();
initCamera();
initScene();
initLight();
initObject();
animation();
}
start();
</script>
</body>
</html>