项目作者: bcafuk

项目描述 :
Encodes an animated GIF by reading frames from a canvas.
高级语言: JavaScript
项目地址: git://github.com/bcafuk/canvas-gif-encoder.git
创建时间: 2019-05-14T19:34:32Z
项目社区:https://github.com/bcafuk/canvas-gif-encoder

开源协议:Other

下载


canvas-gif-encoder

npm

A package to encode animated GIFs. Input frames are provided through a canvas, and the output is provided through a ReadStream.

Installation

Install using npm:

  1. npm i canvas-gif-encoder

Example

  1. const CanvasGifEncoder = require('canvas-gif-encoder');
  2. const {createCanvas} = require('canvas');
  3. const fs = require('fs');
  4. const canvas = createCanvas(120, 120);
  5. const ctx = canvas.getContext('2d');
  6. const encoder = new CanvasGifEncoder(120, 120);
  7. let stream = fs.createWriteStream('output.gif');
  8. encoder.createReadStream().pipe(stream);
  9. encoder.begin();
  10. ctx.fillStyle = 'black';
  11. ctx.fillRect(0, 0, 120, 120);
  12. encoder.addFrame(ctx, 250);
  13. let colors = ['white', 'yellow', 'cyan', 'lime', 'magenta', 'red', 'blue'];
  14. for (let i = 0; i < colors.length; ++i) {
  15. ctx.fillStyle = colors[i];
  16. ctx.fillRect(i / colors.length * 120, 0, 120 / colors.length, 120);
  17. encoder.addFrame(ctx, 250);
  18. }
  19. encoder.end();

Documentation

In order to write a valid GIF file, the workflow is as follows:

  1. Construct an encoder using the new keyword
  2. Open a read stream using createReadStream
  3. Begin a file with begin
  4. Draw the desired frame on a canvas
  5. Create a frame from the canvas with addFrame
  6. Repeat steps 4 and 5 until you have all the frames you want
  7. End the file using end

constructor(width, height, options)

  • width: The width of the GIF in pixels, in the range [1, 65535].
  • height: The height of the GIF in pixels, in the range [1, 65535].
  • options: (optional) Currently unused.

Creates an encoder of the specified width and height.

begin()

Initializes the file by writing the header.

addFrame(context, delay)

  • context: The canvas context from which the frame is constructed.
  • delay: The length of the frame being added in milliseconds, in the range [0, 655350].

Writes a frame to the file.

end()

Finalizes the file by writing the trailer.

createReadStream()

Returns a read stream to which the other methods write.