three.js 3D立方體效果程式碼例項

antzone發表於2017-02-20
分享一段程式碼例項,它利用three.js實現了3D立方體效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
#canvas{
  width:1100px;
  height:600px;
  background:palevioletred;
  border:1px solid;
}
</style>
<!--步驟(自認為)
  1.設定three.js渲染器
  2.設定場景scene
  3.設定物體object
  4.設定攝像機camera
  5.設定光源light
-->
<script src="https://threejs.org/build/three.js"></script>
<script>
//渲染器
var renderer;
function init_Three_renderer() {
  width = document.getElementById("canvas").clientWidth;
  height = document.getElementById("canvas").clientHeight;
  renderer = new THREE.WebGLRenderer({ //生成渲染物件
    antialias: true //去鋸齒
  });
  renderer.setSize(width, height); //設定渲染的寬度和高度;
  document.getElementById("canvas").appendChild(renderer.domElement);
  renderer.setClearColor(0xEEEEEE, 1); //設定渲染的顏色;
}
//場景
var scene;
 
function init_Three_scene() {
  scene = new THREE.Scene();
}
//物體
var cube;
 
function init_Three_object() {
  var geometry = new THREE.CubeGeometry(20, 20, 20); //幾何體 (長,寬,高)
  //var texture = THREE.ImageUtils.loadTexture("b.jpg",null,function(t){});//新增紋理
  //var material = new THREE.MeshLambertMaterial({color:0x00ff00,map:texture});
  var material = new THREE.MeshLambertMaterial({
    color: 0x00ff00
  }); //表面有光澤的材質型別
  cube = new THREE.Mesh(geometry, material);
  //cube.position.set(0,0,0);//設定幾何體的位置(x,y,z)
  scene.add(cube);
}
// 相機
var camera;
 
function init_Three_camera() {
  camera = new THREE.PerspectiveCamera(50, width / height, 1, 5000); //透視相機
  camera.position.x = 20
  camera.position.y = 20;
  camera.position.z = 50;
 
  camera.up.x = 0; //設定相機的上為「x」軸方向
  camera.up.y = 1; //設定相機的上為「y」軸方向
  camera.up.z = 0; //設定相機的上為「z」軸方向
  camera.lookAt({
    x: 0,
    y: 0,
    z: 0
  }); //設定視野的中心座標
}
//        光源
var light;
 
function init_Three_light() {
  light = new THREE.DirectionalLight(0xffffff, 1); //設定平行光源 (光顏色,光強度)
  light.position.set(10, 30, 20); //設定光源向量 (x,y,z)
  scene.add(light);
}
 
function ThreeJs_Main() {
  init_Three_renderer(); //渲染
  init_Three_scene(); //場景
  init_Three_object(); //物體
  init_Three_camera(); //相機
  init_Three_light(); //光源
  variation(); //動畫迴圈
}
 
function variation() {
  cube.rotation.x += 0.01;
  cube.rotation.y += 0.01;
  renderer.clear();
  renderer.render(scene, camera);
  requestAnimationFrame(variation);
}
</script>
</head>
<body>
  <div id="canvas"></div>
</body>
</html>

相關文章