Interactive Camera Feed Controller Demo
Here's a complete HTML file that creates an interactive demo where the user's camera feed acts as a controller. This demo includes:
- Camera access
- Motion detection
- Color tracking
- Simple game mechanics
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Camera Controller Demo</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
background-color: #f0f0f0;
color: #333;
}
.container {
max-width: 800px;
margin: 0 auto;
background-color: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
h1 {
text-align: center;
color: #2c3e50;
}
.video-container {
display: flex;
justify-content: center;
margin: 20px 0;
}
#video {
width: 100%;
max-width: 640px;
border: 2px solid #3498db;
border-radius: 5px;
}
.controls {
display: flex;
justify-content: center;
margin: 20px 0;
}
button {
background-color: #3498db;
color: white;
border: none;
padding: 10px 20px;
margin: 0 10px;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
}
button:hover {
background-color: #2980b9;
}
.game-container {
width: 100%;
height: 300px;
background-color: #ecf0f1;
border: 2px solid #3498db;
border-radius: 5px;
position: relative;
overflow: hidden;
margin: 20px 0;
}
#player {
width: 50px;
height: 50px;
background-color: #e74c3c;
position: absolute;
border-radius: 50%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
#target {
width: 30px;
height: 30px;
background-color: #2ecc71;
position: absolute;
border-radius: 50%;
}
.stats {
display: flex;
justify-content: space-around;
margin: 20px 0;
}
.stat-box {
background-color: #ecf0f1;
padding: 10px 20px;
border-radius: 5px;
text-align: center;
}
.instructions {
background-color: #f8f9fa;
padding: 15px;
border-radius: 5px;
margin: 20px 0;
}
</style>
</head>
<body>
<div class="container">
<h1>Camera Controller Demo</h1>
<div class="instructions">
<p>This demo uses your camera feed as a controller. Move your hand or a colored object to control the game.</p>
<p>Try to keep the red player circle over the green target to score points!</p>
</div>
<div class="video-container">
<video id="video" autoplay muted playsinline></video>
</div>
<div class="controls">
<button id="startButton">Start Camera</button>
<button id="stopButton">Stop Camera</button>
<button id="resetButton">Reset Game</button>
</div>
<div class="game-container">
<div id="player"></div>
<div id="target"></div>
</div>
<div class="stats">
<div class="stat-box">
<h3>Score</h3>
<p id="score">0</p>
</div>
<div class="stat-box">
<h3>Time</h3>
<p id="time">0</p>
</div>
<div class="stat-box">
<h3>Accuracy</h3>
<p id="accuracy">0%</p>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/handtrackjs@0.0.6/dist/handtrack.min.js"></script>
<script>
// Game variables
let score = 0;
let time = 0;
let hits = 0;
let attempts = 0;
let gameInterval;
let model = null;
let video = document.getElementById('video');
let canvas = document.createElement('canvas');
let ctx = canvas.getContext('2d');
let player = document.getElementById('player');
let target = document.getElementById('target');
let isTracking = false;
let lastPosition = { x: 0, y: 0 };
// Initialize game
function initGame() {
score = 0;
time = 0;
hits = 0;
attempts = 0;
updateStats();
// Position target randomly
positionTarget();
// Start game loop
if (gameInterval) clearInterval(gameInterval);
gameInterval = setInterval(gameLoop, 100);
}
// Position target randomly
function positionTarget() {
const gameContainer = document.querySelector('.game-container');
const gameWidth = gameContainer.offsetWidth;
const gameHeight = gameContainer.offsetHeight;
const targetSize = 30;
const maxX = gameWidth - targetSize;
const maxY = gameHeight - targetSize;
const x = Math.floor(Math.random() * maxX);
const y = Math.floor(Math.random() * maxY);
target.style.left = `${x}px`;
target.style.top = `${y}px`;
}
// Game loop
function gameLoop() {
time++;
updateStats();
// Check if player is near target
checkCollision();
// Move target occasionally
if (time % 100 === 0) {
positionTarget();
}
}
// Check collision between player and target
function checkCollision() {
const playerRect = player.getBoundingClientRect();
const targetRect = target.getBoundingClientRect();
const distance = Math.sqrt(
Math.pow(playerRect.left - targetRect.left, 2) +
Math.pow(playerRect.top - targetRect.top, 2)
);
const threshold = 50; // pixels
if (distance < threshold) {
hits++;
score += 10;
positionTarget();
}
attempts++;
updateStats();
}
// Update stats display
function updateStats() {
document.getElementById('score').textContent = score;
document.getElementById('time').textContent = time;
if (attempts > 0) {
const accuracy = Math.round((hits / attempts) * 100);
document.getElementById('accuracy').textContent = `${accuracy}%`;
}
}
// Start camera
document.getElementById('startButton').addEventListener('click', async () => {
try {
const stream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: 'user' },
audio: false
});
video.srcObject = stream;
video.play();
// Load hand tracking model
model = await handTrack.load();
isTracking = true;
detectHand();
initGame();
} catch (err) {
console.error("Error accessing camera:", err);
alert("Could not access the camera. Please ensure you have granted permissions.");
}
});
// Stop camera
document.getElementById('stopButton').addEventListener('click', () => {
if (video.srcObject) {
video.srcObject.getTracks().forEach(track => track.stop());
video.srcObject = null;
isTracking = false;
}
});
// Reset game
document.getElementById('resetButton').addEventListener('click', initGame);
// Detect hand and update player position
async function detectHand() {
if (!isTracking || !model) return;
const predictions = await model.detect(video);
if (predictions.length > 0) {
// Get the first detected hand
const hand = predictions[0].bbox;
// Calculate center of the hand
const centerX = hand[0] + (hand[2] / 2);
const centerY = hand[1] + (hand[3] / 2);
// Normalize coordinates to game container
const gameContainer = document.querySelector('.game-container');
const gameWidth = gameContainer.offsetWidth;
const gameHeight = gameContainer.offsetHeight;
const x = (centerX / video.videoWidth) * gameWidth;
const y = (centerY / video.videoHeight) * gameHeight;
// Update player position with some smoothing
lastPosition.x = x;
lastPosition.y = y;
player.style.left = `${x}px`;
player.style.top = `${y}px`;
}
requestAnimationFrame(detectHand);
}
// Initialize
initGame();
</script>
</body>
</html>
How This Demo Works:
-
Camera Access: The demo requests access to the user's camera and displays the feed.
-
Hand Tracking: Using the HandTrack.js library (loaded from CDN), it detects hands in the video feed.
-
Game Mechanics:
- A red player circle is controlled by the position of your hand
- A green target appears randomly on the screen
- You score points by keeping the red circle near the green target
-
Stats Tracking:
- Score increases when you're near the target
- Time tracks how long you've been playing
- Accuracy shows your success rate
-
Controls:
- Start/Stop camera buttons
- Reset game button
To use this demo, simply save the code as an HTML file and open it in a modern browser. You'll need to grant camera permissions when prompted.