2.创建一个three.js场景
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>three.js</title>
</head>
<body>
<script type="text/javascript" src="js/Three/three.js"></script>
<script>
var renderer, scene, camera, light;
function init() {
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setClearColor(0xffffff);
renderer.setSize(window.innerWidth, window.innerHeight);
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.lookAt(new THREE.Vector3(20, 0, 20));
//添加环境光,没有光你就瞎了
light = new THREE.AmbientLight(0xffffff);
scene.add(light);
//使用three.js 生成canvas
document.body.appendChild(renderer.domElement);
creatCube();
render();
}
function creatCube() {
var geometry = new THREE.CubeGeometry(4, 4, 4);
var material = new THREE.MeshBasicMaterial({
color: 0xff0000
});
var mesh = new THREE.Mesh(geometry, material);
mesh.position.set(10, 0, 10);
scene.add(mesh);
}
function render() {
requestAnimationFrame(render);
renderer.render(scene, camera);
}
init();
</script>
</body>
</html>
我们先新建了一个renderer(渲染器),scene(场景),camera(相机),light(灯光)。
2.1
document.body.appendChild(renderer.domElement);
使three.js为我们生成一个canvas 并将canvas和renderer绑定。
当然我们也可以自己写一个canvas。
<canvas id="myCanvas" width="400px" height="300px" ></canvas>并将 renderer定义改为
renderer = new THREE.WebGLRenderer({即可。
canvas: document.getElementById('myCanvas'),
antialias: true
});
2.2
creatCube函数生成了一个cube,放在场景中的(10,0,10)处。
2.3
render函数调用requestAnimationFrame函数让场景持续渲染。
fork me on github blog: https://chenjy1225.github.io/