93 lines
2.5 KiB
Plaintext
93 lines
2.5 KiB
Plaintext
// 尝试使用 Puppeteer 截图 Canvas(保留完整样式)
|
||
async tryNativeCanvasCapture(canvasFile: TFile): Promise<Uint8Array | null> {
|
||
let newWindowLeaf: any = null;
|
||
|
||
try {
|
||
console.log('🔍 Step 1: Opening canvas in new window...');
|
||
|
||
// 创建新窗口
|
||
newWindowLeaf = this.app.workspace.getLeaf('window');
|
||
if (!newWindowLeaf) {
|
||
console.log('❌ Failed to create new window');
|
||
return null;
|
||
}
|
||
|
||
console.log('✅ New window created, opening canvas file...');
|
||
await newWindowLeaf.openFile(canvasFile);
|
||
|
||
console.log('⏳ Step 2: Waiting for canvas render...');
|
||
// 等待 Canvas 渲染
|
||
await new Promise(resolve => setTimeout(resolve, 3000));
|
||
|
||
console.log('📸 Step 3: Capturing with Puppeteer...');
|
||
// @ts-ignore
|
||
const puppeteer = require('puppeteer');
|
||
|
||
// 启动 Puppeteer
|
||
const browser = await puppeteer.launch({
|
||
headless: true,
|
||
args: ['--no-sandbox', '--disable-setuid-sandbox']
|
||
});
|
||
|
||
try {
|
||
const page = await browser.newPage();
|
||
|
||
// 获取新窗口的 HTML 内容
|
||
const container = newWindowLeaf.containerEl;
|
||
const canvasWrapper = container.querySelector('.canvas-wrapper');
|
||
|
||
if (!canvasWrapper) {
|
||
console.log('❌ Could not find canvas wrapper');
|
||
return null;
|
||
}
|
||
|
||
// 获取完整的 HTML,包括所有样式
|
||
const htmlContent = canvasWrapper.outerHTML;
|
||
|
||
// 设置 HTML 内容
|
||
await page.setContent(htmlContent, {
|
||
waitUntil: 'networkidle0',
|
||
timeout: 10000
|
||
});
|
||
|
||
// 计算内容尺寸
|
||
const contentSize = this.getCanvasContentSize(canvasWrapper);
|
||
const viewportWidth = Math.ceil(contentSize.width);
|
||
const viewportHeight = Math.ceil(contentSize.height);
|
||
|
||
console.log(`📸 Screenshot size: ${viewportWidth}x${viewportHeight}`);
|
||
|
||
// 截图
|
||
const screenshot = await page.screenshot({
|
||
type: 'png',
|
||
clip: {
|
||
x: contentSize.offsetX,
|
||
y: contentSize.offsetY,
|
||
width: contentSize.width,
|
||
height: contentSize.height
|
||
}
|
||
});
|
||
|
||
console.log('✅ Capture successful!');
|
||
return new Uint8Array(screenshot);
|
||
|
||
} finally {
|
||
await browser.close();
|
||
}
|
||
|
||
} catch (error) {
|
||
console.error('❌ Puppeteer capture failed:', error);
|
||
return null;
|
||
} finally {
|
||
// 关闭新窗口
|
||
if (newWindowLeaf) {
|
||
try {
|
||
newWindowLeaf.detach();
|
||
console.log('🧹 Closed new window');
|
||
} catch (e) {
|
||
console.log('⚠️ Could not close new window:', e);
|
||
}
|
||
}
|
||
}
|
||
}
|