代码效果
源码
<!DOCTYPE html>
<html>
<head>
<title>Example 01.02 - First Scene</title>
<script type="text/javascript" src="../libs/three.js"></script>
<style>
body {
/* set margin to 0 and overflow to hidden, to go fullscreen */
margin: 0;
overflow: hidden;
}
</style>
</head>
<body>
<div id="Lapbin-output"></div>
<!-- Javascript code that runs our Three.js examples -->
<script type="text/javascript">
// once everything is loaded, we run our Three.js stuff.
function init() {
// 创建一个场景,该场景将包含所有元素,例如对象、摄影机和灯光。
var scene = new THREE.Scene();
// 创建一个摄像头,它定义了我们要看的范围。
var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
// 创建渲染并设置大小
var renderer = new THREE.WebGLRenderer();
renderer.setClearColor(new THREE.Color(0x000000));
renderer.setSize(window.innerWidth, window.innerHeight);
// 在屏幕上显示轴
var axes = new THREE.AxisHelper(20);
scene.add(axes);
// 创建平面
var planeGeometry = new THREE.PlaneGeometry(60, 20);
var planeMaterial = new THREE.MeshBasicMaterial({color: 0xcccccc});
var plane = new THREE.Mesh(planeGeometry, planeMaterial);
// 旋转并定位平面
plane.rotation.x = -0.5 * Math.PI;
plane.position.x = 15;
plane.position.y = 0;
plane.position.z = 0;
// 将平面添加到场景中
scene.add(plane);
// 创建一个立方体
var cubeGeometry = new THREE.BoxGeometry(4, 4, 4);
var cubeMaterial = new THREE.MeshBasicMaterial({color: 0xff0000, wireframe: true});
var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
// 定位立方体
cube.position.x = -4;
cube.position.y = 3;
cube.position.z = 0;
// 将立方体添加到场景中
scene.add(cube);
// 创建一个球体
var sphereGeometry = new THREE.SphereGeometry(4, 20, 20);
var sphereMaterial = new THREE.MeshBasicMaterial({color: 0xdd77ff, wireframe: true});
var sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
// 定位球体
sphere.position.x = 20;
sphere.position.y = 4;
sphere.position.z = 2;
// 将球体添加到场景中
scene.add(sphere);
// 将摄影机定位并指向场景的中心
camera.position.x = -30;
camera.position.y = 40;
camera.position.z = 30;
camera.lookAt(scene.position);
// 将渲染器的输出添加到html元素
document.getElementById("Lapbin-output").appendChild(renderer.domElement);
// 渲染场景
renderer.render(scene, camera);
}
window.onload = init;
</script>
</body>
</html>