(文章来源一个日本鬼子)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Three.js Lesson</title>
<!--引入Three.js-->
<script src="../src/Three.js"></script>
<style type="text/css">
div#canvas3d{
border: none;
cursor: move;
width: 1400px;
height: 600px;
background-color: #EEEEEE;
}
</style>
<script type="text/javascript" defer="defer">
//开启Three.js渲染器
var renderer;
function initThree(){
width = document.getElementById('canvas3d').clientWidth;
height = document.getElementById('canvas3d').clientHeight;
//生成渲染器对象(属性:抗锯齿效果为设置有效)
renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setSize(width, height);
//追加 【canvas】 元素到 【canvas3d】 元素中。
document.getElementById('canvas3d').appendChild(renderer.domElement);
renderer.setClearColorHex(0xFFFFFF, 1.0);
}
//设置相机
var camera;
function initCamera(){
//设置透视投影的相机,默认情况下相机的上方向为Y轴,右方向为X轴,沿着Z轴朝里
camera = new THREE.PerspectiveCamera(45, width/height, 1, 5000);//(视野角:fov 纵横比:aspect 相机离视体积最近的距离:near 相机离视体积最远的距离:far)
//位置坐标
camera.position.x = 0;
camera.position.y = 50;
camera.position.z = 100;
//轴方向
camera.up.x = 0;
camera.up.y = 1;
camera.up.z = 0;
//视野中心坐标
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(200, 200, 200);//设置光源向量
scene.add(light);//追加光源到场景
}
//设置物体
var sphere;
function initObject(){
sphere = new THREE.Mesh(
new THREE.SphereGeometry(20, 20),
new THREE.MeshLambertMaterial({color:0xff0000})//材质设定
);
scene.add(sphere);
sphere.position.set(0,0,0);
}
//执行
function threeStart(){
initThree();
initCamera();
initScene();
initLight();
initObject();
renderer.clear();
renderer.render(scene, camera);
}
</script>
</head>
<body onload='threeStart();'>
<!--盛放canvas的容器-->
<div id="canvas3d"></div>
</body>
</html>
设置相机
var camera = NEW THREE.PerspectiveCamera (fov, Aspect, near, FAR);
设置光源
包括聚光源spot light source和点光源point source,平行光parallel light是点光源的特例,例子里是平行光。
其他光源:
var light = NEW THREE.AmbientLight (hex); //ambient light
var light = NEW THREE.PointLight (hex, Intensity, Distance); // point light source
var light = NEW THREE.SpotLight (hex, Intensity, Distance, CastShadow); // light source Spot Light
设置物体
THREE.CubeGeometry (width, height, depth, segmentsWidth, segmentsHeight, segmentsDepth, materials, sides); //立方体
THREE.CylinderGeometry (radiusTop, radiusBottom, height, segmentsRadius, segmentsHeight, openEnded); //圆锥体
THREE.OctahedronGeometry (radius, detail) //八面体
THREE.PlaneGeometry (width, height, segmentsWidth, segmentsHeight); //平面
THREE.SphereGeometry (radius, segmentsWidth, segmentsHeight, phiStart, phiLength, thetaStart, thetaLength); //球体
THREE.TorusGeometry (radius, tube, segmentsR, segmentsT, arc) type // 圆环