开发者

Extracting single frames from an animated GIF to canvas

开发者 https://www.devze.com 2023-02-04 10:06 出处:网络
I need to load all the frames of an animated GIF to an HTML5 ca开发者_如何学运维nvas. Please note, I don\'t want to \"play\" the animated (someone asked this before), all I want is to extract all the

I need to load all the frames of an animated GIF to an HTML5 ca开发者_如何学运维nvas.

Please note, I don't want to "play" the animated (someone asked this before), all I want is to extract all the frames to use them as single images.


Buzzfeed have librarified the code from the repo tommitytom posted. I haven't tried it yet but it looks good.

https://github.com/buzzfeed/libgif-js


Take a look at jsgif; it downloads a GIF, parses it, and draws the individual frames of the file to a <canvas>. With a bit of digging you should be able to find the code that draws the individual frames and work from there.


Sorry, the short answer is that JavaScript has no way of controlling the current frame of an Animated GIF.

The long answer is that there are sort-of ways to do what you want with just JS, but they are very much convoluted hacks.

Example of hackish way: Create a canvas and don't add it to the DOM (so this won't be seen by anyone). In a fast loop (setTimeout), draw to this canvas constantly and collect snapshots. Compare the canvas ImageData to see if the frames have changed or not.

It would be a better use of your time, probably, to see how you can get your server to split it apart for you (with php/perl/python/etc)


When you only need the first frame of the GIF:

const image = document.getElementById('my-image');
const canvas = document.getElementById('my-canvas');
const ctx = canvas.getContext("2d");
// context.drawImage(img, x, y, width, height);
ctx.drawImage(image, 0, 0);

Credits: How to draw a GIF on a canvas?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号