threejs 通过封装WEBGL API 实现了在网页端直接进行三维3d模型渲染。应用场景包括:小游戏,在线展厅,DIY 互动等现代互联网应用,极具发展前景。
three.js就是使用javascript 来写3D程序。
在浏览器端,WebGL 是一个底层的标准,在这些标准被定义之后,Chrome、Firefox之类的浏览器实现了这些标准。然后,就能通过 JavaScript 代码,在网页上实现三维图形的渲染了。ThreeJS则是封装了底层的图形接口,更容易来实现3D程序。
核心
WebGL 的渲染是需要 HTML5 Canvas 元素的,所以需要在 部分中定义Canvas 元素,或者使用 js 生成。
一个典型的 Three.js 程序至少要包括渲染器(Renderer)、场景(Scene)、照相机(Camera),以及你在场景中创建的物体。
渲染器
渲染器将和 Canvas 元素进行绑定,如果在 HTML 中手动定义了Canvas 元素,那么 Renderer 可以这样写:
1、打开 官网 下载Three.js
https://threejs.org
或者使用 Github 下载Three.js
https://github.com/mrdoob/three.js
2、three.js的使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="js/three.js"></script>
<script>
const scene = new THREE.Scene(); //场景
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 ); //摄像机
const renderer = new THREE.WebGLRenderer(); //渲染器
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
const geometry = new THREE.BoxGeometry( 1, 1, 1 );
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
const cube = new THREE.Mesh( geometry, material );
scene.add( cube );
camera.position.z = 5;
function animate() {
requestAnimationFrame( animate );
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render( scene, camera );
};
animate();
</script>
</body>
</html>
3、代码说明
THREE.BoxGeometry 立方体
const geom = new THREE.BoxGeometry(width, height, depth,widthSegments, heightSegments,depthSegments)
通过width属性调整方块的宽度
通过height属性调整方块的高度
通过depth属性调整方块的深度
通过widthSegments属性调整方块在x轴方向上将面分成的段数
通过heightSegments属性调整方块在y轴方向上将面分成的段数
通过depthSegments属性调整方块在z轴方向上将面分成的段数