| 649 | } |
| 650 | |
| 651 | function setupHandTracking() { |
| 652 | if (!videoElement || !canvasElement || !canvasCtx) { |
| 653 | console.error("Video or Canvas element not ready for Hand Tracking setup."); |
| 654 | return; |
| 655 | } |
| 656 | |
| 657 | // Check if MediaPipe components are loaded |
| 658 | if (typeof Hands === 'undefined' || typeof Camera === 'undefined' || |
| 659 | typeof drawConnectors === 'undefined' || typeof drawLandmarks === 'undefined') { |
| 660 | console.error("MediaPipe Hands/Camera/Drawing library not found."); |
| 661 | const instructions = document.getElementById('instructions'); |
| 662 | if(instructions) instructions.textContent = "Hand tracking library failed to load."; |
| 663 | return; |
| 664 | } |
| 665 | |
| 666 | // Reset clap detection variables |
| 667 | lastHandDistance = Infinity; |
| 668 | handsComeCloser = false; |
| 669 | handsMovingApart = false; |
| 670 | |
| 671 | try { |
| 672 | hands = new Hands({locateFile: (file) => { |
| 673 | return `https://cdn.jsdelivr.net/npm/@mediapipe/hands/${file}`; |
| 674 | }}); |
| 675 | |
| 676 | hands.setOptions({ |
| 677 | // --- Track up to two hands --- |
| 678 | maxNumHands: 2, |
| 679 | // --- |
| 680 | modelComplexity: 1, |
| 681 | minDetectionConfidence: 0.6, // Adjusted confidence |
| 682 | minTrackingConfidence: 0.6 |
| 683 | }); |
| 684 | |
| 685 | hands.onResults(onResults); |
| 686 | |
| 687 | const camera = new Camera(videoElement, { |
| 688 | onFrame: async () => { |
| 689 | if (videoElement.readyState >= 2) { // HAVE_CURRENT_DATA or more |
| 690 | await hands.send({image: videoElement}); |
| 691 | } |
| 692 | }, |
| 693 | width: 640, // Internal processing resolution |
| 694 | height: 360 |
| 695 | }); |
| 696 | |
| 697 | camera.start() |
| 698 | .then(() => console.log("Camera started successfully.")) |
| 699 | .catch(err => { |
| 700 | console.error("Error starting webcam:", err); |
| 701 | const instructions = document.getElementById('instructions'); |
| 702 | if(instructions) instructions.textContent = "Could not access webcam. Please grant permission and reload."; |
| 703 | }); |
| 704 | |
| 705 | console.log("Hand tracking setup complete."); |
| 706 | |
| 707 | } catch (error) { |
| 708 | console.error("Error setting up MediaPipe Hands:", error); |