File size: 40,323 Bytes
beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 05ba257 beccaa3 |
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 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Virtual Fitting Room</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/face-landmarks-detection@0.0.1/dist/face-landmarks-detection.js"></script>
<style>
.loading-spinner {
border: 4px solid rgba(255, 255, 255, 0.3);
border-radius: 50%;
border-top: 4px solid #6366f1;
width: 30px;
height: 30px;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.measurement-line {
position: absolute;
background-color: rgba(99, 102, 241, 0.7);
height: 2px;
transform-origin: left center;
z-index: 10;
}
.measurement-label {
position: absolute;
background-color: rgba(99, 102, 241, 0.9);
color: white;
padding: 2px 5px;
border-radius: 4px;
font-size: 12px;
z-index: 11;
transform: translateY(-50%);
}
.clothing-item {
position: absolute;
transition: all 0.3s ease;
cursor: move;
z-index: 5;
}
.clothing-item.selected {
outline: 2px solid #6366f1;
}
.posture-indicator {
position: absolute;
width: 10px;
height: 10px;
border-radius: 50%;
background-color: #10b981;
z-index: 10;
}
.posture-indicator.bad {
background-color: #ef4444;
}
#previewCanvas {
transform: scaleX(-1);
}
</style>
</head>
<body class="bg-gray-100 min-h-screen">
<div class="container mx-auto px-4 py-8">
<header class="mb-8">
<h1 class="text-3xl font-bold text-indigo-700 text-center">Virtual Fitting Room</h1>
<p class="text-gray-600 text-center mt-2">Try on clothes virtually with real-time measurements</p>
</header>
<div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
<!-- Camera Feed Section -->
<div class="lg:col-span-2 bg-white rounded-lg shadow-md p-4">
<div class="relative">
<video id="video" width="100%" height="auto" autoplay muted playsinline class="rounded-lg hidden"></video>
<canvas id="previewCanvas" width="640" height="480" class="rounded-lg w-full"></canvas>
<div id="loadingIndicator" class="absolute inset-0 flex items-center justify-center bg-black bg-opacity-50 rounded-lg">
<div class="loading-spinner"></div>
<span class="ml-2 text-white">Loading models...</span>
</div>
<div id="errorMessage" class="absolute inset-0 flex items-center justify-center bg-black bg-opacity-50 rounded-lg hidden">
<div class="bg-red-500 text-white p-4 rounded-lg">
<p id="errorText">Error message</p>
<button id="retryButton" class="mt-2 bg-white text-red-500 px-4 py-1 rounded">Retry</button>
</div>
</div>
</div>
<div class="mt-4 flex flex-wrap gap-2">
<button id="startCamera" class="bg-indigo-600 text-white px-4 py-2 rounded hover:bg-indigo-700 transition">
Start Camera
</button>
<button id="takePhoto" class="bg-green-600 text-white px-4 py-2 rounded hover:bg-green-700 transition hidden">
Take Photo
</button>
<button id="toggleMeasurements" class="bg-purple-600 text-white px-4 py-2 rounded hover:bg-purple-700 transition">
Show Measurements
</button>
<button id="togglePosture" class="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700 transition">
Show Posture
</button>
<button id="resetClothing" class="bg-gray-600 text-white px-4 py-2 rounded hover:bg-gray-700 transition">
Reset Clothing
</button>
</div>
<div class="mt-4 p-4 bg-gray-50 rounded-lg">
<h3 class="font-semibold text-lg mb-2">Posture Analysis</h3>
<div id="postureFeedback" class="text-sm">
<p>Stand in front of the camera to analyze your posture.</p>
</div>
</div>
</div>
<!-- Clothing Selection Section -->
<div class="bg-white rounded-lg shadow-md p-4">
<h2 class="text-xl font-semibold mb-4">Select Clothing</h2>
<div class="mb-4">
<label class="block text-sm font-medium text-gray-700 mb-1">Clothing Type</label>
<select id="clothingType" class="w-full p-2 border border-gray-300 rounded-md">
<option value="t-shirt">T-Shirt</option>
<option value="shirt">Shirt</option>
<option value="dress">Dress</option>
<option value="pants">Pants</option>
<option value="jacket">Jacket</option>
</select>
</div>
<div class="mb-4">
<label class="block text-sm font-medium text-gray-700 mb-1">Color</label>
<div class="flex flex-wrap gap-2">
<div class="w-8 h-8 rounded-full bg-red-500 cursor-pointer border-2 border-transparent hover:border-gray-300" data-color="red"></div>
<div class="w-8 h-8 rounded-full bg-blue-500 cursor-pointer border-2 border-transparent hover:border-gray-300" data-color="blue"></div>
<div class="w-8 h-8 rounded-full bg-green-500 cursor-pointer border-2 border-transparent hover:border-gray-300" data-color="green"></div>
<div class="w-8 h-8 rounded-full bg-black cursor-pointer border-2 border-transparent hover:border-gray-300" data-color="black"></div>
<div class="w-8 h-8 rounded-full bg-white cursor-pointer border-2 border-gray-300 hover:border-gray-500" data-color="white"></div>
<div class="w-8 h-8 rounded-full bg-yellow-400 cursor-pointer border-2 border-transparent hover:border-gray-300" data-color="yellow"></div>
</div>
</div>
<div class="mb-4">
<label class="block text-sm font-medium text-gray-700 mb-1">Pattern</label>
<div class="flex flex-wrap gap-2">
<div class="w-12 h-12 bg-gray-200 cursor-pointer border-2 border-transparent hover:border-gray-300 flex items-center justify-center" data-pattern="solid">
<span class="text-xs">Solid</span>
</div>
<div class="w-12 h-12 bg-gray-200 cursor-pointer border-2 border-transparent hover:border-gray-300" style="background-image: linear-gradient(45deg, #ccc 25%, transparent 25%, transparent 75%, #ccc 75%, #ccc), linear-gradient(45deg, #ccc 25%, transparent 25%, transparent 75%, #ccc 75%, #ccc); background-size: 10px 10px;" data-pattern="checkered"></div>
<div class="w-12 h-12 bg-gray-200 cursor-pointer border-2 border-transparent hover:border-gray-300" style="background-image: radial-gradient(circle, #999 1px, transparent 1px); background-size: 10px 10px;" data-pattern="polka"></div>
<div class="w-12 h-12 bg-gray-200 cursor-pointer border-2 border-transparent hover:border-gray-300" style="background-image: linear-gradient(0deg, #999, #999 50%, transparent 50%, transparent 100%); background-size: 10px 10px;" data-pattern="striped"></div>
</div>
</div>
<div class="mb-4">
<label class="block text-sm font-medium text-gray-700 mb-1">Size Adjustment</label>
<div class="flex items-center gap-2">
<button id="decreaseSize" class="bg-gray-200 p-1 rounded-full w-8 h-8 flex items-center justify-center hover:bg-gray-300">-</button>
<span id="sizeValue" class="font-medium">100%</span>
<button id="increaseSize" class="bg-gray-200 p-1 rounded-full w-8 h-8 flex items-center justify-center hover:bg-gray-300">+</button>
</div>
</div>
<button id="addClothing" class="w-full bg-indigo-600 text-white px-4 py-2 rounded hover:bg-indigo-700 transition">
Add to Fitting Room
</button>
<div class="mt-6">
<h3 class="font-semibold text-lg mb-2">Your Measurements</h3>
<div id="measurementsDisplay" class="text-sm space-y-1">
<div class="flex justify-between">
<span>Shoulder Width:</span>
<span id="shoulderWidth">-- cm</span>
</div>
<div class="flex justify-between">
<span>Chest Width:</span>
<span id="chestWidth">-- cm</span>
</div>
<div class="flex justify-between">
<span>Waist Width:</span>
<span id="waistWidth">-- cm</span>
</div>
<div class="flex justify-between">
<span>Hip Width:</span>
<span id="hipWidth">-- cm</span>
</div>
<div class="flex justify-between">
<span>Torso Length:</span>
<span id="torsoLength">-- cm</span>
</div>
</div>
</div>
<div class="mt-6 p-4 bg-indigo-50 rounded-lg">
<h3 class="font-semibold text-lg mb-2 text-indigo-800">Fit Recommendation</h3>
<div id="fitRecommendation" class="text-sm text-indigo-700">
<p>Add clothing to see fit recommendations based on your measurements.</p>
</div>
</div>
</div>
</div>
</div>
<script>
// Global variables
let model = null;
let video = document.getElementById('video');
let canvas = document.getElementById('previewCanvas');
let ctx = canvas.getContext('2d');
let loadingIndicator = document.getElementById('loadingIndicator');
let errorMessage = document.getElementById('errorMessage');
let errorText = document.getElementById('errorText');
let retryButton = document.getElementById('retryButton');
let startCameraButton = document.getElementById('startCamera');
let takePhotoButton = document.getElementById('takePhoto');
let toggleMeasurementsButton = document.getElementById('toggleMeasurements');
let togglePostureButton = document.getElementById('togglePosture');
let resetClothingButton = document.getElementById('resetClothing');
let addClothingButton = document.getElementById('addClothing');
let clothingTypeSelect = document.getElementById('clothingType');
let decreaseSizeButton = document.getElementById('decreaseSize');
let increaseSizeButton = document.getElementById('increaseSize');
let sizeValueSpan = document.getElementById('sizeValue');
let postureFeedback = document.getElementById('postureFeedback');
let fitRecommendation = document.getElementById('fitRecommendation');
// Measurement display elements
let shoulderWidthSpan = document.getElementById('shoulderWidth');
let chestWidthSpan = document.getElementById('chestWidth');
let waistWidthSpan = document.getElementById('waistWidth');
let hipWidthSpan = document.getElementById('hipWidth');
let torsoLengthSpan = document.getElementById('torsoLength');
// State variables
let isCameraOn = false;
let showMeasurements = false;
let showPosture = false;
let currentSize = 100;
let selectedColor = 'blue';
let selectedPattern = 'solid';
let clothingItems = [];
let selectedClothingItem = null;
let isDragging = false;
let dragOffsetX = 0;
let dragOffsetY = 0;
let measurements = {
shoulderWidth: 0,
chestWidth: 0,
waistWidth: 0,
hipWidth: 0,
torsoLength: 0
};
// Constants
const PIXELS_PER_CM = 10; // This would need calibration in a real application
const GOOD_POSTURE_THRESHOLD = 5; // Degrees from vertical
// Initialize the application
async function init() {
try {
// Load the face and body detection model
model = await faceLandmarksDetection.load(
faceLandmarksDetection.SupportedPackages.mediapipeFacemesh,
{ maxFaces: 1 }
);
loadingIndicator.classList.add('hidden');
startCameraButton.classList.remove('hidden');
// Set up event listeners
setupEventListeners();
} catch (error) {
console.error('Error loading model:', error);
showError('Failed to load the detection model. Please try again.');
}
}
// Set up all event listeners
function setupEventListeners() {
// Camera controls
startCameraButton.addEventListener('click', startCamera);
retryButton.addEventListener('click', init);
takePhotoButton.addEventListener('click', takePhoto);
// Display toggles
toggleMeasurementsButton.addEventListener('click', () => {
showMeasurements = !showMeasurements;
toggleMeasurementsButton.classList.toggle('bg-purple-600');
toggleMeasurementsButton.classList.toggle('bg-gray-600');
});
togglePostureButton.addEventListener('click', () => {
showPosture = !showPosture;
togglePostureButton.classList.toggle('bg-blue-600');
togglePostureButton.classList.toggle('bg-gray-600');
});
resetClothingButton.addEventListener('click', resetClothing);
// Clothing selection
document.querySelectorAll('[data-color]').forEach(el => {
el.addEventListener('click', () => {
document.querySelectorAll('[data-color]').forEach(e => e.classList.remove('border-indigo-500'));
el.classList.add('border-indigo-500');
selectedColor = el.getAttribute('data-color');
});
});
document.querySelectorAll('[data-pattern]').forEach(el => {
el.addEventListener('click', () => {
document.querySelectorAll('[data-pattern]').forEach(e => e.classList.remove('border-indigo-500'));
el.classList.add('border-indigo-500');
selectedPattern = el.getAttribute('data-pattern');
});
});
// Size adjustment
decreaseSizeButton.addEventListener('click', () => {
if (currentSize > 50) {
currentSize -= 5;
sizeValueSpan.textContent = `${currentSize}%`;
if (selectedClothingItem) {
resizeClothing(selectedClothingItem, currentSize);
}
}
});
increaseSizeButton.addEventListener('click', () => {
if (currentSize < 150) {
currentSize += 5;
sizeValueSpan.textContent = `${currentSize}%`;
if (selectedClothingItem) {
resizeClothing(selectedClothingItem, currentSize);
}
}
});
// Add clothing
addClothingButton.addEventListener('click', addClothingItem);
// Default selections
document.querySelector('[data-color="blue"]').classList.add('border-indigo-500');
document.querySelector('[data-pattern="solid"]').classList.add('border-indigo-500');
}
// Start the camera
async function startCamera() {
try {
const stream = await navigator.mediaDevices.getUserMedia({
video: { width: 640, height: 480, facingMode: 'user' },
audio: false
});
video.srcObject = stream;
video.classList.remove('hidden');
startCameraButton.classList.add('hidden');
takePhotoButton.classList.remove('hidden');
isCameraOn = true;
// Start detection loop
detect();
} catch (error) {
console.error('Error accessing camera:', error);
showError('Could not access the camera. Please ensure you have granted camera permissions.');
}
}
// Main detection loop
async function detect() {
if (!isCameraOn || !model) return;
try {
// Get face landmarks
const faces = await model.estimateFaces({
input: video,
returnTensors: false,
flipHorizontal: false,
predictIrises: true
});
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw video frame (mirrored)
ctx.save();
ctx.scale(-1, 1);
ctx.drawImage(video, 0, 0, canvas.width * -1, canvas.height);
ctx.restore();
if (faces.length > 0) {
const face = faces[0];
// Calculate measurements based on face landmarks
calculateMeasurements(face);
// Update posture analysis
analyzePosture(face);
// Update fit recommendations
updateFitRecommendations();
}
// Draw clothing items
drawClothingItems();
// Show measurements if enabled
if (showMeasurements) {
drawMeasurements();
}
// Show posture indicators if enabled
if (showPosture) {
drawPostureIndicators();
}
} catch (error) {
console.error('Error during detection:', error);
}
// Continue the loop
requestAnimationFrame(detect);
}
// Calculate body measurements based on face landmarks
function calculateMeasurements(face) {
// These are simplified calculations - in a real app you'd need more precise logic
const landmarks = face.scaledMesh;
// Estimate shoulder width (distance between ears * 2.5)
const leftEar = landmarks[234]; // Approximate left ear position
const rightEar = landmarks[454]; // Approximate right ear position
const earDistance = Math.sqrt(
Math.pow(rightEar[0] - leftEar[0], 2) +
Math.pow(rightEar[1] - leftEar[1], 2)
);
measurements.shoulderWidth = earDistance * 2.5;
measurements.chestWidth = earDistance * 2.8;
measurements.waistWidth = earDistance * 2.6;
measurements.hipWidth = earDistance * 2.9;
// Estimate torso length (chin to waist)
const chin = landmarks[152]; // Approximate chin position
const waistY = chin[1] + earDistance * 4;
measurements.torsoLength = waistY - chin[1];
// Update measurement display
shoulderWidthSpan.textContent = `${Math.round(measurements.shoulderWidth / PIXELS_PER_CM)} cm`;
chestWidthSpan.textContent = `${Math.round(measurements.chestWidth / PIXELS_PER_CM)} cm`;
waistWidthSpan.textContent = `${Math.round(measurements.waistWidth / PIXELS_PER_CM)} cm`;
hipWidthSpan.textContent = `${Math.round(measurements.hipWidth / PIXELS_PER_CM)} cm`;
torsoLengthSpan.textContent = `${Math.round(measurements.torsoLength / PIXELS_PER_CM)} cm`;
}
// Analyze posture based on face landmarks
function analyzePosture(face) {
const landmarks = face.scaledMesh;
// Get nose and chin positions
const noseTip = landmarks[1];
const chin = landmarks[152];
// Calculate angle from vertical
const dx = chin[0] - noseTip[0];
const dy = chin[1] - noseTip[1];
const angle = Math.atan2(dy, dx) * 180 / Math.PI;
const deviationFromVertical = Math.abs(90 - angle);
// Update posture feedback
if (deviationFromVertical > GOOD_POSTURE_THRESHOLD) {
postureFeedback.innerHTML = `
<p class="text-red-600 font-medium">Poor Posture Detected</p>
<p class="mt-1">Your head is tilted by ${Math.round(deviationFromVertical)}° from vertical.</p>
<p class="mt-1">Try to straighten your back and align your head with your spine.</p>
`;
} else {
postureFeedback.innerHTML = `
<p class="text-green-600 font-medium">Good Posture</p>
<p class="mt-1">Your head alignment looks good!</p>
`;
}
// Store posture data for drawing
postureData = {
noseTip,
chin,
deviation: deviationFromVertical
};
}
// Update fit recommendations based on measurements
function updateFitRecommendations() {
if (clothingItems.length === 0) return;
let recommendations = [];
clothingItems.forEach(item => {
// Simple fit check - in a real app this would be more sophisticated
const shoulderFit = item.width / measurements.shoulderWidth;
const lengthFit = item.height / measurements.torsoLength;
if (shoulderFit < 0.9 || lengthFit < 0.9) {
recommendations.push(`The ${item.type} might be too small. Consider sizing up.`);
} else if (shoulderFit > 1.1 || lengthFit > 1.1) {
recommendations.push(`The ${item.type} might be too large. Consider sizing down.`);
} else {
recommendations.push(`The ${item.type} appears to be a good fit!`);
}
});
fitRecommendation.innerHTML = recommendations.map(r => `<p class="mt-1">${r}</p>`).join('');
}
// Draw measurement lines on the canvas
function drawMeasurements() {
// Clear previous measurements
document.querySelectorAll('.measurement-line, .measurement-label').forEach(el => el.remove());
// Draw shoulder width
const shoulderY = canvas.height / 3;
const shoulderLine = document.createElement('div');
shoulderLine.className = 'measurement-line';
shoulderLine.style.width = `${measurements.shoulderWidth}px`;
shoulderLine.style.left = `${(canvas.width - measurements.shoulderWidth) / 2}px`;
shoulderLine.style.top = `${shoulderY}px`;
document.body.appendChild(shoulderLine);
const shoulderLabel = document.createElement('div');
shoulderLabel.className = 'measurement-label';
shoulderLabel.textContent = `Shoulder: ${Math.round(measurements.shoulderWidth / PIXELS_PER_CM)} cm`;
shoulderLabel.style.left = `${(canvas.width - measurements.shoulderWidth) / 2 + measurements.shoulderWidth / 2 - 50}px`;
shoulderLabel.style.top = `${shoulderY - 20}px`;
document.body.appendChild(shoulderLabel);
// Draw chest width
const chestY = shoulderY + measurements.torsoLength * 0.2;
const chestLine = document.createElement('div');
chestLine.className = 'measurement-line';
chestLine.style.width = `${measurements.chestWidth}px`;
chestLine.style.left = `${(canvas.width - measurements.chestWidth) / 2}px`;
chestLine.style.top = `${chestY}px`;
document.body.appendChild(chestLine);
const chestLabel = document.createElement('div');
chestLabel.className = 'measurement-label';
chestLabel.textContent = `Chest: ${Math.round(measurements.chestWidth / PIXELS_PER_CM)} cm`;
chestLabel.style.left = `${(canvas.width - measurements.chestWidth) / 2 + measurements.chestWidth / 2 - 50}px`;
chestLabel.style.top = `${chestY - 20}px`;
document.body.appendChild(chestLabel);
// Draw waist width
const waistY = shoulderY + measurements.torsoLength * 0.5;
const waistLine = document.createElement('div');
waistLine.className = 'measurement-line';
waistLine.style.width = `${measurements.waistWidth}px`;
waistLine.style.left = `${(canvas.width - measurements.waistWidth) / 2}px`;
waistLine.style.top = `${waistY}px`;
document.body.appendChild(waistLine);
const waistLabel = document.createElement('div');
waistLabel.className = 'measurement-label';
waistLabel.textContent = `Waist: ${Math.round(measurements.waistWidth / PIXELS_PER_CM)} cm`;
waistLabel.style.left = `${(canvas.width - measurements.waistWidth) / 2 + measurements.waistWidth / 2 - 50}px`;
waistLabel.style.top = `${waistY - 20}px`;
document.body.appendChild(waistLabel);
// Draw hip width
const hipY = shoulderY + measurements.torsoLength * 0.8;
const hipLine = document.createElement('div');
hipLine.className = 'measurement-line';
hipLine.style.width = `${measurements.hipWidth}px`;
hipLine.style.left = `${(canvas.width - measurements.hipWidth) / 2}px`;
hipLine.style.top = `${hipY}px`;
document.body.appendChild(hipLine);
const hipLabel = document.createElement('div');
hipLabel.className = 'measurement-label';
hipLabel.textContent = `Hip: ${Math.round(measurements.hipWidth / PIXELS_PER_CM)} cm`;
hipLabel.style.left = `${(canvas.width - measurements.hipWidth) / 2 + measurements.hipWidth / 2 - 50}px`;
hipLabel.style.top = `${hipY - 20}px`;
document.body.appendChild(hipLabel);
// Draw torso length
const torsoLine = document.createElement('div');
torsoLine.className = 'measurement-line';
torsoLine.style.width = `${measurements.torsoLength}px`;
torsoLine.style.left = `${canvas.width / 2}px`;
torsoLine.style.top = `${shoulderY}px`;
torsoLine.style.transform = `rotate(90deg)`;
document.body.appendChild(torsoLine);
const torsoLabel = document.createElement('div');
torsoLabel.className = 'measurement-label';
torsoLabel.textContent = `Torso: ${Math.round(measurements.torsoLength / PIXELS_PER_CM)} cm`;
torsoLabel.style.left = `${canvas.width / 2 + 20}px`;
torsoLabel.style.top = `${shoulderY + measurements.torsoLength / 2}px`;
document.body.appendChild(torsoLabel);
}
// Draw posture indicators
function drawPostureIndicators() {
// Clear previous indicators
document.querySelectorAll('.posture-indicator').forEach(el => el.remove());
if (!postureData) return;
// Draw head position indicator
const headIndicator = document.createElement('div');
headIndicator.className = `posture-indicator ${postureData.deviation > GOOD_POSTURE_THRESHOLD ? 'bad' : ''}`;
headIndicator.style.left = `${postureData.noseTip[0]}px`;
headIndicator.style.top = `${postureData.noseTip[1]}px`;
document.body.appendChild(headIndicator);
// Draw chin position indicator
const chinIndicator = document.createElement('div');
chinIndicator.className = `posture-indicator ${postureData.deviation > GOOD_POSTURE_THRESHOLD ? 'bad' : ''}`;
chinIndicator.style.left = `${postureData.chin[0]}px`;
chinIndicator.style.top = `${postureData.chin[1]}px`;
document.body.appendChild(chinIndicator);
}
// Add a new clothing item
function addClothingItem() {
const type = clothingTypeSelect.value;
const baseWidth = measurements.shoulderWidth * 1.2;
const baseHeight = measurements.torsoLength * 1.1;
// Adjust dimensions based on clothing type
let width, height;
switch (type) {
case 't-shirt':
case 'shirt':
width = baseWidth;
height = baseHeight * 0.8;
break;
case 'dress':
width = baseWidth * 0.9;
height = baseHeight * 1.5;
break;
case 'pants':
width = baseWidth * 0.8;
height = baseHeight * 0.9;
break;
case 'jacket':
width = baseWidth * 1.1;
height = baseHeight * 0.9;
break;
default:
width = baseWidth;
height = baseHeight;
}
const clothingItem = {
id: Date.now(),
type,
color: selectedColor,
pattern: selectedPattern,
x: (canvas.width - width) / 2,
y: canvas.height / 3 - height * 0.2,
width,
height,
originalWidth: width,
originalHeight: height,
size: 100
};
clothingItems.push(clothingItem);
selectClothingItem(clothingItem);
// Update fit recommendations
updateFitRecommendations();
}
// Draw all clothing items
function drawClothingItems() {
// Clear previous clothing items
document.querySelectorAll('.clothing-item').forEach(el => el.remove());
clothingItems.forEach(item => {
const clothingElement = document.createElement('div');
clothingElement.className = 'clothing-item';
clothingElement.dataset.id = item.id;
// Set position and size
clothingElement.style.left = `${item.x}px`;
clothingElement.style.top = `${item.y}px`;
clothingElement.style.width = `${item.width}px`;
clothingElement.style.height = `${item.height}px`;
// Set appearance based on color and pattern
let bgStyle = '';
if (item.pattern === 'solid') {
bgStyle = `background-color: ${getColorValue(item.color)};`;
} else if (item.pattern === 'checkered') {
bgStyle = `background-image: linear-gradient(45deg, #999 25%, transparent 25%, transparent 75%, #999 75%, #999),
linear-gradient(45deg, #999 25%, transparent 25%, transparent 75%, #999 75%, #999);
background-size: 10px 10px;
background-color: ${getColorValue(item.color)};`;
} else if (item.pattern === 'polka') {
bgStyle = `background-image: radial-gradient(circle, #999 1px, transparent 1px);
background-size: 10px 10px;
background-color: ${getColorValue(item.color)};`;
} else if (item.pattern === 'striped') {
bgStyle = `background-image: linear-gradient(0deg, #999, #999 50%, transparent 50%, transparent 100%);
background-size: 10px 10px;
background-color: ${getColorValue(item.color)};`;
}
clothingElement.style.cssText += bgStyle;
// Add selection class if this is the selected item
if (selectedClothingItem && selectedClothingItem.id === item.id) {
clothingElement.classList.add('selected');
}
// Add event listeners for selection and dragging
clothingElement.addEventListener('mousedown', (e) => {
selectClothingItem(item);
// Prepare for dragging
isDragging = true;
dragOffsetX = e.clientX - item.x;
dragOffsetY = e.clientY - item.y;
});
document.body.appendChild(clothingElement);
});
}
// Handle mouse move for dragging clothing items
document.addEventListener('mousemove', (e) => {
if (isDragging && selectedClothingItem) {
selectedClothingItem.x = e.clientX - dragOffsetX;
selectedClothingItem.y = e.clientY - dragOffsetY;
// Constrain to canvas
selectedClothingItem.x = Math.max(0, Math.min(canvas.width - selectedClothingItem.width, selectedClothingItem.x));
selectedClothingItem.y = Math.max(0, Math.min(canvas.height - selectedClothingItem.height, selectedClothingItem.y));
}
});
// Handle mouse up to stop dragging
document.addEventListener('mouseup', () => {
isDragging = false;
});
// Select a clothing item
function selectClothingItem(item) {
selectedClothingItem = item;
currentSize = item.size;
sizeValueSpan.textContent = `${currentSize}%`;
// Update UI to reflect selected item
drawClothingItems();
}
// Resize a clothing item
function resizeClothing(item, newSize) {
const scaleFactor = newSize / 100;
item.width = item.originalWidth * scaleFactor;
item.height = item.originalHeight * scaleFactor;
item.size = newSize;
// Keep the center position
const centerX = item.x + item.width / 2;
const centerY = item.y + item.height / 2;
item.x = centerX - item.width / 2;
item.y = centerY - item.height / 2;
}
// Reset all clothing items
function resetClothing() {
clothingItems = [];
selectedClothingItem = null;
drawClothingItems();
fitRecommendation.innerHTML = '<p>Add clothing to see fit recommendations based on your measurements.</p>';
}
// Take a photo of the current view
function takePhoto() {
// Create a temporary canvas with the current view
const tempCanvas = document.createElement('canvas');
tempCanvas.width = canvas.width;
tempCanvas.height = canvas.height;
const tempCtx = tempCanvas.getContext('2d');
// Draw the current frame
tempCtx.save();
tempCtx.scale(-1, 1);
tempCtx.drawImage(video, 0, 0, canvas.width * -1, canvas.height);
tempCtx.restore();
// Draw clothing items
clothingItems.forEach(item => {
tempCtx.fillStyle = getColorValue(item.color);
tempCtx.fillRect(item.x, item.y, item.width, item.height);
});
// Convert to data URL and download
const dataUrl = tempCanvas.toDataURL('image/png');
const link = document.createElement('a');
link.download = 'virtual-fitting-room.png';
link.href = dataUrl;
link.click();
}
// Helper function to get color value
function getColorValue(colorName) {
const colors = {
'red': '#ef4444',
'blue': '#3b82f6',
'green': '#10b981',
'black': '#000000',
'white': '#ffffff',
'yellow': '#f59e0b'
};
return colors[colorName] || '#3b82f6';
}
// Show error message
function showError(message) {
errorText.textContent = message;
errorMessage.classList.remove('hidden');
loadingIndicator.classList.add('hidden');
}
// Initialize the app when the page loads
window.addEventListener('DOMContentLoaded', init);
</script>
<p style="border-radius: 8px; text-align: center; font-size: 12px; color: #fff; margin-top: 16px;position: fixed; left: 8px; bottom: 8px; z-index: 10; background: rgba(0, 0, 0, 0.8); padding: 4px 8px;">Made with <img src="https://enzostvs-deepsite.hf.space/logo.svg" alt="DeepSite Logo" style="width: 16px; height: 16px; vertical-align: middle;display:inline-block;margin-right:3px;filter:brightness(0) invert(1);"><a href="https://enzostvs-deepsite.hf.space" style="color: #fff;text-decoration: underline;" target="_blank" >DeepSite</a> - 🧬 <a href="https://enzostvs-deepsite.hf.space?remix=viswanani/clone-app" style="color: #fff;text-decoration: underline;" target="_blank" >Remix</a></p></body>
</html> |