如何将画布动画保存为 gif 或 webm?

12 浏览
0 Comments

如何将画布动画保存为 gif 或 webm?

我编写了这个函数来捕获GIF的每一帧,但输出非常卡顿,并且当数据增加时会崩溃。有什么建议吗?

代码:

function createGifFromPng(list, framerate, fileName, gifScale) {
    gifshot.createGIF({
        'images': list,
        'gifWidth': wWidth * gifScale,
        'gifHeight': wHeight * gifScale,
        'interval': 1 / framerate,
    }, function(obj) {
        if (!obj.error) {
            var image = obj.image;
            var a = document.createElement('a');
            document.body.append(a);
            a.download = fileName;
            a.href = image;
            a.click();
            a.remove();
        }
    });
}
function getGifFromCanvas(renderer, sprite, fileName, gifScale, framesCount, framerate) {
    var listImgs = [];
    var saving = false;
    var interval = setInterval(function() {
        renderer.extract.canvas(sprite).toBlob(function(b) {
            if (listImgs.length >= framesCount) {
                clearInterval(interval);
                if (!saving) {
                    createGifFromPng(listImgs, framerate, fileName,gifScale);
                    saving = true;
                }
            }
            else {
                listImgs.push(URL.createObjectURL(b));
            }
        }, 'image/gif');
    }, 1000 / framerate);
}

0