Issue
I have a web app that plays an animation using javascript, html, css. Is there a way that I can record that to a video file so that a user can download and view the animation without going to the site?
Solution
Yes, using Canvas and MediaRecorder.
var canvas = document.querySelector("canvas");
var ctx = canvas.getContext("2d");
var video = document.querySelector("video");
var colors = ["red", "blue", "yellow", "orange", "black", "white", "green"];
function draw (){
ctx.fillStyle = colors[Math.floor(Math.random() * colors.length)];
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
draw();
var videoStream = canvas.captureStream(30);
var mediaRecorder = new MediaRecorder(videoStream);
var chunks = [];
mediaRecorder.ondataavailable = function(e) {
chunks.push(e.data);
};
mediaRecorder.onstop = function(e) {
var blob = new Blob(chunks, { 'type' : 'video/mp4' });
chunks = [];
var videoURL = URL.createObjectURL(blob);
video.src = videoURL;
};
mediaRecorder.ondataavailable = function(e) {
chunks.push(e.data);
};
mediaRecorder.start();
setInterval(draw, 300);
setTimeout(function (){ mediaRecorder.stop(); }, 5000);
<canvas width="200" height="200"></canvas>
<p>Wait for 5 seconds...</p>
<video autoplay controls download></video>
Source: How to record a canvas element by Alexis Delrieu
Note: At the time of writing, only ~90% of global users can use MediaRecorder according to CanIUse.com.
Answered By - Chris Happy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.