import { useCallback } from 'react'; import html2canvas from 'html2canvas'; export function useScreenshot() { const takeScreenshot = useCallback(async (username: string = 'Explorer') => { // 1. Find the container that includes both the Canvas and the HTML overlays (labels) const element = document.getElementById('cosmo-scene-container'); if (!element) { console.error('Scene container not found'); return; } try { // 2. Use html2canvas to capture the visual composite const canvas = await html2canvas(element, { backgroundColor: '#000000', useCORS: true, // Allow loading cross-origin images (textures) logging: false, scale: window.devicePixelRatio, // Capture at high resolution allowTaint: true, // Allow tainted canvas (might limit editing but okay for saving) ignoreElements: (_el) => { // Ignore elements that we don't want in the screenshot (if any end up inside) return false; } }); const ctx = canvas.getContext('2d'); if (!ctx) return; const width = canvas.width; const height = canvas.height; // 3. Add Overlay / Watermark const now = new Date(); const dateStr = now.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }); const timeStr = now.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' }); // Background gradient for text legibility const gradient = ctx.createLinearGradient(0, height - 150, 0, height); gradient.addColorStop(0, 'transparent'); gradient.addColorStop(1, 'rgba(0,0,0,0.9)'); ctx.fillStyle = gradient; ctx.fillRect(0, height - 200, width, 200); // Text Settings ctx.shadowColor = 'rgba(0,0,0,0.5)'; ctx.shadowBlur = 4; // User Name & App Name (Bottom Right) ctx.textAlign = 'right'; // Nickname@Cosmo ctx.font = 'bold 32px sans-serif'; ctx.fillStyle = '#ffffff'; ctx.fillText(`${username}@Cosmo`, width - 40, height - 60); // Subtitle ctx.font = '16px sans-serif'; ctx.fillStyle = '#aaaaaa'; ctx.fillText('DEEP SPACE EXPLORER', width - 40, height - 35); // Date/Time (Bottom Left) ctx.textAlign = 'left'; ctx.font = 'bold 24px monospace'; ctx.fillStyle = '#44aaff'; ctx.fillText(dateStr, 40, height - 60); ctx.font = '18px monospace'; ctx.fillStyle = '#cccccc'; ctx.fillText(timeStr, 40, height - 35); // 4. Trigger Download const dataUrl = canvas.toDataURL('image/png'); const link = document.createElement('a'); link.download = `Cosmo_Snapshot_${now.toISOString().slice(0,19).replace(/[:T]/g, '-')}.png`; link.href = dataUrl; link.click(); } catch (err) { console.error('Screenshot failed:', err); } }, []); return { takeScreenshot }; }