Listen to this article
gfgfg
"use client";
import { useState, useEffect, useRef } from "react";
export default function FilterCamera() {
const videoRef = useRef(null);
const [currentFilter, setCurrentFilter] = useState<"red" | "blue">("red");
const [isCameraActive, setIsCameraActive] = useState(false);
const [error, setError] = useState(null);
// Touch handling for swipe detection
const touchStartX = useRef(0);
const touchEndX = useRef(0);
// Initialize camera
useEffect(() => {
const initCamera = async () => {
try {
const stream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: "environment" }
});
if (videoRef.current) {
videoRef.current.srcObject = stream;
setIsCameraActive(true);
}
} catch (err) {
console.error("Camera error:", err);
setError("Could not access camera. Please ensure you've granted permission.");
}
};
initCamera();
return () => {
if (videoRef.current?.srcObject) {
const tracks = (videoRef.current.srcObject as MediaStream).getTracks();
tracks.forEach(track => track.stop());
}
};
}, []);
// Handle touch events for swipe detection
const handleTouchStart = (e: React.TouchEvent) => {
touchStartX.current = e.touches[0].clientX;
};
const handleTouchMove = (e: React.TouchEvent) => {
touchEndX.current = e.touches[0].clientX;
};
const handleTouchEnd = () => {
if (!touchStartX.current || !touchEndX.current) return;
const distance = touchStartX.current - touchEndX.current;
const isLeftSwipe = distance > 50;
const isRightSwipe = distance < -50;
if (isLeftSwipe) {
setCurrentFilter("blue");
} else if (isRightSwipe) {
setCurrentFilter("red");
}
};
// Filter classes
const filterClass = currentFilter === "red"
? "hue-rotate-[90deg] saturate-[5]"
: "hue-rotate-[180deg] saturate-[5]";
return (
) : (
<>
>
)}
);
}
Filter Camera
{error ? ({error}
{isCameraActive ? (
) : (
)}
{/* Filter indicator */}
{/* Swipe instructions */}
Loading camera...
{currentFilter === "red" ? "Red Filter" : "Blue Filter"}
Swipe left/right to switch filters
Red
⟷
Blue
