Spaces:
Running
Running
File size: 9,082 Bytes
303fdae 83b5d8a 303fdae 83b5d8a 303fdae 83b5d8a 303fdae 83b5d8a 303fdae 83b5d8a 303fdae 83b5d8a 303fdae 83b5d8a 303fdae 83b5d8a 303fdae 83b5d8a 303fdae 83b5d8a 303fdae 83b5d8a 303fdae 83b5d8a 303fdae 83b5d8a 303fdae | 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 | document.addEventListener("DOMContentLoaded", () => {
// DOM Elements
const video = document.getElementById("camera-stream");
const canvas = document.getElementById("overlay-canvas");
const ctx = canvas.getContext("2d", { willReadFrequently: true });
const sourceImage = document.getElementById("source-image");
// Controls
const opacitySlider = document.getElementById("opacity-slider");
const opacityVal = document.getElementById("opacity-val");
const scaleSlider = document.getElementById("scale-slider");
const scaleVal = document.getElementById("scale-val");
const colorPicker = document.getElementById("color-picker");
const toleranceSlider = document.getElementById("tolerance-slider");
const toleranceVal = document.getElementById("tolerance-val");
const imageUpload = document.getElementById("image-upload");
const lockBtn = document.getElementById("lock-btn");
const unlockBtn = document.getElementById("unlock-btn");
const resetBtn = document.getElementById("reset-btn");
// State
let isLocked = false;
let imgX = 0;
let imgY = 0;
let scale = 1.0;
// Touch & Drag State
let isDragging = false;
let startDragX = 0;
let startDragY = 0;
let initialPinchDistance = null;
let initialScale = 1.0;
let initialPinchCenter = { x: 0, y: 0 };
// Original image data for processing
let originalImageData = null;
// --- Camera Setup ---
async function setupCamera() {
try {
const stream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: "environment" }, // Prefer rear camera
});
video.srcObject = stream;
} catch (err) {
console.error("Error accessing camera:", err);
alert(
"Could not access the camera. Please ensure you have granted permission.",
);
}
}
// --- Image Processing ---
function hexToRgb(hex) {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result
? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16),
}
: { r: 255, g: 255, b: 255 };
}
function processImageColor() {
if (!originalImageData) return;
const targetColor = hexToRgb(colorPicker.value);
const tolerance = parseInt(toleranceSlider.value, 10);
// Create a copy of the original data to modify
const processedData = new ImageData(
new Uint8ClampedArray(originalImageData.data),
originalImageData.width,
originalImageData.height,
);
const data = processedData.data;
for (let i = 0; i < data.length; i += 4) {
const r = data[i];
const g = data[i + 1];
const b = data[i + 2];
// Calculate color distance (simple Manhattan distance for speed)
const rDiff = Math.abs(r - targetColor.r);
const gDiff = Math.abs(g - targetColor.g);
const bDiff = Math.abs(b - targetColor.b);
// If the pixel is within tolerance of the target color, make it transparent
if (rDiff <= tolerance && gDiff <= tolerance && bDiff <= tolerance) {
data[i + 3] = 0; // Set alpha to 0
}
}
ctx.putImageData(processedData, 0, 0);
}
function initImage() {
// Set canvas size to match image
canvas.width = sourceImage.naturalWidth;
canvas.height = sourceImage.naturalHeight;
// Draw initial image
ctx.drawImage(sourceImage, 0, 0);
// Store original data for color processing
originalImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
// Center the image initially
resetPosition();
// Apply initial transparency if needed
processImageColor();
}
// --- Interactions & Controls ---
function updateTransform() {
canvas.style.transform = `translate(${imgX}px, ${imgY}px) scale(${scale})`;
canvas.style.opacity = opacitySlider.value;
// Sync slider with scale
scaleSlider.value = scale;
scaleVal.textContent = scale.toFixed(1) + "x";
}
function resetPosition() {
scale = 1.0;
// Center based on window size and canvas size
imgX = (window.innerWidth - canvas.width) / 2;
// Place it slightly higher than center to leave room for controls
imgY = (window.innerHeight - canvas.height) / 3;
updateTransform();
}
// --- Multi-Touch Gesture Logic ---
function getPinchDistance(touches) {
const dx = touches[0].clientX - touches[1].clientX;
const dy = touches[0].clientY - touches[1].clientY;
return Math.sqrt(dx * dx + dy * dy);
}
function getPinchCenter(touches) {
return {
x: (touches[0].clientX + touches[1].clientX) / 2,
y: (touches[0].clientY + touches[1].clientY) / 2,
};
}
function startDrag(e) {
if (isLocked) return;
e.preventDefault(); // Prevent default touch actions like scrolling
if (e.touches) {
if (e.touches.length === 1) {
// Single finger: Pan
isDragging = true;
startDragX = e.touches[0].clientX - imgX;
startDragY = e.touches[0].clientY - imgY;
} else if (e.touches.length === 2) {
// Two fingers: Zoom & Pan
isDragging = true;
initialPinchDistance = getPinchDistance(e.touches);
initialScale = scale;
const center = getPinchCenter(e.touches);
startDragX = center.x - imgX;
startDragY = center.y - imgY;
}
} else {
// Mouse drag
isDragging = true;
startDragX = e.clientX - imgX;
startDragY = e.clientY - imgY;
}
}
function doDrag(e) {
if (!isDragging || isLocked) return;
e.preventDefault();
if (e.touches) {
if (e.touches.length === 1) {
// Single finger: Pan
imgX = e.touches[0].clientX - startDragX;
imgY = e.touches[0].clientY - startDragY;
} else if (e.touches.length === 2) {
// Two fingers: Zoom & Pan
// 1. Handle Pan (using midpoint)
const center = getPinchCenter(e.touches);
imgX = center.x - startDragX;
imgY = center.y - startDragY;
// 2. Handle Zoom
if (initialPinchDistance) {
const currentDistance = getPinchDistance(e.touches);
const distanceRatio = currentDistance / initialPinchDistance;
let newScale = initialScale * distanceRatio;
// Constrain scale to reasonable limits
newScale = Math.max(0.1, Math.min(newScale, 5.0));
scale = newScale;
}
}
} else {
// Mouse drag
imgX = e.clientX - startDragX;
imgY = e.clientY - startDragY;
}
updateTransform();
}
function endDrag(e) {
if (e.touches && e.touches.length > 0) {
// If one finger remains after a pinch, reset the drag starting point so it doesn't jump
isDragging = true;
startDragX = e.touches[0].clientX - imgX;
startDragY = e.touches[0].clientY - imgY;
initialPinchDistance = null;
} else {
isDragging = false;
initialPinchDistance = null;
}
}
// Event Listeners for Dragging & Gestures
canvas.addEventListener("mousedown", startDrag);
window.addEventListener("mousemove", doDrag);
window.addEventListener("mouseup", endDrag);
// Use passive: false so we can call e.preventDefault() to stop page scroll
canvas.addEventListener("touchstart", startDrag, { passive: false });
window.addEventListener("touchmove", doDrag, { passive: false });
window.addEventListener("touchend", endDrag);
window.addEventListener("touchcancel", endDrag);
// Controls Listeners
opacitySlider.addEventListener("input", (e) => {
opacityVal.textContent = Math.round(e.target.value * 100) + "%";
canvas.style.opacity = e.target.value;
});
scaleSlider.addEventListener("input", (e) => {
scale = parseFloat(e.target.value);
updateTransform();
});
colorPicker.addEventListener("input", processImageColor);
toleranceSlider.addEventListener("input", (e) => {
toleranceVal.textContent = e.target.value;
processImageColor();
});
resetBtn.addEventListener("click", resetPosition);
// Lock logic
lockBtn.addEventListener("click", () => {
isLocked = true;
document.body.classList.add("locked");
lockBtn.style.display = "none";
unlockBtn.style.display = "block"; // Explicitly show the unlock button
});
unlockBtn.addEventListener("click", () => {
isLocked = false;
document.body.classList.remove("locked");
lockBtn.style.display = "inline-block";
unlockBtn.style.display = "none"; // Hide unlock button
});
imageUpload.addEventListener("change", (e) => {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (event) => {
sourceImage.onload = () => {
initImage();
};
sourceImage.src = event.target.result;
};
reader.readAsDataURL(file);
});
// --- Initialization ---
// Ensure image loads (especially useful for local dev or cached images)
if (sourceImage.complete) {
initImage();
} else {
sourceImage.onload = initImage;
}
setupCamera();
});
|