前言
本文将介绍如何在网页中实现3D效果,包括CSS 3D变换和WebGL基础。
目录
- CSS 3D变换
- WebGL基础
- Three.js入门
1. CSS 3D变换
1.1 基本概念
CSS3提供了多种3D变换属性:
1
| transform: rotateX(45deg) rotateY(45deg) translateZ(100px);
|
1.2 示例代码
1 2 3 4 5 6 7 8
| <div class="cube"> <div class="face front">Front</div> <div class="face back">Back</div> <div class="face right">Right</div> <div class="face left">Left</div> <div class="face top">Top</div> <div class="face bottom">Bottom</div> </div>
|
2. WebGL基础
2.1 初始化WebGL
1 2 3 4 5 6
| const canvas = document.getElementById('canvas'); const gl = canvas.getContext('webgl');
if (!gl) { console.error('WebGL not supported'); }
|
2.2 绘制三角形
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| const vsSource = ` attribute vec4 aVertexPosition; void main() { gl_Position = aVertexPosition; } `;
const fsSource = ` void main() { gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); } `;
|
3. Three.js入门
3.1 基本场景
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| 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(); 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();
|
结语
通过本教程,您已经掌握了基本的3D效果实现方法。更多高级技巧请参考官方文档。