• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Three.js一学就会系列01 第3D网站

武飞扬头像
成茂峰
帮助3


前言

最近开始入坑前端3D建站,跟大家一起慢慢深入three.js做网站3D


一、Three.js是什么?

官网

https://threejs.org/

three.js是JavaScript编写的WebGL第三方库。提供了非常多的3D显示功能。

官网示例效果尝鲜

学新通

二、使用步骤

1.引入three.js库

在线库

<script src="https://threejs.org/build/three.js"></script>

离线可以去官网https://threejs.org/docs/index.html#manual/en/introduction/Creating-a-scene
下载复制到项目所在的目录下
学新通

<script src="./three.js"></script>

2.使用方法

创建一个场景

const scene = new THREE.Scene();

创建一个透视摄像机

const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
camera.position.z = 5;

参数:视野角度(FOV)、长宽比(aspect ratio)、近截面(near)和远截面(far)
camera.position.z:透视摄像机位置

将渲染器添加到页面上

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 );

BoxGeometry:立方体,参数为所有顶点和面
MeshBasicMaterial:材质,将应用到对象上,color设置了对象的颜色
Mesh:网格,几何体和几何体材质,作用
scene.add:添加到场景上

渲染场景

function animate() {
	requestAnimationFrame( animate );
	renderer.render( scene, camera );
}
animate();

requestAnimationFrame有很多的优点。最重要的一点或许就是当用户切换到其它的标签页时,它会暂停,因此不会浪费用户宝贵的处理器资源,也不会损耗电池的使用寿命。

立方体动起来

function animate() {
	requestAnimationFrame( animate );
	// 旋转方向,及大小
	cube.rotation.x  = 0.01;
	cube.rotation.y  = 0.01;

	renderer.render( scene, camera );
};

animate();

完整代码(实例)

<html>
	<head>
		<meta charset="utf-8">
		<title>My first three.js app</title>
		<style>
			body { margin: 0; }
		</style>
	</head>
	<body>
		<script src="./three.js"></script>
		<!-- <script src="https://threejs.org/build/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>
学新通

效果

学新通

总结

如果觉得有用欢迎点赞关注
有问题私信我!!~~

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhfibhbi
系列文章
更多 icon
同类精品
更多 icon
继续加载