javascript - 如何将 Canvas 动画保存为 gif 或 webm?

标签 javascript html canvas three.js gif

我编写了这个函数来捕获 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);
        }

最佳答案

在现代浏览器中,您可以使用 MediaRecorder API 的连词。和 HTMLCanvasElement.captureStream方法。

MediaRecorder API 将能够动态编码视频或音频媒体文件中的 MediaStream,从而比抓取静态图像时所需的内存少得多。

const ctx = canvas.getContext('2d');
var x = 0;
anim();
startRecording();

function startRecording() {
  const chunks = []; // here we will store our recorded media chunks (Blobs)
  const stream = canvas.captureStream(); // grab our canvas MediaStream
  const rec = new MediaRecorder(stream); // init the recorder
  // every time the recorder has new data, we will store it in our array
  rec.ondataavailable = e => chunks.push(e.data);
  // only when the recorder stops, we construct a complete Blob from all the chunks
  rec.onstop = e => exportVid(new Blob(chunks, {type: 'video/webm'}));
  
  rec.start();
  setTimeout(()=>rec.stop(), 3000); // stop recording in 3s
}

function exportVid(blob) {
  const vid = document.createElement('video');
  vid.src = URL.createObjectURL(blob);
  vid.controls = true;
  document.body.appendChild(vid);
  const a = document.createElement('a');
  a.download = 'myvid.webm';
  a.href = vid.src;
  a.textContent = 'download the video';
  document.body.appendChild(a);
}

function anim(){
  x = (x + 1) % canvas.width;
  ctx.fillStyle = 'white';
  ctx.fillRect(0,0,canvas.width,canvas.height);
  ctx.fillStyle = 'black';
  ctx.fillRect(x - 20, 0, 40, 40);
  requestAnimationFrame(anim);
}
<canvas id="canvas"></canvas>

关于javascript - 如何将 Canvas 动画保存为 gif 或 webm?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50681683/

相关文章:

html - CSS 过渡效果向上高度不起作用

css - CSS 网格之谜 : padding in grid items

canvas - Firefox 4 文本渲染错误

javascript - 为基本的 CSS Canvas 游戏实现游戏开始/游戏结束/重启步骤

javascript - 用选定的颜色转换主色

javascript - 如何防止按钮提交表单

javascript - 在 Vue 实例方法中使用全局模块对象

javascript - 创建表困惑

javascript - 取消/取消 IE7 输入搜索上的 JavaScript 操作

javascript - ThreeJS ObjectLoader-无法读取未定义的属性 'fog'