78 lines
2.6 KiB
TypeScript
78 lines
2.6 KiB
TypeScript
import { useCallback } from 'react';
|
|
import * as THREE from 'three';
|
|
|
|
export function useScreenshot() {
|
|
const takeScreenshot = useCallback(() => {
|
|
// 1. Find the Three.js Canvas
|
|
const canvas = document.querySelector('canvas');
|
|
if (!canvas) {
|
|
console.error('Canvas not found');
|
|
return;
|
|
}
|
|
|
|
try {
|
|
// 2. Create a temporary 2D canvas for compositing
|
|
const tempCanvas = document.createElement('canvas');
|
|
const width = canvas.width;
|
|
const height = canvas.height;
|
|
tempCanvas.width = width;
|
|
tempCanvas.height = height;
|
|
const ctx = tempCanvas.getContext('2d');
|
|
|
|
if (!ctx) return;
|
|
|
|
// 3. Draw the 3D scene onto the temp canvas
|
|
ctx.drawImage(canvas, 0, 0, width, height);
|
|
|
|
// 4. Get current camera info (approximate from scene if possible, or just current date)
|
|
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' });
|
|
|
|
// We can try to get camera position if we had access to the store,
|
|
// but for now let's stick to generic data or we can grab it from global window if exposed
|
|
// Better: just show the Date and App Name.
|
|
|
|
// 5. Add Overlay / Watermark
|
|
// Background gradient for text
|
|
const gradient = ctx.createLinearGradient(0, height - 100, 0, height);
|
|
gradient.addColorStop(0, 'transparent');
|
|
gradient.addColorStop(1, 'rgba(0,0,0,0.8)');
|
|
ctx.fillStyle = gradient;
|
|
ctx.fillRect(0, height - 150, width, 150);
|
|
|
|
// App Name
|
|
ctx.font = 'bold 32px sans-serif';
|
|
ctx.fillStyle = '#ffffff';
|
|
ctx.textAlign = 'right';
|
|
ctx.fillText('Cosmo', width - 40, height - 60);
|
|
|
|
ctx.font = '16px sans-serif';
|
|
ctx.fillStyle = '#aaaaaa';
|
|
ctx.fillText('DEEP SPACE EXPLORER', width - 40, height - 35);
|
|
|
|
// Date/Time
|
|
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);
|
|
|
|
// 6. Trigger Download
|
|
const dataUrl = tempCanvas.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 };
|
|
}
|