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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
| let videoElement; let videoCanvas; let videoCtx; let particleCanvas; let handStatus; let particleStatus;
let scene, camera, renderer, particles; let particleGeometry, particleMaterial; let particleCount = 12000; let basePositions = [];
let hands; let handResults = null; let lastHandPosition = null; let lastGestureTime = 0; let isCameraActive = false;
let scale = 1.0; let rotationX = 0; let rotationY = 0; let agitation = 0;
let colorIntensity = 2.5; let saturationBoost = 1.8; let contrastBoost = 1.8;
let time = 0; let animationFrameId = null;
function init() { console.log("开始初始化手势控制3D星云系统..."); videoElement = document.getElementById('video'); videoCanvas = document.getElementById('video-canvas'); particleCanvas = document.getElementById('particle-canvas'); if (!videoElement || !videoCanvas || !particleCanvas) { console.error("无法找到必要的HTML元素"); return; } videoCtx = videoCanvas.getContext('2d'); handStatus = document.getElementById('hand-status'); particleStatus = document.getElementById('particle-status'); console.log("DOM元素获取成功"); initThreeJSScene(); initMediaPipeHands(); setupEventListeners(); animate(); console.log("系统初始化完成"); }
function initThreeJSScene() { try { console.log("初始化Three.js场景..."); scene = new THREE.Scene(); const aspect = particleCanvas.clientWidth / particleCanvas.clientHeight; camera = new THREE.PerspectiveCamera(70, aspect, 0.1, 3000); camera.position.z = 50; renderer = new THREE.WebGLRenderer({ canvas: particleCanvas, antialias: true, alpha: true, powerPreference: 'high-performance' }); renderer.setSize(particleCanvas.clientWidth, particleCanvas.clientHeight); renderer.setClearColor(0x000000, 1); renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); createVibrantParticleSystem(); console.log("Three.js场景初始化成功"); particleStatus.textContent = '鲜艳3D星云系统已就绪 - ' + particleCount + '个粒子'; } catch (error) { console.error("Three.js初始化失败:", error); particleStatus.textContent = '星云系统初始化失败'; } }
function createVibrantParticleSystem() { try { console.log("创建鲜艳的粒子系统..."); particleGeometry = new THREE.BufferGeometry(); basePositions = []; const positions = new Float32Array(particleCount * 3); const colors = new Float32Array(particleCount * 3); const sizes = new Float32Array(particleCount); const cores = [ { x: 0, y: 0, z: 0, radius: 25, colorHue: 0.65, density: 0.35 }, { x: 15, y: 5, z: -10, radius: 15, colorHue: 0.8, density: 0.25 }, { x: -10, y: -8, z: 8, radius: 12, colorHue: 0.9, density: 0.15 }, { x: 5, y: 12, z: 15, radius: 10, colorHue: 0.55, density: 0.15 }, { x: -15, y: 10, z: -5, radius: 8, colorHue: 0.3, density: 0.1 } ]; let particleIndex = 0; for (const core of cores) { const particlesInCore = Math.floor(particleCount * core.density); for (let i = 0; i < particlesInCore && particleIndex < particleCount; i++) { const radius = core.radius * Math.pow(Math.random(), 0.5); const theta = Math.random() * Math.PI * 2; const phi = Math.acos(2 * Math.random() - 1); const x = core.x + radius * Math.sin(phi) * Math.cos(theta); const y = core.y + radius * Math.sin(phi) * Math.sin(theta); const z = core.z + radius * Math.cos(phi); const perturb = 3; const px = x + (Math.random() - 0.5) * perturb; const py = y + (Math.random() - 0.5) * perturb; const pz = z + (Math.random() - 0.5) * perturb; positions[particleIndex * 3] = px; positions[particleIndex * 3 + 1] = py; positions[particleIndex * 3 + 2] = pz; basePositions.push(px, py, pz); const distance = Math.sqrt(x*x + y*y + z*z) / core.radius; let hue, saturation, lightness; if (distance < 0.3) { hue = core.colorHue + (Math.random() - 0.5) * 0.08; saturation = 0.98 + Math.random() * 0.02; lightness = 0.85 + Math.random() * 0.15; } else if (distance < 0.7) { hue = core.colorHue + (Math.random() - 0.5) * 0.15; saturation = 0.9 + Math.random() * 0.08; lightness = 0.75 + Math.random() * 0.15; } else { hue = core.colorHue + (Math.random() - 0.5) * 0.25; saturation = 0.8 + Math.random() * 0.15; lightness = 0.6 + Math.random() * 0.2; } const color = new THREE.Color(); color.setHSL(hue, saturation, lightness); colors[particleIndex * 3] = Math.min(2.0, color.r * colorIntensity); colors[particleIndex * 3 + 1] = Math.min(2.0, color.g * colorIntensity); colors[particleIndex * 3 + 2] = Math.min(2.0, color.b * colorIntensity); let size; if (distance < 0.2) { size = 0.18 + Math.random() * 0.12; } else if (distance < 0.5) { size = 0.12 + Math.random() * 0.08; } else { size = 0.08 + Math.random() * 0.06; } sizes[particleIndex] = size; particleIndex++; } } for (; particleIndex < particleCount; particleIndex++) { const range = 60; const px = (Math.random() - 0.5) * range; const py = (Math.random() - 0.5) * range * 0.7; const pz = (Math.random() - 0.5) * range; positions[particleIndex * 3] = px; positions[particleIndex * 3 + 1] = py; positions[particleIndex * 3 + 2] = pz; basePositions.push(px, py, pz); const hue = Math.random(); const saturation = 0.8 + Math.random() * 0.2; const lightness = 0.7 + Math.random() * 0.3; const color = new THREE.Color(); color.setHSL(hue, saturation, lightness); colors[particleIndex * 3] = Math.min(2.0, color.r * 2.0); colors[particleIndex * 3 + 1] = Math.min(2.0, color.g * 2.0); colors[particleIndex * 3 + 2] = Math.min(2.0, color.b * 2.0); const size = 0.06 + Math.random() * 0.06; sizes[particleIndex] = size; } particleGeometry.setAttribute('position', new THREE.BufferAttribute(positions, 3)); particleGeometry.setAttribute('color', new THREE.BufferAttribute(colors, 3)); particleGeometry.setAttribute('size', new THREE.BufferAttribute(sizes, 1)); const vertexShader = ` attribute float size; attribute vec3 color; varying vec3 vColor; varying float vSize; uniform float time; uniform float scale; uniform float agitation; uniform float saturationBoost; uniform float colorIntensity; // 噪声函数,用于自然运动和躁动效果 float noise(vec3 p) { return sin(p.x*1.5 + time*0.5) * cos(p.y*1.3 + time*0.3) * sin(p.z*1.7 + time*0.7); } void main() { // 增强颜色饱和度和强度 vec3 enhancedColor = color * colorIntensity * saturationBoost; vColor = enhancedColor; vSize = size; // 应用基础位置 vec3 pos = position; // 应用缩放 pos *= scale; // 应用躁动效果 float noiseValue = noise(pos * 0.05 + time); pos.x += noiseValue * agitation * 3.0; pos.y += noise(pos.yzx * 0.05 + time) * agitation * 3.0; pos.z += noise(pos.zxy * 0.05 + time) * agitation * 2.0; // 添加微弱的自然运动(模拟星云流动) float naturalMovement = sin(time * 0.2 + position.x * 0.02) * 0.5; pos.x += naturalMovement; pos.y += cos(time * 0.3 + position.y * 0.02) * 0.5; pos.z += sin(time * 0.25 + position.z * 0.02) * 0.3; vec4 mvPosition = modelViewMatrix * vec4(pos, 1.0); // 粒子大小随躁动变化 - 躁动时粒子更大更亮 float sizeFactor = 1.0 + agitation * 1.5 + sin(time * 0.5 + position.x * 0.01) * 0.5; gl_PointSize = size * sizeFactor * (500.0 / -mvPosition.z); gl_Position = projectionMatrix * mvPosition; } `; const fragmentShader = ` varying vec3 vColor; varying float vSize; void main() { // 计算粒子中心的距离 vec2 coord = gl_PointCoord - vec2(0.5); float distance = length(coord); // 圆形粒子 if (distance > 0.5) { discard; } // 核心区域更亮 - 根据粒子大小调整 float coreSize = 0.5 - vSize * 0.1; float core = smoothstep(0.5, coreSize, distance); // 发光光晕效果 - 更强烈的发光 float glow = pow(1.0 - distance * 2.0, 4.0) * 2.5; // 边缘发光效果 float edgeGlow = pow(1.0 - distance * 1.3, 3.0) * 2.0; // 组合效果 float alpha = core * 1.5 + glow * 1.0 + edgeGlow * 0.7; alpha = min(alpha, 2.0); // 最终颜色,增强发光效果 vec3 finalColor = vColor + vec3(glow * 1.0) + vec3(edgeGlow * 0.5); finalColor = min(finalColor, vec3(3.0)); // 限制最大亮度 gl_FragColor = vec4(finalColor, alpha); } `; particleMaterial = new THREE.ShaderMaterial({ uniforms: { time: { value: 0 }, scale: { value: scale }, agitation: { value: agitation }, saturationBoost: { value: saturationBoost }, colorIntensity: { value: colorIntensity } }, vertexShader: vertexShader, fragmentShader: fragmentShader, transparent: true, blending: THREE.AdditiveBlending, depthWrite: false }); particles = new THREE.Points(particleGeometry, particleMaterial); scene.add(particles); console.log("鲜艳粒子系统创建成功"); } catch (error) { console.error("创建粒子系统失败:", error); particleStatus.textContent = '创建粒子系统失败'; } }
function initMediaPipeHands() { try { console.log("初始化MediaPipe Hands..."); if (typeof window.Hands === 'undefined') { console.error("MediaPipe Hands未加载"); handStatus.textContent = "MediaPipe库加载失败,请刷新页面"; return; } hands = new Hands({ locateFile: (file) => { return `https://cdn.jsdelivr.net/npm/@mediapipe/hands/${file}`; } }); hands.setOptions({ maxNumHands: 1, modelComplexity: 0, minDetectionConfidence: 0.6, minTrackingConfidence: 0.6 }); hands.onResults(onHandResults); console.log("MediaPipe Hands初始化成功"); handStatus.textContent = "手部检测系统就绪"; } catch (error) { console.error("MediaPipe初始化失败:", error); handStatus.textContent = "手部检测系统初始化失败"; } }
function onHandResults(results) { if (!results) { return; } handResults = results; if (results.image && videoCtx) { videoCtx.save(); videoCtx.clearRect(0, 0, videoCanvas.width, videoCanvas.height); videoCtx.drawImage(results.image, 0, 0, videoCanvas.width, videoCanvas.height); videoCtx.restore(); } if (!results.multiHandLandmarks || results.multiHandLandmarks.length === 0) { handStatus.textContent = '未检测到手部,请将手放在摄像头前'; scale = scale * 0.98 + 1.0 * 0.02; rotationX *= 0.95; rotationY *= 0.95; agitation *= 0.95; return; } handStatus.textContent = '手部已检测到,正在分析手势...'; if (results.multiHandLandmarks && videoCtx) { for (const landmarks of results.multiHandLandmarks) { drawHand(landmarks); processHandGesture(landmarks); } } }
function drawHand(landmarks) { if (!videoCtx) return; videoCtx.save(); videoCtx.strokeStyle = '#00FF00'; videoCtx.lineWidth = 2; const connections = [ [0, 1], [1, 2], [2, 3], [3, 4], [0, 5], [5, 6], [6, 7], [7, 8], [0, 9], [9, 10], [10, 11], [11, 12], [0, 13], [13, 14], [14, 15], [15, 16], [0, 17], [17, 18], [18, 19], [19, 20], [5, 9], [9, 13], [13, 17] ]; for (const [start, end] of connections) { const startPoint = landmarks[start]; const endPoint = landmarks[end]; videoCtx.beginPath(); videoCtx.moveTo(startPoint.x * videoCanvas.width, startPoint.y * videoCanvas.height); videoCtx.lineTo(endPoint.x * videoCanvas.width, endPoint.y * videoCanvas.height); videoCtx.stroke(); } for (let i = 0; i < landmarks.length; i++) { const landmark = landmarks[i]; let color = '#FFFF00'; if (i === 0) { color = '#ff1493'; } else if ([4, 8, 12, 16, 20].includes(i)) { color = '#00ffff'; } if (i === 8) { color = '#ff00ff'; } else if (i === 4) { color = '#ffff00'; } videoCtx.fillStyle = color; videoCtx.beginPath(); videoCtx.arc( landmark.x * videoCanvas.width, landmark.y * videoCanvas.height, (i === 0) ? 6 : (i === 8 || i === 4) ? 8 : 4, 0, Math.PI * 2 ); videoCtx.fill(); if (i === 8 || i === 4) { videoCtx.shadowColor = color; videoCtx.shadowBlur = 15; videoCtx.fill(); videoCtx.shadowBlur = 0; } } videoCtx.restore(); }
function processHandGesture(landmarks) { if (!landmarks || landmarks.length < 21) return; const now = Date.now(); const wrist = landmarks[0]; const thumbTip = landmarks[4]; const indexTip = landmarks[8]; rotationY = (indexTip.x - 0.5) * 4; rotationX = (0.5 - indexTip.y) * 2; const thumbIndexDistance = Math.sqrt( Math.pow(thumbTip.x - indexTip.x, 2) + Math.pow(thumbTip.y - indexTip.y, 2) ); scale = 0.5 + thumbIndexDistance * 2.5; scale = Math.max(0.5, Math.min(3.0, scale)); if (lastHandPosition) { const deltaTime = (now - lastGestureTime) / 1000; if (deltaTime > 0) { const deltaX = wrist.x - lastHandPosition.x; const deltaY = wrist.y - lastHandPosition.y; const movementSpeed = Math.sqrt(deltaX * deltaX + deltaY * deltaY) / deltaTime; agitation = Math.min(2.0, movementSpeed * 5); } lastGestureTime = now; } lastHandPosition = { x: wrist.x, y: wrist.y }; }
function setupEventListeners() { console.log("设置事件监听器..."); window.addEventListener('resize', onWindowResize); document.getElementById('start-btn').addEventListener('click', startCamera); document.getElementById('stop-btn').addEventListener('click', stopCamera); document.getElementById('reset-btn').addEventListener('click', resetParticles); onWindowResize(); console.log("事件监听器设置完成"); }
function onWindowResize() { if (particleCanvas && renderer && camera) { const width = particleCanvas.parentElement.clientWidth; const height = particleCanvas.parentElement.clientHeight; particleCanvas.width = width; particleCanvas.height = height; renderer.setSize(width, height); camera.aspect = width / height; camera.updateProjectionMatrix(); } if (videoCanvas) { const width = videoCanvas.parentElement.clientWidth; const height = videoCanvas.parentElement.clientHeight; videoCanvas.width = width; videoCanvas.height = height; } }
async function startCamera() { try { console.log("正在启动摄像头..."); handStatus.textContent = '正在请求摄像头权限...'; if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { throw new Error("您的浏览器不支持摄像头访问"); } const stream = await navigator.mediaDevices.getUserMedia({ video: { width: { ideal: 640 }, height: { ideal: 480 }, facingMode: 'user', frameRate: { ideal: 30 } }, audio: false }); console.log("摄像头权限已获得"); videoElement.srcObject = stream; handStatus.textContent = '摄像头已启动,请将手放在摄像头前'; await new Promise((resolve) => { videoElement.onloadedmetadata = () => { videoElement.play().then(resolve).catch(() => resolve()); }; }); isCameraActive = true; processVideoFrame(); console.log("摄像头启动成功"); } catch (error) { console.error('摄像头访问错误:', error); handStatus.textContent = '无法访问摄像头'; let errorMessage = '无法访问摄像头。请确保已授予摄像头权限。'; if (error.name === 'NotAllowedError') { errorMessage = '摄像头访问被拒绝。请允许摄像头权限并刷新页面。'; } else if (error.name === 'NotFoundError') { errorMessage = '未找到摄像头设备。请检查摄像头连接。'; } else if (error.name === 'NotReadableError') { errorMessage = '摄像头正被其他应用占用。'; } alert(errorMessage); } }
async function processVideoFrame() { if (!isCameraActive) return; try { if (videoElement.readyState < 2) { setTimeout(() => processVideoFrame(), 100); return; } const tempCanvas = document.createElement('canvas'); tempCanvas.width = videoElement.videoWidth || 640; tempCanvas.height = videoElement.videoHeight || 480; const tempCtx = tempCanvas.getContext('2d'); tempCtx.drawImage(videoElement, 0, 0, tempCanvas.width, tempCanvas.height); if (hands && typeof hands.send === 'function') { await hands.send({image: tempCanvas}); } setTimeout(() => processVideoFrame(), 50); } catch (error) { console.error('处理视频帧时出错:', error); setTimeout(() => processVideoFrame(), 100); } }
function stopCamera() { console.log("停止摄像头"); isCameraActive = false; if (videoElement.srcObject) { const tracks = videoElement.srcObject.getTracks(); tracks.forEach(track => track.stop()); videoElement.srcObject = null; } handStatus.textContent = '摄像头已停止'; if (videoCtx) { videoCtx.clearRect(0, 0, videoCanvas.width, videoCanvas.height); videoCtx.fillStyle = '#ffffff'; videoCtx.font = '20px Arial'; videoCtx.textAlign = 'center'; videoCtx.fillText('摄像头已停止', videoCanvas.width/2, videoCanvas.height/2); } handResults = null; scale = 1.0; rotationX = 0; rotationY = 0; agitation = 0; }
function resetParticles() { console.log("重置粒子系统"); if (scene && particles) { scene.remove(particles); createVibrantParticleSystem(); } scale = 1.0; rotationX = 0; rotationY = 0; agitation = 0; time = 0; particleStatus.textContent = '星云已重置为鲜艳状态'; }
function animate(timestamp) { requestAnimationFrame(animate); time = timestamp * 0.001; if (particleMaterial && particleMaterial.uniforms) { particleMaterial.uniforms.time.value = time; particleMaterial.uniforms.scale.value = scale; particleMaterial.uniforms.agitation.value = agitation; particleMaterial.uniforms.saturationBoost.value = saturationBoost; particleMaterial.uniforms.colorIntensity.value = colorIntensity; } if (particles) { particles.rotation.y += rotationY * 0.01; particles.rotation.x += rotationX * 0.01; if (Math.abs(rotationY) < 0.1 && Math.abs(rotationX) < 0.1) { particles.rotation.y += 0.01; particles.rotation.x += 0.005 * Math.sin(time * 0.1); } particles.rotation.z += 0.002 * Math.sin(time * 0.3); } if (renderer && scene && camera) { renderer.render(scene, camera); } }
window.addEventListener('DOMContentLoaded', () => { console.log("DOM加载完成,开始初始化"); init(); });
|