Search code examples
javascriptnode.jsgifanimated-gif

Node - Why is my gif so slow when using GifEncoder


i want to render a Gif with GifEncoder (older version), but unfortunately the gif output is much slower or so to say, it lags. This is my code:

import GIFEncoder from "gif-encoder-2";
import fs from "fs";

import pkg from "canvas";
const { createCanvas } = pkg;

let frame = 0;
const size = 200;
const fr = 60; //starting FPS
const encoder = new GIFEncoder(size, size);

encoder
  .createReadStream()
  .pipe(fs.createWriteStream("my.gif"));

encoder.start();
encoder.setRepeat(0); // 0 for repeat, -1 for no-repeat
encoder.setDelay(0); // frame delay in ms
encoder.setQuality(10); // image quality. 10 is default.

var canvas = createCanvas(size, size),
  cw = canvas.width,
  ch = canvas.height,
  cx = null,
  fps = 60,
  bX = 30,
  bY = 30,
  mX = 10,
  mY = 20,
  interval = null;

function gameLoop() {
  cx.clearRect(0, 0, cw, cw);

  cx.beginPath();
  cx.fillStyle = "red";
  cx.arc(bX, bY, 20, 0, Math.PI * 360);
  cx.fill();
  if (bX >= cw || bX <= 0) {
    mX *= -1;
  }
  if (bY >= ch || bY <= 0) {
    mY *= -1;
  }

  bX += mX;
  bY += mY;

  encoder.addFrame(cx);

  console.log(frame);

  if (frame > 60) {
    clearInterval(interval);
    encoder.finish();
  }

  ++frame;
}

if (typeof canvas.getContext !== undefined) {
  cx = canvas.getContext("2d");

  interval = setInterval(gameLoop, 1000 / fps);
}

This is the output

gif output

I took the example from this fiddle, where you can see, how smooth the ball should look like.

how it should look like

What I tried so far without success,

  • Not creating a stream, when using GifEncoder
  • Collecting cx in an array and use GifEncoder afterwards, but it seems the ctx is a reference object and I could not find a way how to copy it
  • Playing around with P5 in hope, they have an internal calculation, when the deltaTime is to high between the frames

Can anyone help me here or give me an advice what to do?


Solution

  • It seems, I have already the solution. Setting the delay to:

    encoder.setDelay(30); // frame delay in ms
    

    Already smooths the gif:

    output

    My suggestion. Sleep a night and start with a fresh head