在现代互联网时代,Web 技术的快速发展使得 Web 开发领域日新月异。随着互联网内容变得越来越丰富、复杂,用户对于网页和应用程序的交互性和视觉效果提出了更高的要求。在这样的背景下,基于 WebGL 的 3D 图形技术越来越受到关注和重视。 而在众多的 3D 图形库中,Three.js 作为一款优秀的 JavaScript 3D 图形库,受到了广泛的欢迎和应用。无论是创建引人入胜的交互式 3D 场景、还是打造惊艳的虚拟现实体验,Three.js 都展现出了强大的潜力和灵活性。 本系列文章将深入探讨 Three.js,从基础入门到高级应用,带领读者逐步掌握 Three.js 的核心概念和技术要点。我们将从搭建基本的 3D 场景开始,逐步引入光影、材质、纹理、动画等概念,让读者能够系统地掌握 Three.js 的开发技巧和实践经验。 通过本系列文章的学习,读者将能够掌握使用 Three.js 创建精美的 3D 可视化效果,以及实现交互式的虚拟场景的能力。无论是 Web 开发工程师、还是对 3D 图形技术感兴趣的爱好者,都能够从中受益匪浅。 让我们一起踏上 Three.js 的学习之旅,探索无限的创意可能性,开启属于自己的 3D 时代! 欢迎各位小伙伴们多多关注,你的点赞和评论是我写作的动力!
下面我将详细解释 Three.js 的核心概念:
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(windowWidth, windowHeight);// 设置渲染器的大小
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);// 渲染场景
}
window.onload = animate// 页面加载完毕后执行动画函数
<!--
* @Date: 2023-11-11 14:14:21
* @LastEditors: 前端少年汪
* @LastEditTime: 2023-11-11 15:50:17
* @FilePath: /webGIS/1-three.html
* @Description:
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
h1 {
text-align: center;
}
#webgl {
width: 1200px;
height: 700px;
margin: 0 auto;
}
</style>
</head>
<body>
<h1>three.js入门教程</h1>
<div id="webgl"></div>
<script type="module">
// 现在浏览器支持ES6语法,自然包括import方式引入js文件
import * as THREE from './node_modules/three/src/Three.js';
let windowWidth = 1200;// 窗口宽度
let windowHeight = 700;// 窗口高度
const scene = new THREE.Scene();// 场景
const camera = new THREE.PerspectiveCamera(75, windowWidth / windowHeight, 0.1, 1000);// 摄像机
const renderer = new THREE.WebGLRenderer();// 渲染器
renderer.setSize(windowWidth, windowHeight);// 设置渲染器的大小
document.getElementById('webgl').appendChild(renderer.domElement);// 将渲染器添加到页面中
// 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);// 渲染场景
}
window.onload = animate// 页面加载完毕后执行动画函数
</script>
</body>
</html>
以上demo总结来说,使用了 Three.js 库创建了一个简单的绿色立方体模型,并实现了旋转动画效果。 总结一下它的步骤:
通过以上步骤,我们成功创建了一个具有旋转动画效果的绿色立方体模型,并将其显示在网页中。这个简单的示例展示了如何使用 Three.js 创建基本的 3D 模型并实现动画效果。