Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a video from a Javascript animation?

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?

like image 267
lukew3 Avatar asked Sep 06 '25 03:09

lukew3


1 Answers

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, ~95% of global users can use MediaRecorder according to CanIUse.com.

like image 135
Chris Happy Avatar answered Sep 07 '25 21:09

Chris Happy