Files
photobooth/src/views/ShootingView.vue

681 lines
20 KiB
Vue

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const videoRef = ref<HTMLVideoElement>()
const canvasRef = ref<HTMLCanvasElement>()
const photos = ref<string[]>([])
const currentPhotoIndex = ref(0)
const isCapturing = ref(false)
const isAutoCapturing = ref(false)
const countdown = ref(0)
const stream = ref<MediaStream | null>(null)
const totalPhotos = 4
onMounted(async () => {
await startCamera()
})
onUnmounted(() => {
stopCamera()
})
const startCamera = async () => {
try {
const constraints = {
video: {
facingMode: 'user',
width: { ideal: 720 },
height: { ideal: 960 }
}
}
stream.value = await navigator.mediaDevices.getUserMedia(constraints)
if (videoRef.value) {
videoRef.value.srcObject = stream.value
}
} catch (error) {
console.error('Error accessing camera:', error)
alert('ไม่สามารถเข้าถึงกล้องได้ กรุณาตรวจสอบสิทธิ์การใช้งานกล้อง')
}
}
const stopCamera = () => {
if (stream.value) {
stream.value.getTracks().forEach(track => track.stop())
stream.value = null
}
}
const applyFilmEffect = (context: CanvasRenderingContext2D, width: number, height: number, volume: number = 5) => {
const imageData = context.getImageData(0, 0, width, height);
const data = imageData.data;
// 1. แปลง Volume (1-10) เป็นค่าที่ใช้งานได้จริง
// contrast: ยิ่งเยอะ ภาพยิ่งคมเข้ม (แนะนำช่วง 0 ถึง 50)
const contrast = (volume / 10) * 50;
const contrastFactor = (259 * (contrast + 255)) / (255 * (259 - contrast));
// tint: ปรับโทนสี (Film มักจะอมแดง/เขียว ลดฟ้า)
const redBoost = volume * 2; // เพิ่มแดงนิดหน่อย
const greenBoost = volume * 1; // เพิ่มเขียวจางๆ
const blueCut = volume * 3; // ลดฟ้าลงเพื่อให้ภาพดูอุ่น (Warm tone)
// grain: ความแรงของเม็ดเกรน
const grainStrength = volume * 1.5;
for (let i = 0; i < data.length; i += 4) {
let r = data[i]!;
let g = data[i + 1]!;
let b = data[i + 2]!;
// --- STEP 1: Apply Contrast (ทำให้ภาพไม่แบน) ---
// สูตร Contrast มาตรฐาน
r = contrastFactor * (r - 128) + 128;
g = contrastFactor * (g - 128) + 128;
b = contrastFactor * (b - 128) + 128;
// --- STEP 2: Color Grading (ปรับโทนฟิล์ม) ---
// ฟิล์ม Kodak/Fuji มักจะไม่ใช่ Sepia ล้วน แต่คือการจูน Channel
r += redBoost;
g += greenBoost;
b -= blueCut;
// --- STEP 3: Add Grain (เม็ดเกรน) ---
// ใช้เทคนิคสุ่มทั้งบวกและลบ เพื่อไม่ให้ความสว่างรวมเพี้ยน
const grain = (Math.random() - 0.5) * grainStrength;
// ผสมเกรนลงไป
r += grain;
g += grain;
b += grain;
// --- STEP 4: Clamp values (กันค่าเกิน 0-255) ---
// ถ้าไม่กันค่า จะเกิดจุดสีประหลาดๆ เมื่อค่าทะลุ 255 หรือต่ำกว่า 0
data[i] = Math.max(0, Math.min(255, r));
data[i + 1] = Math.max(0, Math.min(255, g));
data[i + 2] = Math.max(0, Math.min(255, b));
}
context.putImageData(imageData, 0, 0);
// --- STEP 5: (Optional) Add Vignette (ขอบมืด) ---
// การวาด Gradient ทับ เร็วกว่าและเนียนกว่าการคำนวณทีละ pixel
if (volume > 2) {
addVignette(context, width, height, volume);
}
};
// ฟังก์ชันเสริมสำหรับทำขอบมืด (Vignette)
const addVignette = (ctx: CanvasRenderingContext2D, w: number, h: number, strength: number) => {
const opacity = (strength / 10) * 0.6; // สูงสุดที่ 0.6 opacity
const radius = Math.max(w, h) * 0.8;
// สร้าง Gradient วงกลมจากตรงกลาง
const gradient = ctx.createRadialGradient(w/2, h/2, 0, w/2, h/2, radius);
gradient.addColorStop(0.5, "rgba(0,0,0,0)"); // ตรงกลางใส
gradient.addColorStop(1, `rgba(0,0,0,${opacity})`); // ขอบดำ
ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, w, h);
};
const drawDateStamp = (context: CanvasRenderingContext2D, width: number, height: number) => {
const now = new Date();
// จัดรูปแบบวันที่แบบกล้องฟิล์ม (เช่น '98 1 25 หรือ 25 1 '98)
// ปีเอาแค่ 2 หลักท้าย
const year = now.getFullYear().toString().slice(-2);
const month = (now.getMonth() + 1).toString().padStart(2, '0'); // หรือจะใช้เลขเดียวแบบกล้องเก่าๆ ก็ได้
const day = now.getDate().toString().padStart(2, '0');
const dateString = `'${year} ${month} ${day}`; // รูปแบบ: '24 01 18
// ตั้งค่า Font (Digital-like)
// แนะนำให้หา Font ชื่อ 'Digital-7' หรือ 'DS-Digital' มาลงจะเหมือนมาก
// แต่ถ้าไม่มี ใช้ Arial หรือ Courier New ก็พอไหวครับ
const fontSize = height * 0.05; // ขนาด 5% ของความสูงภาพ
context.font = `bold ${fontSize}px "Courier New", monospace`;
// สีส้มอมแดง (Classic Date Stamp Color)
context.fillStyle = "#ff5e3a";
// เพิ่มเงาเรืองแสงนิดๆ ให้ดูเหมือนไฟ LED ที่ยิงลงฟิล์ม
context.shadowColor = "#ff0000";
context.shadowBlur = 10;
// ตำแหน่ง: มุมขวาล่าง
const paddingX = width * 0.05;
const paddingY = height * 0.03;
const x = width - context.measureText(dateString).width - paddingX;
const y = height - paddingY;
context.fillText(dateString, x, y);
// Reset shadow เพื่อไม่ให้กวนการวาดส่วนอื่น
context.shadowBlur = 0;
};
const captureSinglePhoto = () => {
if (!videoRef.value || !canvasRef.value || isCapturing.value) return
isCapturing.value = true
const video = videoRef.value
const canvas = canvasRef.value
const context = canvas.getContext('2d')
if (!context) return
const videoWidth = video.videoWidth
const videoHeight = video.videoHeight
// คำนวณขนาดสำหรับ 3:4 aspect ratio
const targetAspectRatio = 3/4 // width:height = 3:4
let cropWidth, cropHeight, cropX, cropY
if (videoWidth / videoHeight > targetAspectRatio) {
// ภาพกว้างกว่าที่ต้องการ - ครอบด้านข้าง
cropHeight = videoHeight
cropWidth = videoHeight * targetAspectRatio
cropX = (videoWidth - cropWidth) / 2
cropY = 0
} else {
// ภาพสูงกว่าที่ต้องการ - ครอบด้านบน/ล่าง
cropWidth = videoWidth
cropHeight = videoWidth / targetAspectRatio
cropX = 0
cropY = (videoHeight - cropHeight) / 2
}
// ตั้งค่าขนาด canvas เป็น 3:4 (360x480) - ลดขนาดเพื่อป้องกัน localStorage quota exceeded
const finalWidth = 360
const finalHeight = 480
canvas.width = finalWidth
canvas.height = finalHeight
// วาดภาพที่ครอบแล้วไปยัง canvas
context.drawImage(
video,
cropX, cropY, cropWidth, cropHeight, // ตำแหน่งและขนาดที่ครอบจาก video
0, 0, finalWidth, finalHeight // ตำแหน่งและขนาดใน canvas
)
// Apply film effect with default volume
applyFilmEffect(context, finalWidth, finalHeight, 5);
drawDateStamp(context, finalWidth, finalHeight);
// แปลงเป็น base64 ด้วย quality 0.7 เพื่อลดขนาด
const photoDataUrl = canvas.toDataURL('image/jpeg', 0.7)
photos.value.push(photoDataUrl)
currentPhotoIndex.value++
setTimeout(() => {
isCapturing.value = false
}, 200)
}
const startAutoCapture = () => {
if (isAutoCapturing.value) return
isAutoCapturing.value = true
photos.value = []
currentPhotoIndex.value = 0
const captureNextPhoto = () => {
if (currentPhotoIndex.value >= totalPhotos) {
// ถ่ายครบแล้ว ไปหน้าถัดไป
isAutoCapturing.value = false
proceedToNext()
return
}
// นับถอยหลังสำหรับรูปปัจจุบัน
countdown.value = 3
const countdownInterval = setInterval(() => {
countdown.value--
if (countdown.value <= 0) {
clearInterval(countdownInterval)
countdown.value = 0
// ถ่ายภาพ
captureSinglePhoto()
// ถ่ายรูปต่อไปหลังจาก delay สั้นๆ
setTimeout(() => {
captureNextPhoto()
}, 500)
}
}, 1000)
}
// เริ่มถ่ายรูปแรก
captureNextPhoto()
}
const proceedToNext = () => {
try {
// เคลียร์ cached images ที่เก่าออกก่อนเพื่อให้มีพื้นที่
const keysToRemove = []
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i)
if (key && (key.startsWith('photobooth-1x4-') || key.startsWith('photobooth-2x2-'))) {
keysToRemove.push(key)
}
}
keysToRemove.forEach(key => {
if (key !== null) {
localStorage.removeItem(key)
}
})
// เก็บรูปภาพไว้ใน localStorage
localStorage.setItem('photobooth-photos', JSON.stringify(photos.value))
stopCamera()
router.push('/printstep')
} catch (error) {
if (error instanceof DOMException && error.name === 'QuotaExceededError') {
alert('รูปภาพมีขนาดใหญ่เกินไป กรุณาลองใหม่อีกครั้งหรือใช้รูปภาพขนาดเล็กลง')
console.error('localStorage quota exceeded:', error)
} else {
console.error('Error saving photos:', error)
alert('เกิดข้อผิดพลาดในการบันทึกภาพ')
}
}
}
const goBack = () => {
stopCamera()
router.push('/selectsource')
}
const retakePhoto = () => {
photos.value = []
currentPhotoIndex.value = 0
isAutoCapturing.value = false
countdown.value = 0
}
</script>
<template>
<div class="shooting-container">
<!-- <header class="header">
<button @click="goBack" class="back-button"> กล</button>
<h1>ายภาพ</h1>
<span class="photo-counter">{{ currentPhotoIndex }}/{{ totalPhotos }}</span>
</header> -->
<section class="camera-section">
<div class="camera-container">
<video
ref="videoRef"
autoplay
playsinline
muted
class="camera-video"
></video>
<canvas ref="canvasRef" class="hidden-canvas"></canvas>
<div class="camera-overlay">
<div class="capture-guide">
<div class="guide-frame"></div>
</div>
<!-- Countdown overlay -->
<div v-if="countdown > 0" class="countdown-overlay">
<div class="countdown-info">ปท {{ currentPhotoIndex + 1 }}</div>
<div class="countdown-number">{{ countdown }}</div>
</div>
</div>
</div>
<div class="controls">
<button
@click="startAutoCapture"
:disabled="isAutoCapturing || currentPhotoIndex >= totalPhotos"
class="capture-button"
:class="{ capturing: isAutoCapturing }"
>
<span v-if="!isAutoCapturing && currentPhotoIndex === 0">📷 ถ่ายทั้ง 4 รูป</span>
<span v-else-if="isAutoCapturing">กำลังถ่าย...</span>
<span v-else>ถ่ายเสร็จแล้ว</span>
</button>
<button
v-if="currentPhotoIndex > 0 && !isAutoCapturing"
@click="retakePhoto"
class="retake-button"
>
ายใหมงหมด
</button>
</div>
</section>
<section class="preview-section" v-if="photos.length > 0">
<h3>ภาพทายแล</h3>
<div class="photo-preview">
<div
v-for="(photo, index) in photos"
:key="index"
class="preview-item"
>
<img :src="photo" :alt="`Photo ${index + 1}`" />
<span class="photo-number">{{ index + 1 }}</span>
</div>
</div>
</section>
</div>
</template>
<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Crete+Round&family=Old+Standard+TT&display=swap');
.shooting-container {
min-height: 100vh;
padding: 1.5rem; /* Adjusted padding */
background: #fdfaf6; /* Dark brown, vintage background */
color: #fdfaf6; /* Light vintage paper color for text */
font-family: 'Old Standard TT', serif;
display: flex;
flex-direction: column;
}
.header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 2rem;
background: #5d4037; /* Darker vintage tone for header */
padding: 0.8rem 1.2rem;
border-radius: 8px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
border: 1px solid #4e342e;
}
.back-button {
background: #8d6e63; /* Vintage brown */
color: #fdfaf6;
border: 1px solid #795548;
padding: 0.4rem 0.8rem;
border-radius: 5px;
cursor: pointer;
font-size: 1rem;
font-weight: bold;
box-shadow: 1px 1px 3px rgba(0,0,0,0.1);
transition: background 0.2s ease, transform 0.2s ease;
}
.back-button:hover {
background: #795548;
transform: translateY(-1px);
}
.header h1 {
margin: 0;
font-size: 2rem;
font-family: 'Crete Round', serif;
color: #fdfaf6;
text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
}
.photo-counter {
background: #a1887f; /* Muted brown */
padding: 0.5rem 1rem;
border-radius: 20px;
font-weight: bold;
color: #fdfaf6;
border: 1px solid #8d6e63;
}
.camera-section {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
gap: 2rem;
}
.camera-container {
position: relative;
width: 100%;
max-width: 400px;
aspect-ratio: 3/4;
border-radius: 12px; /* Slightly softer radius */
overflow: hidden;
box-shadow: 0 5px 20px rgba(0,0,0,0.4); /* Darker, more prominent shadow */
border: 4px solid #4e342e; /* Frame-like border */
background: #2b1c18; /* Darker background inside frame */
}
.camera-video {
width: 100%;
height: 100%;
object-fit: cover;
}
.hidden-canvas {
display: none;
}
.camera-overlay {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
pointer-events: none;
}
.countdown-overlay {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(43, 28, 24, 0.85); /* Darker, vintage transparent overlay */
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
animation: none; /* Removed fade animation for countdown */
}
.countdown-info {
font-size: 1.5rem;
font-weight: bold;
color: #fdfaf6; /* Light text */
margin-bottom: 1rem;
text-shadow: 1px 1px 2px rgba(0,0,0,0.5);
font-family: 'Crete Round', serif;
}
.countdown-number {
font-size: 7rem; /* Slightly smaller number */
font-weight: bold;
color: #ff5e3a; /* Vintage orange-red for countdown */
text-shadow: 2px 2px 5px rgba(255, 94, 58, 0.7); /* Glowing effect */
animation: countdownPulse 1s ease-in-out;
font-family: 'Digital-7', monospace; /* Ideal for digital clock look, otherwise Courier New */
}
.capture-guide {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
.guide-frame {
width: 80%;
height: 80%;
border: 2px dashed rgba(253,250,246,0.5); /* Dashed light border for guide */
border-radius: 8px;
}
.controls {
display: flex;
flex-direction: column;
align-items: center;
gap: 1rem;
}
.capture-button {
background: #a1887f; /* Vintage brown */
color: #fdfaf6;
border: 2px solid #8d6e63;
padding: 1rem 2.5rem;
font-size: 1.3rem;
font-weight: bold;
border-radius: 8px; /* Softer border-radius */
cursor: pointer;
transition: all 0.3s ease;
min-width: 220px;
box-shadow: 0 4px 10px rgba(0,0,0,0.2);
font-family: 'Crete Round', serif;
text-transform: uppercase;
letter-spacing: 1px;
}
.capture-button:hover:not(:disabled) {
background: #8d6e63;
transform: translateY(-2px);
box-shadow: 0 6px 15px rgba(0,0,0,0.3);
}
.capture-button:disabled {
opacity: 0.5;
cursor: not-allowed;
background: #a1887f; /* Keep base color */
border-color: #8d6e63;
box-shadow: none;
}
.capturing {
animation: pulse 0.5s ease-in-out infinite alternate; /* Keep pulse but make it subtle */
}
.retake-button {
background: #6d4c41; /* Muted brown */
color: #fdfaf6;
border: 1px solid #5d4037;
padding: 0.7rem 1.4rem;
border-radius: 5px;
cursor: pointer;
transition: all 0.3s ease;
font-weight: bold;
font-family: 'Old Standard TT', serif;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
.retake-button:hover {
background: #5d4037;
transform: translateY(-1px);
}
.preview-section {
margin-top: 2rem;
text-align: center;
background: #2b1c18; /* Dark background for preview section */
padding: 1.5rem;
border-radius: 10px;
box-shadow: inset 0 0 10px rgba(0,0,0,0.3);
}
.preview-section h3 {
margin-bottom: 1rem;
color: #fdfaf6;
font-family: 'Crete Round', serif;
text-shadow: 1px 1px 2px rgba(0,0,0,0.05);
}
.photo-preview {
display: flex;
gap: 1rem;
justify-content: center;
flex-wrap: wrap;
}
.preview-item {
position: relative;
width: 70px; /* Slightly larger preview items */
aspect-ratio: 3/4;
border-radius: 4px; /* Sharper corners for printed photo look */
overflow: hidden;
border: 2px solid #bcaaa4; /* Frame-like border for previews */
box-shadow: 0 2px 5px rgba(0,0,0,0.15); /* Subtle shadow for depth */
}
.preview-item img {
width: 100%;
height: 100%;
object-fit: cover;
filter: sepia(0.1) brightness(0.95); /* Subtle sepia and brightness for vintage feel */
}
.photo-number {
position: absolute;
top: 4px;
right: 4px;
background: #8d6e63; /* Vintage brown for number badge */
color: #fdfaf6;
width: 22px; /* Slightly larger badge */
height: 22px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-size: 0.8rem;
font-weight: bold;
box-shadow: 1px 1px 3px rgba(0,0,0,0.2);
}
@keyframes pulse {
0% { transform: scale(1); box-shadow: 0 4px 10px rgba(0,0,0,0.2); }
50% { transform: scale(1.02); box-shadow: 0 6px 15px rgba(0,0,0,0.3); }
100% { transform: scale(1); box-shadow: 0 4px 10px rgba(0,0,0,0.2); }
}
@keyframes countdownPulse {
0% { transform: scale(0.8); opacity: 0.5; }
50% { transform: scale(1.1); opacity: 1; }
100% { transform: scale(1); opacity: 0.8; }
}
@media (max-width: 768px) {
.camera-container {
max-width: 100%;
}
.photo-preview {
gap: 0.5rem;
}
.preview-item {
width: 60px;
height: auto; /* Adjust height automatically with aspect-ratio */
}
.header h1 {
font-size: 1.8rem;
}
.countdown-number {
font-size: 5rem;
}
.capture-button {
font-size: 1.1rem;
padding: 0.8rem 2rem;
min-width: 180px;
}
.retake-button {
font-size: 0.9rem;
padding: 0.6rem 1.2rem;
}
}
</style>