Dav*_*nan 5 javascript canvas todataurl web-mediarecorder mediarecorder-api
我从收到的帧canvas通过canvas.getDataURL().
但是,现在我有一系列png图像,但我想要一个视频文件.
我该怎么做呢?
var canvas = document.getElementById("mycanvaselementforvideocapturing");
var pngimages = [];
...
setInterval(function(){pngimages.push(canvas.toDataURL())}, 1000);
Run Code Online (Sandbox Code Playgroud)
对于完整的浏览器支持方式,您必须将映像批处理发送到服务器,然后使用某些服务器端程序进行编码.
但在最新的浏览器中,该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.onended = 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();Run Code Online (Sandbox Code Playgroud)
<canvas id="canvas" width="500" height="200"></canvas>
<button id="rec">record</button>Run Code Online (Sandbox Code Playgroud)
因为你想要一种方法来为这个视频添加音频,请注意你可以cStream.addTrack(anAudioStream.getAudioTracks()[0]);在调用之前使用new MediaRecorder(cStream),但是这目前只能在chrome中使用,FF似乎在MediaRecorder中有一个错误,它使它只记录带有跟踪的流定义为...... FF的解决方法是调用new MediaStream([videoTrack, audioTrack]);
[非常感谢@jib让我知道如何实际使用它...]
编辑:video.onend- >video.onended