本节从webgl中文网学习:http://www.hewebgl.com/article/getarticle/59
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Three框架</title>
<script src="js/Three.js"></script>
<!--图形用户界面,提供控件-->
<script src="js/dat.gui.js"></script>
<style type="text/css">
div#canvas-frame {
border: none;
cursor: pointer;
width: 100%;
height: 600px;
background-color: #EEEEEE;
}
</style>
<script>
//渲染器
var renderer;
function initThree() {
width = document.getElementById('canvas-frame').clientWidth;
height = document.getElementById('canvas-frame').clientHeight;
renderer = new THREE.WebGLRenderer({
antialias : true
});
renderer.setSize(width, height);
document.getElementById('canvas-frame').appendChild(renderer.domElement);
renderer.setClearColor(0xFFFFFF, 1.0);
}
//相机
var camera;
function initCamera() {
camera = new THREE.PerspectiveCamera(45, width / height, 1, 10000); //透视投影相机
//camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, 10, 1000 ); //正投影相机
camera.position.x = 0; //相机的位置 x,y,z
camera.position.y = 0;
camera.position.z = 600;
camera.up.x = 0; //相机以y=1轴为相机的上方,如果不设置,默认为y
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.AmbientLight(0xFF0000); //定义环境光,影响整个场景,无特定来源,无阴影,不能作为场景中唯一光源
light.position.set(100, 100, 200);
scene.add(light);
light = new THREE.PointLight(0x00FF00); //定义点光源,向所有方向都发射光线,无阴影
light.position.set(0, 0,300);
scene.add(light);
}
//多维数据集
var cube;
function initObject() {
var geometry = new THREE.CylinderGeometry( 70,100,200); //定义一个圆柱体(顶部面积,底部面积,高)
var material = new THREE.MeshLambertMaterial( { color:0xFFFFFF} ); //定义材质
var mesh = new THREE.Mesh( geometry,material);
mesh.position = new THREE.Vector3(0,0,0);
scene.add(mesh);
}
//启动函数
function threeStart() {
initThree();
initCamera();
initScene();
initLight();
initObject();
createUI();
animation();
}
//创建控件,选择参数
var text;
function createUI()
{
var FizzyText = function() {
this.fov = 45;
};
text = new FizzyText();
var gui = new dat.GUI();
gui.add(text,"fov",0,180).name("视角大小");
}
//渲染循环
function animation()
{
changeFov(); //调用函数,更新相机参数
renderer.render(scene, camera);
requestAnimationFrame(animation); //循环调用
}
//获取参数,更新视图
function setCameraFov(fov)
{
camera.fov = fov; //控件参数,赋予相机
camera.updateProjectionMatrix(); //更新摄像机投影矩阵,相机参数更改后,必须调用
}
//监控控件参数
function changeFov()
{
setCameraFov(text.fov);
}
</script>
</head>
<body οnlοad="threeStart();">
<div id="canvas-frame"></div>
</body>
</html>