jnordberg / gif.js

JavaScript GIF encoding library
http://jnordberg.github.io/gif.js/
MIT License
4.74k stars 668 forks source link

1px border on alpha export #100

Open FuzzyWobble opened 5 years ago

FuzzyWobble commented 5 years ago

gritty_1px

^^ cannot remove the 1px border created by the key color.

Any idea if this is possible? Thanks.

johnlandish commented 5 years ago

did you fine a solution to this.

1j01 commented 5 years ago

GIF as a format only supports one-bit transparency, but you can get rid of this color artifact by passing an image where every pixel is already fully opaque or transparent.

You can apply a threshold, like so, using canvas:

var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
ctx.drawImage(image, 0, 0);

var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
var threshold = 128;
for (var i=0; i<imageData.data.length; i+=4) {
    imageData.data[i+3] = 255 * (imageData.data[i+3] > threshold);
}
ctx.putImageData(imageData, 0, 0);

// and add the canvas as the frame instead of the image
gif.addFrame(canvas);

You can play around with the threshold between 0 and 255 to find what works best.