video to gif in javascript

You can convert a video to a GIF in JavaScript using a library like "gifshot". First, you would need to capture frames from the video and then use those frames to generate a GIF. Here is a sample code snippet on how to achieve this:

index.tsx
// Include the gifshot library in your project
// You can install it using npm: npm install gifshot

// Assuming you have an HTML5 video element with id "videoElement"
const videoElement = document.getElementById("videoElement");

const captureFrames = () => {
    const canvas = document.createElement("canvas");
    const context = canvas.getContext('2d');

    canvas.width = videoElement.videoWidth;
    canvas.height = videoElement.videoHeight;

    context.drawImage(videoElement, 0, 0, canvas.width, canvas.height);

    // Convert the current frame into a base64 image
    return canvas.toDataURL('image/png');
};

const createGIF = () => {
    const frames = [];

    // Capture frames at specific intervals
    const intervalId = setInterval(() => {
        frames.push(captureFrames());

        if (videoElement.ended) {
            clearInterval(intervalId);

            // Using the gifshot library to create a GIF
            gifshot.createGIF({
                images: frames,
                interval: 0.1,
                gifWidth: videoElement.videoWidth,
                gifHeight: videoElement.videoHeight
            }, (obj) => {
                if (!obj.error) {
                    // obj.image contains the base64 GIF image
                    console.log(obj.image);
                }
            });
        }
    }, 100); // Capture frames every 100 milliseconds
};

// Call the createGIF function when the video is loaded
videoElement.addEventListener('loadeddata', createGIF);
1509 chars
48 lines

This code captures frames from a video element and then uses the "gifshot" library to create a GIF. You can adjust the interval at which frames are captured and customize the GIF generation according to your requirements.

related categories

gistlibby LogSnag