在p5.js中导出视频 [英] Exporting a video in p5.js

查看:160
本文介绍了在p5.js中导出视频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在p5.js中创建一个简单的动画程序.当用户单击保存"按钮时,我要下载该动画的视频.

I am creating a simple animation program in p5.js. When a user clicks the save button, I want to download a video of the animation.

我有一个名为frames的对象,其中每个键都标记为frame_1frame_2等.与每个键关联的值是构成该帧的线段的array.

I have an object called frames where each key is labelled frame_1, frame_2 and so on. The value associated with each key is an array of line segments that makes up that frame.

我正在尝试一种获取这些数据并创建mp4视频的方法. p5.j​​s具有内置的保存功能,我认为这可能会有所帮助,但没有帮助一个完整的解决方案.我可以将每个帧另存为单独的图像,然后以某种方式在客户端将这些图像拼接在一起,但是我还没有找到解决方案.

I am trying to think of an approach to take this data and create an mp4 video. p5.js has a built in save function that I thought might be helpful but it is not a full solution on its own. I could save each frame as an individual image and then somehow stitch those images together on the client side but I have yet to find a solution to this.

任何其他方法也都很好.唯一的要求是它是在客户端完成的.

Any other approaches would be great as well. The only requirement is that it is done client side.

推荐答案

由于p5.js是基于Canvas API构建的,因此在现代浏览器中,您可以使用

Since p5.js is built on the Canvas API, in modern browsers, you can use a MediaRecorder to do this job.

const btn = document.querySelector('button'),
  chunks = [];

function record() {
  chunks.length = 0;
  let stream = document.querySelector('canvas').captureStream(30),
    recorder = new MediaRecorder(stream);
  recorder.ondataavailable = e => {
    if (e.data.size) {
      chunks.push(e.data);
    }
  };
  recorder.onstop = exportVideo;
  btn.onclick = e => {
    recorder.stop();
    btn.textContent = 'start recording';
    btn.onclick = record;
  };
  recorder.start();
  btn.textContent = 'stop recording';
}

function exportVideo(e) {
  var blob = new Blob(chunks);
  var vid = document.createElement('video');
  vid.id = 'recorded'
  vid.controls = true;
  vid.src = URL.createObjectURL(blob);
  document.body.appendChild(vid);
  vid.play();
}
btn.onclick = record;

// taken from pr.js docs
var x, y;

function setup() {
  createCanvas(300, 200);
  // Starts in the middle
  x = width / 2;
  y = height;
}

function draw() {
  background(200);

  // Draw a circle
  stroke(50);
  fill(100);
  ellipse(x, y, 24, 24);

  // Jiggling randomly on the horizontal axis
  x = x + random(-1, 1);
  // Moving up at a constant speed
  y = y - 1;

  // Reset to the bottom
  if (y < 0) {
    y = height;
  }
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.7/p5.min.js"></script>
<button>start recording</button><br>

这篇关于在p5.js中导出视频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆