export-frames.js 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. #!/usr/bin/env node
  2. /**
  3. * p5.js Skill — Headless Frame Export
  4. *
  5. * Captures frames from a p5.js sketch using Puppeteer (headless Chrome).
  6. * Uses noLoop() + redraw() for DETERMINISTIC frame-by-frame control.
  7. *
  8. * IMPORTANT: Your sketch must call noLoop() in setup() and set
  9. * window._p5Ready = true when initialized. This script calls redraw()
  10. * for each frame capture, ensuring exact 1:1 correspondence between
  11. * frameCount and captured frames.
  12. *
  13. * If the sketch does NOT set window._p5Ready, the script falls back to
  14. * a timed capture mode (less precise, may drop/duplicate frames).
  15. *
  16. * Usage:
  17. * node export-frames.js sketch.html [options]
  18. *
  19. * Options:
  20. * --output <dir> Output directory (default: ./frames)
  21. * --width <px> Canvas width (default: 1920)
  22. * --height <px> Canvas height (default: 1080)
  23. * --frames <n> Number of frames to capture (default: 1)
  24. * --fps <n> Target FPS for timed fallback mode (default: 30)
  25. * --wait <ms> Wait before first capture (default: 2000)
  26. * --selector <sel> Canvas CSS selector (default: canvas)
  27. *
  28. * Examples:
  29. * node export-frames.js sketch.html --frames 1 # single PNG
  30. * node export-frames.js sketch.html --frames 300 --fps 30 # 10s at 30fps
  31. * node export-frames.js sketch.html --width 3840 --height 2160 # 4K still
  32. *
  33. * Sketch template for deterministic capture:
  34. * function setup() {
  35. * createCanvas(1920, 1080);
  36. * pixelDensity(1);
  37. * noLoop(); // REQUIRED for deterministic capture
  38. * window._p5Ready = true; // REQUIRED to signal readiness
  39. * }
  40. * function draw() { ... }
  41. */
  42. const puppeteer = require('puppeteer');
  43. const path = require('path');
  44. const fs = require('fs');
  45. // Parse CLI arguments
  46. function parseArgs() {
  47. const args = process.argv.slice(2);
  48. const opts = {
  49. input: null,
  50. output: './frames',
  51. width: 1920,
  52. height: 1080,
  53. frames: 1,
  54. fps: 30,
  55. wait: 2000,
  56. selector: 'canvas',
  57. };
  58. for (let i = 0; i < args.length; i++) {
  59. if (args[i].startsWith('--')) {
  60. const key = args[i].slice(2);
  61. const val = args[i + 1];
  62. if (key in opts && val !== undefined) {
  63. opts[key] = isNaN(Number(val)) ? val : Number(val);
  64. i++;
  65. }
  66. } else if (!opts.input) {
  67. opts.input = args[i];
  68. }
  69. }
  70. if (!opts.input) {
  71. console.error('Usage: node export-frames.js <sketch.html> [options]');
  72. process.exit(1);
  73. }
  74. return opts;
  75. }
  76. async function main() {
  77. const opts = parseArgs();
  78. const inputPath = path.resolve(opts.input);
  79. if (!fs.existsSync(inputPath)) {
  80. console.error(`File not found: ${inputPath}`);
  81. process.exit(1);
  82. }
  83. // Create output directory
  84. fs.mkdirSync(opts.output, { recursive: true });
  85. console.log(`Capturing ${opts.frames} frame(s) from ${opts.input}`);
  86. console.log(`Resolution: ${opts.width}x${opts.height}`);
  87. console.log(`Output: ${opts.output}/`);
  88. const browser = await puppeteer.launch({
  89. headless: 'new',
  90. args: [
  91. '--no-sandbox',
  92. '--disable-setuid-sandbox',
  93. '--disable-gpu',
  94. '--disable-dev-shm-usage',
  95. '--disable-web-security',
  96. '--allow-file-access-from-files',
  97. ],
  98. });
  99. const page = await browser.newPage();
  100. await page.setViewport({
  101. width: opts.width,
  102. height: opts.height,
  103. deviceScaleFactor: 1,
  104. });
  105. // Navigate to sketch
  106. const fileUrl = `file://${inputPath}`;
  107. await page.goto(fileUrl, { waitUntil: 'networkidle0', timeout: 30000 });
  108. // Wait for canvas to appear
  109. await page.waitForSelector(opts.selector, { timeout: 10000 });
  110. // Detect capture mode: deterministic (noLoop+redraw) vs timed (fallback)
  111. let deterministic = false;
  112. try {
  113. await page.waitForFunction('window._p5Ready === true', { timeout: 5000 });
  114. deterministic = true;
  115. console.log(`Mode: deterministic (noLoop + redraw)`);
  116. } catch {
  117. console.log(`Mode: timed fallback (sketch does not set window._p5Ready)`);
  118. console.log(` For frame-perfect capture, add noLoop() and window._p5Ready=true to setup()`);
  119. await new Promise(r => setTimeout(r, opts.wait));
  120. }
  121. const startTime = Date.now();
  122. for (let i = 0; i < opts.frames; i++) {
  123. if (deterministic) {
  124. // Advance exactly one frame
  125. await page.evaluate(() => { redraw(); });
  126. // Brief settle time for render to complete
  127. await new Promise(r => setTimeout(r, 20));
  128. }
  129. const frameName = `frame-${String(i).padStart(4, '0')}.png`;
  130. const framePath = path.join(opts.output, frameName);
  131. // Capture the canvas element
  132. const canvas = await page.$(opts.selector);
  133. if (!canvas) {
  134. console.error('Canvas element not found');
  135. break;
  136. }
  137. await canvas.screenshot({ path: framePath, type: 'png' });
  138. // Progress
  139. if (i % 30 === 0 || i === opts.frames - 1) {
  140. const pct = ((i + 1) / opts.frames * 100).toFixed(1);
  141. const elapsed = ((Date.now() - startTime) / 1000).toFixed(1);
  142. process.stdout.write(`\r Frame ${i + 1}/${opts.frames} (${pct}%) — ${elapsed}s`);
  143. }
  144. // In timed mode, wait between frames
  145. if (!deterministic && i < opts.frames - 1) {
  146. await new Promise(r => setTimeout(r, 1000 / opts.fps));
  147. }
  148. }
  149. console.log('\n Done.');
  150. await browser.close();
  151. }
  152. main().catch(err => {
  153. console.error('Error:', err.message);
  154. process.exit(1);
  155. });