GLSL(OpenGL Shading Language)是一种用于编写着色器程序的高级着色语言,主要用于图形渲染。着色器是运行在GPU上的小程序,用于处理图形渲染过程中的各个阶段,如顶点着色器和片段着色器。
Three.js是一个基于WebGL的JavaScript库,用于在浏览器中创建和显示3D图形。它简化了WebGL的复杂性,使得开发者可以更容易地创建复杂的3D场景和动画。
以下是一个简单的示例,展示如何在Three.js中使用GLSL着色器将粒子推离鼠标位置。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Particle Push Away from Mouse</title>
<style>
body { margin: 0; }
canvas { display: block; }
</style>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/three@0.132.2/build/three.min.js"></script>
<script src="app.js"></script>
</body>
</html>
// 创建场景、相机和渲染器
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 particleCount = 1000;
const particles = new THREE.BufferGeometry();
const positions = new Float32Array(particleCount * 3);
for (let i = 0; i < particleCount * 3; i++) {
positions[i] = (Math.random() - 0.5) * 10;
}
particles.setAttribute('position', new THREE.BufferAttribute(positions, 3));
const particleMaterial = new THREE.ShaderMaterial({
uniforms: {
mousePos: { value: new THREE.Vector2(0, 0) }
},
vertexShader: `
uniform vec2 mousePos;
void main() {
vec3 pos = position;
float distance = length(mousePos - (pos.xy * 2.0 - 1.0));
pos.z += distance * 0.1;
gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);
}
`,
fragmentShader: `
void main() {
gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
}
`
});
const particleSystem = new THREE.Points(particles, particleMaterial);
scene.add(particleSystem);
camera.position.z = 5;
// 监听鼠标移动事件
const mouse = new THREE.Vector2();
window.addEventListener('mousemove', (event) => {
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
particleMaterial.uniforms.mousePos.value.copy(mouse);
});
// 渲染循环
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
通过这种方式,你可以实现一个简单的粒子系统,使粒子推离鼠标位置,适用于各种需要动态交互效果的场景。
领取专属 10元无门槛券
手把手带您无忧上云