Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const jsnes = require('jsnes')
- const { createCanvas } = require('canvas');
- const { writeFileSync } = require('fs');
- const { requestAnimationFrame, cancelAnimationFrame } = require('request-animation-frame-polyfill')
- class NESScreenShooter {
- constructor() {
- this.SCREEN_WIDTH = 256;
- this.SCREEN_HEIGHT = 240;
- this.FRAMEBUFFER_SIZE = this.SCREEN_WIDTH * this.SCREEN_HEIGHT;
- this.canvas_ctx;
- this.image;
- this.framebuffer_u8;
- this.framebuffer_u32;
- this.id = 0;
- this.nes = new jsnes.NES({
- onFrame: (framebuffer_24) => {
- for (var i = 0; i < this.FRAMEBUFFER_SIZE; i++) this.framebuffer_u32[i] = 0xFF000000 | framebuffer_24[i];
- },
- });
- }
- requestAnimationFrame(fn) {
- this.id = requestAnimationFrame(fn)
- if (this.id > 5000) {
- cancelAnimationFrame(this.id)
- }
- }
- onAnimationFrame(time) {
- if(this.id % 60 === 0) this.saveImage(`image_${this.id}`)
- this.requestAnimationFrame(this.onAnimationFrame.bind(this))
- this.image.data.set(this.framebuffer_u8);
- this.canvas_ctx.putImageData(this.image, 0, 0);
- this.nes.frame();
- if (this.id > 60) {
- this.nes.buttonDown(1, jsnes.Controller.BUTTON_START)
- }
- if (this.id > 120) {
- this.nes.buttonDown(1, jsnes.Controller.BUTTON_B)
- this.nes.buttonDown(1, jsnes.Controller.BUTTON_A)
- }
- }
- nes_init() {
- const canvas = createCanvas(this.SCREEN_WIDTH, this.SCREEN_HEIGHT);
- this.canvas_ctx = canvas.getContext("2d");
- this.image = this.canvas_ctx.getImageData(0, 0, this.SCREEN_WIDTH, this.SCREEN_HEIGHT);
- this.canvas_ctx.fillStyle = "black";
- this.canvas_ctx.fillRect(0, 0, this.SCREEN_WIDTH, this.SCREEN_HEIGHT);
- // Allocate framebuffer array.
- var buffer = new ArrayBuffer(this.image.data.length);
- this.framebuffer_u8 = new Uint8ClampedArray(buffer);
- this.framebuffer_u32 = new Uint32Array(buffer);
- }
- nes_boot(rom_data) {
- this.nes.loadROM(rom_data);
- this.requestAnimationFrame(this.onAnimationFrame.bind(this));
- }
- nes_load_data(rom_data) {
- this.nes_init();
- this.nes_boot(rom_data);
- }
- saveImage(name) {
- const buffer = this.canvas_ctx.canvas.toBuffer('image/png')
- writeFileSync(`./images/${name}.png`, buffer);
- }
- }
- module.exports = NESScreenShooter;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement