benjaminadk / gif-encoder-2

Encode GIFs with Node
The Unlicense
58 stars 18 forks source link

Why is my gif output so slow? #17

Closed Yetispapa closed 2 years ago

Yetispapa commented 2 years ago

i want to render a gif with your library. 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

smooth-gif-from-canvas

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

ezgif-7-a9fde05d79f9

What I tried so far without success,

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

I posted the same issue in the origin GifEncoder repo, in hope someone can help me here.

Thank you in advance

Yetispapa commented 2 years ago

Setting:

encoder.setDelay(30);

solved the problem..