Encodes an animated GIF by reading frames from a canvas.
A package to encode animated GIFs. Input frames are provided through a canvas, and the output is provided through a ReadStream
.
Install using npm:
npm i canvas-gif-encoder
const CanvasGifEncoder = require('canvas-gif-encoder');
const {createCanvas} = require('canvas');
const fs = require('fs');
const canvas = createCanvas(120, 120);
const ctx = canvas.getContext('2d');
const encoder = new CanvasGifEncoder(120, 120);
let stream = fs.createWriteStream('output.gif');
encoder.createReadStream().pipe(stream);
encoder.begin();
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, 120, 120);
encoder.addFrame(ctx, 250);
let colors = ['white', 'yellow', 'cyan', 'lime', 'magenta', 'red', 'blue'];
for (let i = 0; i < colors.length; ++i) {
ctx.fillStyle = colors[i];
ctx.fillRect(i / colors.length * 120, 0, 120 / colors.length, 120);
encoder.addFrame(ctx, 250);
}
encoder.end();
In order to write a valid GIF file, the workflow is as follows:
new
keywordcreateReadStream
begin
addFrame
end
Creates an encoder of the specified width and height.
Initializes the file by writing the header.
Writes a frame to the file.
Finalizes the file by writing the trailer.
Returns a read stream to which the other methods write.