4

我从canvascanvas.getDataURL()获取帧。如何将PNG图像数据数组转换为视频文件

但是,现在我有一个PNG图像数组,但我想要一个视频文件。

我该怎么做?

var canvas = document.getElementById("mycanvaselementforvideocapturing"); 
var pngimages = []; 
... 
setInterval(function(){pngimages.push(canvas.toDataURL())}, 1000); 

回答

5

对于一个完整的浏览器支持的方式,你有你的图片批量发送到服务器,然后使用一些服务器端程序做编码。

FFmpeg might be able to do it.

但在最新的浏览器canvas.captureStream方法,已落实。 它会将您的画布图纸转换为webm视频流,可用MediaRecorder记录。 尽管如此,所有这些仍然不稳定,并且只会在最新版本的浏览器中提供,可能会在用户的偏好设置中设置一些标志(例如chrome需要“实验性Web平台”之一)。

var cStream, 
 
    recorder, 
 
    chunks = []; 
 

 
rec.onclick = function() { 
 
    this.textContent = 'stop recording'; 
 
    // set the framerate to 30FPS 
 
    var cStream = canvas.captureStream(30); 
 
    // create a recorder fed with our canvas' stream 
 
    recorder = new MediaRecorder(cStream); 
 
    // start it 
 
    recorder.start(); 
 
    // save the chunks 
 
    recorder.ondataavailable = saveChunks; 
 

 
    recorder.onstop = exportStream; 
 
    // change our button's function 
 
    this.onclick = stopRecording; 
 
}; 
 

 
function saveChunks(e) { 
 

 
    chunks.push(e.data); 
 

 
} 
 

 
function stopRecording() { 
 

 
    recorder.stop(); 
 

 
} 
 

 

 
function exportStream(e) { 
 
    // combine all our chunks in one blob 
 
    var blob = new Blob(chunks) 
 
    // do something with this blob 
 
    var vidURL = URL.createObjectURL(blob); 
 
    var vid = document.createElement('video'); 
 
    vid.controls = true; 
 
    vid.src = vidURL; 
 
    vid.onend = function() { 
 
    URL.revokeObjectURL(vidURL); 
 
    } 
 
    document.body.insertBefore(vid, canvas); 
 
} 
 

 
// make something move on the canvas 
 
var x = 0; 
 
var ctx = canvas.getContext('2d'); 
 

 
var anim = function() { 
 
    x = (x + 2) % (canvas.width + 100); 
 
    // there is no transparency in webm, 
 
    // so we need to set a background otherwise every transparent pixel will become opaque black 
 
    ctx.fillStyle = 'ivory'; 
 
    ctx.fillRect(0, 0, canvas.width, canvas.height); 
 
    ctx.fillStyle = 'black'; 
 
    ctx.fillRect(x - 50, 20, 50, 50) 
 
    requestAnimationFrame(anim); 
 
}; 
 
anim();
<canvas id="canvas" width="500" height="200"></canvas> 
 
<button id="rec">record</button>

既然你问的方式来添加音频视频,请注意,你可以在调用new MediaRecorder(cStream)之前使用cStream.addTrack(anAudioStream.getAudioTracks()[0]);,但这将在Chrome目前只工作,FF似乎有MediaRecorder中的一个错误,它使得它只记录流被定义的轨道...... FF的解决方法是致电new MediaStream([videoTrack, audioTrack]);

[非常感谢@jib让我知道如何实际使用它。 ..]

+0

谢谢。我必须在Firefox上测试它(因为Chrome不支持它)。 “canvas.captureStream”中的30是什么意思?这是帧率。 –

+0

是的,就像评论说的那样;-) – Kaiido

+0

哦,哎呀!错过了。太感谢了。 –