Skip to content

Instantly share code, notes, and snippets.

@agektmr
Last active September 16, 2022 08:13
Show Gist options
  • Save agektmr/6131721 to your computer and use it in GitHub Desktop.
Save agektmr/6131721 to your computer and use it in GitHub Desktop.
How to create gif animation
<html>
<head>
<style>
figure {
width: 200px;
height: 150px;
text-align: center;
float: left;
}
img {
width: 85px;
height: 120px;
}
textarea {
clear: left;
width: 100%;
height: 50%;
}
</style>
<script src="js/LZWEncoder.js"></script>
<script src="js/NeuQuant.js"></script>
<script src="js/GIFEncoder.js"></script>
<script id="source">
var urls = [
'img/frame1.png',
'img/frame2.png',
'img/frame3.png',
'img/frame4.png',
'img/frame5.png',
'img/frame6.png',
'img/frame7.png',
'img/frame8.png',
'img/frame9.png',
'img/frame10.png'
];
var w = 85, h = 120,
canvas, ctx, encoder, image;
var addFrame = function(i, callback) {
this.img = new Image();
this.img.src = urls[i];
// Wait for image to be loaded
img.onload = function() {
// Clear canvas by painting white
ctx.fillStyle = 'rgb(255, 255, 255)';
ctx.fillRect(0, 0, w, h);
// Copy image element onto canvas
ctx.drawImage(this, 0, 0, w, h);
// Add animation frame
encoder.addFrame(ctx);
// Call next iteration only if there's more images left
if (urls[++i]) {
// Time wait only for demo purpose
setTimeout(function() {
callback(i, callback);
}, 500);
} else {
encoder.finish();
generateGIF();
}
};
};
var generateGIF = function() {
// Create ArrayBuffer with unsigned int 8 bit view
var bin = new Uint8Array(encoder.stream().bin);
// Create Blob of GIF type
var blob = new Blob([bin.buffer], {type:'image/gif'});
// Create object URL from blob
var url = URL.createObjectURL(blob);
var image = document.getElementById('image');
/* You can also generate DataURL from binary
var b64 = window.btoa(encode.stream().getData());
image.src = 'data:image/gif;base64,'+b64;
*/
image.src = url;
image.onload = function() {
// Don't forget to revoke object url after load
URL.revokeObjectURL(url);
}
};
window.onload = function() {
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
encoder = new GIFEncoder();
encoder.setRepeat(0);
encoder.setDelay(100);
encoder.setSize(w, h);
canvas.width = w;
canvas.height = h;
encoder.start();
addFrame(0, addFrame);
}
</script>
</head>
<body>
<figure>
<canvas id="canvas"></canvas>
<figcaption>canvas to capture animation</figcaption>
</figure>
<figure>
<img id="image" />
<figcaption>complete animation</figcaption>
</figure>
<div>
<textarea disabled></textarea>
</div>
</body>
</html>
@enessayaci
Copy link

Hi! can you share the sources ?

<script src="js/LZWEncoder.js"></script> <script src="js/NeuQuant.js"></script> <script src="js/GIFEncoder.js"></script>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment