3D手势粒子系统
系统核心特性
✨技术栈
Three.js + MediaPipe
粒子数量
10,000+
实时响应 | 多手势控制 | 零后端依赖
手势粒子文字魔法
新增手势识别
✋
食指单独竖起 → 粒子重组为"HELLO"
✌️
食指+中指竖起 → 粒子重组为"我是QJT"
多手势识别扩展
基于MediaPipe Hands的21个关键点,扩展以下手势控制:
手势动作 粒子效果 实现方式
单手指张合 整体缩放 食指-拇指距离
五指张开 爆炸扩散 手掌面积计算
握拳 重置位置 关键点距离阈值
手掌旋转 3D空间旋转 手掌朝向变化
性能优化策略
为确保60fps流畅运行,实施以下优化措施:
渲染优化 :使用 requestAnimationFrame 替代 setInterval ,实现高效的动画循环。
内存管理 :实现粒子对象池,避免频繁创建/销毁导致的内存抖动。
错误处理 :增强摄像头权限请求的容错机制,优雅处理用户拒绝场景。
完整代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>增强版 3D 手势粒子文字交互</title>
<style>
body { margin: 0; overflow: hidden; background: #000; font-family: sans-serif; }
#status {
position: absolute; top: 20px; left: 50%;
transform: translateX(-50%); color: white;
background: rgba(0,0,0,0.7); padding: 10px 20px;
border-radius: 20px; z-index: 100;
}
#input_video { display: none; }
</style>
</head>
<body>
<div id="status">正在初始化摄像头与模型...</div>
<video id="input_video"></video>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@mediapipe/camera_utils/camera_utils.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@mediapipe/control_utils/control_utils.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@mediapipe/drawing_utils/drawing_utils.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@mediapipe/hands/hands.js"></script>
<script>
const videoElement = document.getElementById('input_video');
const statusElement = document.getElementById('status');
// 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({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// 粒子系统
const PARTICLE_COUNT = 3000;
const geometry = new THREE.BufferGeometry();
const positions = new Float32Array(PARTICLE_COUNT * 3);
const colors = new Float32Array(PARTICLE_COUNT * 3);
const basePositions = new Float32Array(PARTICLE_COUNT * 3);
// 文字轮廓位置
let helloPositions = [];
let qjtPositions = [];
let currentTextMode = 'none'; // 'none', 'hello', 'qjt'
// 初始化粒子
for (let i = 0; i < PARTICLE_COUNT; i++) {
const i3 = i * 3;
positions[i3] = (Math.random() - 0.5) * 10;
positions[i3+1] = (Math.random() - 0.5) * 10;
positions[i3+2] = (Math.random() - 0.5) * 10;
basePositions[i3] = positions[i3];
basePositions[i3+1] = positions[i3+1];
basePositions[i3+2] = positions[i3+2];
colors[i3] = 0.5 + Math.random() * 0.5;
colors[i3+1] = 0.5 + Math.random() * 0.5;
colors[i3+2] = 0.8 + Math.random() * 0.2;
}
geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));
const material = new THREE.PointsMaterial({
size: 0.08,
vertexColors: true,
blending: THREE.AdditiveBlending,
transparent: true,
opacity: 0.9
});
const particles = new THREE.Points(geometry, material);
scene.add(particles);
camera.position.z = 15;
// 创建文字轮廓
function createTextOutline(text, positionsArray) {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = 512;
canvas.height = 256;
ctx.fillStyle = 'white';
ctx.font = '80px Arial';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(text, 256, 128);
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const data = imageData.data;
positionsArray.length = 0;
for (let i = 0; i < PARTICLE_COUNT; i++) {
let x, y;
let attempts = 0;
do {
x = Math.floor(Math.random() * canvas.width);
y = Math.floor(Math.random() * canvas.height);
const index = (y * canvas.width + x) * 4;
attempts++;
} while (data[(y * canvas.width + x) * 3] < 128 && attempts < 100);
positionsArray.push(
(x / canvas.width - 0.5) * 12,
(0.5 - y / canvas.height) * 6,
(Math.random() - 0.5) * 2
);
}
}
// 初始化文字轮廓
createTextOutline("HELLO", helloPositions);
createTextOutline("我是QJT", qjtPositions);
// 手势状态
let handScale = 1.0;
let handRotation = { x: 0, y: 0 };
let handDrift = { x: 0, y: 0 };
let isExploding = false;
// MediaPipe Hands
const hands = new Hands({
locateFile: (file) => `https://cdn.jsdelivr.net/npm/@mediapipe/hands/${file}`
});
hands.setOptions({
maxNumHands: 1,
modelComplexity: 1,
minDetectionConfidence: 0.7,
minTrackingConfidence: 0.5
});
hands.onResults((results) => {
statusElement.textContent = '手势识别已就绪';
if (results.multiHandLandmarks && results.multiHandLandmarks.length > 0) {
const landmarks = results.multiHandLandmarks[0];
// 计算手指状态
const isFingerOpen = (fingerId) => {
const tip = landmarks[fingerId];
const pip = landmarks[fingerId - 2];
return tip.y < pip.y;
};
const thumbOpen = isFingerOpen(4);
const indexOpen = isFingerOpen(8);
const middleOpen = isFingerOpen(12);
const ringOpen = isFingerOpen(16);
const pinkyOpen = isFingerOpen(20);
// 新手势识别
if (indexOpen && !thumbOpen && !middleOpen && !ringOpen && !pinkyOpen) {
currentTextMode = 'hello';
} else if (indexOpen && middleOpen && !thumbOpen && !ringOpen && !pinkyOpen) {
currentTextMode = 'qjt';
} else if (thumbOpen && indexOpen && middleOpen && ringOpen && pinkyOpen) {
currentTextMode = 'none';
}
// 原有手势计算
const palmSize = Math.hypot(
landmarks[5].x - landmarks[0].x,
landmarks[5].y - landmarks[0].y
);
const pinchDistance = Math.hypot(
landmarks[4].x - landmarks[8].x,
landmarks[4].y - landmarks[8].y
);
handScale = 0.3 + (pinchDistance / palmSize) * 2.5;
handScale = Math.max(0.3, Math.min(2.5, handScale));
handRotation.x = (landmarks[8].y - landmarks[0].y) * 3;
handRotation.y = (landmarks[8].x - landmarks[0].x) * 3;
handDrift.x = (landmarks[9].x - 0.5) * 10;
handDrift.y = -(landmarks[9].y - 0.5) * 10;
const fingerTips = [4, 8, 12, 16, 20];
const openFingers = fingerTips.filter(id => {
const dist = Math.hypot(
landmarks[id].x - landmarks[0].x,
landmarks[id].y - landmarks[0].y
);
return dist / palmSize > 0.6;
});
isExploding = openFingers.length >= 4;
} else {
handScale = 1.0;
handRotation = { x: 0, y: 0 };
handDrift = { x: 0, y: 0 };
isExploding = false;
currentTextMode = 'none';
}
});
const cameraUtils = new Camera(videoElement, {
onFrame: async () => {
await hands.send({ image: videoElement });
},
width: 640,
height: 480
});
cameraUtils.start().catch((error) => {
statusElement.textContent = '摄像头启动失败: ' + error.message;
});
// 动画循环
function animate() {
requestAnimationFrame(animate);
const positions = geometry.attributes.position.array;
let targetPositions = basePositions;
if (currentTextMode === 'hello') {
targetPositions = helloPositions;
} else if (currentTextMode === 'qjt') {
targetPositions = qjtPositions;
}
for (let i = 0; i < PARTICLE_COUNT; i++) {
const i3 = i * 3;
let targetX, targetY, targetZ;
if (currentTextMode === 'none') {
targetX = basePositions[i3] * handScale + handDrift.x;
targetY = basePositions[i3+1] * handScale + handDrift.y;
targetZ = basePositions[i3+2] * handScale + (isExploding ? Math.random() * 5 : 0);
} else {
targetX = targetPositions[i3] * handScale + handDrift.x;
targetY = targetPositions[i3+1] * handScale + handDrift.y;
targetZ = targetPositions[i3+2] * handScale;
}
positions[i3] += (targetX - positions[i3]) * 0.1;
positions[i3+1] += (targetY - positions[i3+1]) * 0.1;
positions[i3+2] += (targetZ - positions[i3+2]) * 0.1;
}
particles.rotation.x += (handRotation.x * 0.01 - particles.rotation.x) * 0.05;
particles.rotation.y += (handRotation.y * 0.01 - particles.rotation.y) * 0.05;
geometry.attributes.position.needsUpdate = true;
renderer.render(scene, camera);
}
animate();
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
</script>
</body>
</html>
暂无评论
还没有评论,来说两句吧。