How to record your canvas or screen for video capture?

I recently came across this website Design the next iPhone where after you click preset you have an option of downloading the video of 6s. As you can see below

Does anyone know how can I record the canvas for video or any npm package for recording the webpage.

thankyou
Seeon

I’m using the FileSaver.js library to record. But this requires some modifications in the code. Here are the key pieces of code:

    function dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, {
        type: mime
      });
    }

    function screenshotName(i){
      if(i<10){
        return "screenshot00" + i.toString() + ".png";
      }else if(i < 100){
        return "screenshot0" + i.toString() + ".png";
      }else{
        return "screenshot" + i.toString() + ".png";
      }
    }

......

    let frame = 0;

    function animate() {
      renderer.render(scene, camera);
      if (frame < 180) {
        var dataurl = renderer.domElement.toDataURL();
        var file = dataURLtoFile(dataurl, screenshotName(frame));
        saveAs(file);
        frame += 1;
      }
      ......

Maybe slow down the animation too.

Two paths that I know:

  • in the past I’ve used the spite’s ccapture.js library for recording canvas to video using a fixed framerate. It is kind of dated, and generates WebM and PNGs sequences very well.

  • a more modern approach would be using html5 captureStream() method to grab canvas data and then record it using the MediaRecorder API. Please see this page from mozilla docs for details

My two cents

1 Like

This is the official example from WebRTC of how to record a HTML canvas and download it as a video.

ISSUE: a major issue I had with getting this right was to set the correct mimeType. For example : firefox support video/webm;codecs:vp9 but not video/webm;codecs=vp9
SOLUTION: After a lot of research, I got this resource which helps you find the correct mimeType in runtime for the respective browser.

The core logic is to use MediaRecorder and canvasElement.captureStream(30) to record the canvas and store it into a blob.


Additional References: