其中厂房、储物罐、树丛等物体,我们都可以直接加载第三方模型,而不用自己去手画。
模型可以加载本地的,也可以是远程的,不过需要注意跨域问题。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="http://www.yanhuangxueyuan.com/versions/threejsR92/build/three.js"></script>
<script src="http://www.yanhuangxueyuan.com/threejs/examples/js/controls/OrbitControls.js"></script>
<script src="http://www.yanhuangxueyuan.com/threejs/examples/js/loaders/GLTFLoader.js"></script>
<title>Document</title>
</head>
<body>
<div id="webgl"></div>
</body>
</html>
<script>
var scene = new THREE.Scene();
var axes = new THREE.AxesHelper(50);//添加辅助坐标系
scene.add(axes);
//================================地面================================================//
var plane = new THREE.PlaneGeometry(150, 50);
var materialPlane = new THREE.MeshLambertMaterial({
color: 0xcccccc
});
var planeMesh = new THREE.Mesh(plane, materialPlane);
planeMesh.rotation.x = -0.5 * Math.PI; //沿x轴翻转90°,即为展平效果
planeMesh.position.set(0, 0, 0);
scene.add(planeMesh);
//=================================加载模型==================================================//
initModel();
async function initModel() {
let glb = await loadGlb();
glb.position.set(10, 4, 0);
scene.add(glb);
}
function loadGlb() {
return new Promise((resolve, reject) => {
var loader = new THREE.GLTFLoader();
loader.setCrossOrigin('Anonymous');//跨域问题
loader.load('./train.glb', (glb) => {
console.log('glb>>>', glb);
resolve(glb.scene);
}, undefined, (error) => {
console.error(error);
reject(error);
});
});
}
//=======================================光源===================================================//
scene.add(new THREE.AmbientLight(0x444444));//环境光,可以看到所有物体
var pointLight = new THREE.PointLight(0xffffff);//点光源
pointLight.position.set(20, 30, 20);
scene.add(pointLight);
//=============================相机=============================================//
var camera = new THREE.PerspectiveCamera(45, 2, 0.1, 2000);
camera.position.set(50, 20, 0);
camera.lookAt(scene.position);
/**
* 创建渲染器对象
*/
var renderer = new THREE.WebGLRenderer({
antialias: true //消除锯齿
});
renderer.setSize(1000, 500);
renderer.setClearColor(0xb9d3ff, 1);
renderer.render(scene, camera);
var cont = document.getElementById('webgl');
cont.appendChild(renderer.domElement);
//增加鼠标拾取效果
var controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.addEventListener('change', () => {
renderer.render(scene, camera);
});
</script>
注意运行实例时,需要通过起一个静态文件服务器来访问。
然后找模型的话,可以上这个网站:https://www.kenney.nl/