1
0

screenshot.mjs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #!/usr/bin/env node
  2. /**
  3. * Darwin Skill - 高清截图脚本
  4. *
  5. * 用法: node scripts/screenshot.mjs [html文件路径] [输出png路径]
  6. *
  7. * 特性:
  8. * - 2x deviceScaleFactor,输出高清图
  9. * - 只截 .card 元素,无多余背景
  10. * - 等待字体加载完成
  11. * - 截完自动用 open 命令打开图片
  12. */
  13. import { createRequire } from 'module';
  14. const require = createRequire(import.meta.url);
  15. // 使用全局安装的 playwright-core
  16. const pw = require('/Users/alchain/.npm-global/lib/node_modules/playwright/node_modules/playwright-core');
  17. const htmlPath = process.argv[2] || new URL('../templates/result-card.html', import.meta.url).pathname;
  18. const outputPath = process.argv[3] || new URL('../templates/result-card.png', import.meta.url).pathname;
  19. async function screenshot() {
  20. const browser = await pw.chromium.launch();
  21. try {
  22. const context = await browser.newContext({
  23. viewport: { width: 920, height: 1600 },
  24. deviceScaleFactor: 2,
  25. });
  26. const page = await context.newPage();
  27. await page.goto(`file://${htmlPath}`, { waitUntil: 'networkidle' });
  28. // 等待字体加载
  29. await page.evaluate(() => document.fonts.ready);
  30. // 额外等待确保渲染完成
  31. await page.waitForTimeout(2000);
  32. // 只截 .card 元素
  33. const card = await page.locator('.card');
  34. await card.screenshot({
  35. path: outputPath,
  36. type: 'png',
  37. });
  38. console.log(`截图完成: ${outputPath}`);
  39. // 获取图片尺寸信息
  40. const box = await card.boundingBox();
  41. console.log(`卡片尺寸: ${Math.round(box.width)}x${Math.round(box.height)}px (CSS)`);
  42. console.log(`输出尺寸: ${Math.round(box.width * 2)}x${Math.round(box.height * 2)}px (2x高清)`);
  43. } finally {
  44. await browser.close();
  45. }
  46. // 自动打开图片
  47. const { execSync } = require('child_process');
  48. execSync(`open "${outputPath}"`);
  49. }
  50. screenshot().catch(err => {
  51. console.error('截图失败:', err.message);
  52. process.exit(1);
  53. });