注意:145dev版本会导致模型闪烁,目前使用为94版本
<div id="view"></div>
<script src="r94/three.js"></script>
<script src="r94/controls/OrbitControls.js"></script>
<script src="js/GLTFLoader.js"></script>
<!-- <script src="js/dat.gui.min.js"></script> -->
<script>
//json文件地址
var jsonUrl = "json/8haolou.json";
var renderer, camera, scene, ambientLight, directionalLight, control;
function initRender() {
renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setSize(window.innerWidth, window.innerHeight);
//告诉渲染器需要阴影效果
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap; // 默认的是,没有设置的这个清晰 THREE.PCFShadowMap
document.body.appendChild(renderer.domElement);
}
function initScene() {
scene = new THREE.Scene();
scene.background=new THREE.Color( "#666666" );//背景色
}
function initCamera() {
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(0, 100, 200);
camera.lookAt(new THREE.Vector3(0, 0, 0));
}
function initLight() {
ambientLight = new THREE.AmbientLight("#ffffff");
scene.add(ambientLight);
directionalLight = new THREE.DirectionalLight("#ffffff");
directionalLight.position.set(40, 60, 10);
directionalLight.shadow.camera.near = 1; //产生阴影的最近距离
directionalLight.shadow.camera.far = 400; //产生阴影的最远距离
directionalLight.shadow.camera.left = -50; //产生阴影距离位置的最左边位置
directionalLight.shadow.camera.right = 50; //最右边
directionalLight.shadow.camera.top = 50; //最上边
directionalLight.shadow.camera.bottom = -50; //最下面
//这两个值决定生成阴影密度 默认512
directionalLight.shadow.mapSize.height = 1024;
directionalLight.shadow.mapSize.width = 1024;
//告诉平行光需要开启阴影投射
directionalLight.castShadow = true;
scene.add(directionalLight);
}
function initControl() {
control = new THREE.OrbitControls(camera, renderer.domElement);
}
function render() {
control.update();
renderer.render(scene, camera);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function animate() {
//更新控制器
render();
requestAnimationFrame(animate);
}
function initJson() {
var objectLoader = new THREE.ObjectLoader();
objectLoader.load(jsonUrl, function (group) {//8#楼建筑结构模型
scene.add(group);
scene.scale.set(0.002,0.002,0.002);
});
}
function draw() {
initRender();
initScene();
initCamera();
initLight();
initJson();
initControl();
animate();
window.onresize = onWindowResize;
}
draw();
</script>