Something like:
const fs = require('fs');const path = require('path');const Canvas = require('canvas');const GIFEncoder = require('gifencoder');const sharp = require('sharp');// Define the output path for the GIF.const outputPath = 'animated.gif';// Define the input PNG files.const inputFiles = ['image1.png', 'image2.png', 'image3.png'];// Create a GIFEncoder instance.const encoder = new GIFEncoder(500, 500); // Change the dimensions as needed.// Pipe the encoder output to a writable stream.const output = fs.createWriteStream(outputPath);encoder.pipe(output);// Start encoding.encoder.start();// Loop through the input files.inputFiles.forEach(async (file) => {// Convert each PNG to a raw RGBA buffer.const data = await sharp(file).raw().toBuffer();// Create a new Canvas instance.const canvas = Canvas.createCanvas(500, 500); // Change the dimensions as needed.const ctx = canvas.getContext('2d');// Create an ImageData instance from the raw RGBA buffer.const imageData = new Canvas.ImageData(new Uint8ClampedArray(data),canvas.width,canvas.height);// Put the ImageData instance into the canvas.ctx.putImageData(imageData, 0, 0);// Add the frame to the GIF.encoder.addFrame(ctx);});// Finish encoding.encoder.finish();
That would read each PNG file, converts it to a raw RGBA buffer using sharp, puts the image data into a canvas, and then adds the canvas as a frame to the GIF using gifencoder
.