🎬 super easy recording for p5.js animations

Overview

p5.capture

AboutWhy p5.capture?Getting startedAPI
OptionsBrowser compatibilityLimitations

About

Assuming you would like to record p5.js animations super easily, this package is the right choice for you.

👇 Check out the demo:

Why p5.capture?

🎩 Stable recording

Recording p5.js animations with screen recording tools can cause jerky recordings. Complex animations can slow down the framerate and make recording unstable. p5.capture hooks into the p5.js draw function and records the rendered frame, so it works like magic.

Keep your sketch clean

Adding recording functionality to a sketch can be very tedious. p5.capture provides a minimal GUI and is designed to add recording functionality without adding any code to your sketch. Let's focus on your creative coding. Of course, you can also use the API to integrate it into your code.

🤹 Any format • One API

Tired of having to use different libraries for different formats? p5.capture supports many export formats including WebM, GIF, MP4, PNG, JPG, and WebP. There is sure to be something you want.

Getting started

Installation

Insert a link to the p5.capture after p5.js in your html file:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.min.js"></script>
<!-- insert after p5.js -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/p5.capture.umd.min.js"></script>

You can find all versions in the jsDelivr.

Usage

Basically, the GUI provided by p5.capture starts and stops recording.

usage

That's all 🎉

Export formats

Supported formats include:

  • WebM (default): export WebM video using webm-writer-js
  • GIF: export animated GIF using gif.js
  • MP4: export MP4 video using h264-mp4-encoder
  • PNG: export PNG images in a ZIP file
  • JPG: export JPG images in a ZIP file
  • WebP: export WebP images in a ZIP file

API

The P5Capture class can be used to programmatically control recording.

Static methods

P5Capture.getInstance()

Returns a P5Capture instance.
Used to access the P5Capture instance automatically created when p5.capture is initialized.

P5Capture.setDefaultOptions(options)

Change default options. These options affect both GUI and API recording.
Must be used before p5.js initialization.

P5Capture.setDefaultOptions({
  format: "gif",
  framerate: 10,
  quality: 0.5,
  width: 320,
});

function setup() {
  // do something...
}

Instance methods

start(options?)

Start recording with the specified options.
options can be omitted.

stop()

Stop recording and start encoding.
Download files after encoding is complete.

Instance properties

state (Read only)

Returns the current recording state ("idle", "capturing", or "encoding").

Examples

The following example shows how to record the first 100 frames and create a GIF video:

function draw() {
  if (frameCount === 1) {
    const capture = P5Capture.getInstance();
    capture.start({
      format: "gif",
      duration: 100,
    });
  }

  // do something...
}

The following example shows how to add an event handler that starts and stops recording with a keystroke:

function keyPressed() {
  if (key === "c") {
    const capture = P5Capture.getInstance();
    if (capture.state === "idle") {
      capture.start();
    } else {
      capture.stop();
    }
  }
}

Options

Name Default Description
format "webm" export format. "webm", "gif", "mp4", "png", "jpg", and "webp"
framerate 30 recording framerate
bitrate 5000 recording bitrate in kbps, only valid for MP4
quality see Quality option recording quality from 0 (worst) to 1 (best), valid for WebM, GIF, JPG, WebP
width canvas width output image width
height canvas height output image height
duration null maximum recording duration in number of frames
verbose false dumps info on the console
disableUi false (only P5Capture.setDefaultOptions()) hides the UI
disableScaling false (only P5Capture.setDefaultOptions()) disables pixel scaling for high pixel density displays

Quality option

The default value of the quality option is different for each format.

Format Default
WebM 0.95
GIF 0.7
JPG 0.92
WebP 0.8

Browser compatibility

It may not work depending on your environment.
Tested in the following environments:

Chrome Edge Firefox Safari
WebM
GIF
MP4
PNG
JPG
WebP

The browser versions used for testing are

  • Chrome 98.0.4758.109
  • Edge 98.0.1108.62
  • Firefox 97.0.2
  • Safari 15.3

Limitations

Comments
  • Screen is all black

    Screen is all black

    Here is an example animation that fails to record:

    https://p5.javascript.org.pl/frantic-average?template=none

    I was testing simpler code with the recorder and using script tag this way works fine. Except it fails to record any video, even though it's a simple rotating square.

    This is a simplified version where I have a more complex function instead of a square. I've tried to reproduce the issue.

    opened by jcubic 11
  • Options for filename patterns

    Options for filename patterns

    v1.2.0 specification

    | file format | filename pattern | example | | --------------------------- | ----------------------------- | ---------------------- | | video (webm, gif, mp4), zip | timestamp (YYYYMMDD-HHmmdd) | 20220729-003612.webm | | image (png, jpg, webp) | 7-digit numbers | 0000123.png |

    The timestamp is to avoid duplicate file names.

    Issues

    The following issues are considered.

    • video, zip
      • Arbitrary strings cannot be included in the file name
      • Some locales are not comfortable with the datetime format YYYYYMMDD-HHmmdd
    • image
      • Arbitrary strings cannot be included in the file name
      • Overflow of digits in long animations
      • May not want the counter to reset on each run

    Requirements

    It is cool if the following requirements are met.

    • Avoid duplicate file names
    • Can include any string in the file name
    • Can specify the number of digits in the counter
    • Can specify a starting value for the counter
    opened by tapioca24 5
  • can't install

    can't install

    Can't even install via npm install

    npm ERR! path E:\DEVELOPMENT UTILS\PERSONAL\GENERATIVE\node_modules\p5.capture
    npm ERR! command failed
    npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c playwright install
    npm ERR! 'playwright' is not recognized as an internal or external command,
    npm ERR! operable program or batch file.
    
    
    opened by Polyterative 4
  • intercepting the file before download

    intercepting the file before download

    great library!

    forgive me if this is obvious but in the case that I wanted to let people review the video before downloading, would there be an elegant way to interrupt the process so that the file isn't downloaded directly? at the moment, the file just downloads but in some cases, it may be helpful to preview the recorded video as the user may want to discard it (this is for an interactive work). My understanding / memory is a little hazy, but I guess it's a blob before it gets downloaded.

    thanks much in advance!

    opened by ofZach 3
  • Video quality

    Video quality

    Thank you very much for this tool! I've been looking for an alternative to CCapture.js for some time now and this tool is perfect in every way: easy to use, flexible and easily adaptable to different sketches.

    Unfortunately, I'm not getting a good result regarding the quality of the videos (mp4 and webm). I did some tests varying the quality between 0.1, 0.5 and 1.0 and the results are pretty much the same. The tests can be accessed by this link.

    Here's some screenshots of the tests:


    Quality: 0.1 Quality: 0.1


    Quality: 0.5 Quality: 0.5


    Quality: 1.0 Quality: 1.0


    I'm setting the options right on the code, before setup:

    P5Capture.setDefaultOptions({  
      format: "mp4",  
      framerate: 60,  
      quality: 1.0,  
      width: 1080,  
    });
    

    Am I doing something wrong or is this behavior exactly what is expected?

    opened by werls 3
  • [feature request] segmented capture for large frames and long animations

    [feature request] segmented capture for large frames and long animations

    When capturing many large frames with p5.capture, the browser can crash or the encoding step can take forever

    I made this for my own purpose. It halts the sketch and saves the frames in batches:

    https://editor.p5js.org/SableRaf/sketches/KuLI1oVPT

    However it is a quick and dirty workaround and it would be amazing to have a solution built-in 😌

    opened by SableRaf 3
  • ドラッグ移動機能

    ドラッグ移動機能

    概要

    素晴らしいライブラリありがとうございます!!

    固定でも良いのですが、このcontainerがドラッグ移動出来たらより便利かなと思いました。

    (forkし少し実装したのですが、自分の方法ではfiefoxに対応できなかったためissueに書かせていただきました:pray:)

    以下の追加変更をここでは行っています。

    • 背景色をグレーへ(背景白だと少し見づらく感じました)
    • カーソルをmove
    • ~widthを170pxへ固定~
    opened by 3ru 3
  • adding support to p5 instance mode with one singleton

    adding support to p5 instance mode with one singleton

    This commit adds support for p5 instance mode, allowing the user to record one canvas at a time (any p5 canvas within the page).

    Usage is straightforward. As expected, after the canvas is set up, P5Capture is told to use that p5 instance and canvas instead of window.

    const s = ( sketch ) => {
    
        sketch.setup = () => {
            // your setup
            P5Capture.setDefaultOptions({p5 : sketch});
        };
    
        sketch.draw = () => {
            // your draw
        };
    };
    
    new p5(s);```
    
    That is all. I have also included:
    - the proper end to end tests
    - A safety check to warn if one tries to load p5.capture before the document body has been created. You can't load it before document.body as there would be nowhere for the recording window to be appended to
    
    If this implementation makes sense I can add this example to the Readme to finish it.
    
    I did not choose to support multiple recording sessions running at the same time inside a single page since:
    - it seems to be an even more rare situation
    - it would require to remove the singleton pattern of the P5.Capture, which is not a minor feature
    
    I guess that is all, thanks for the great work.
    opened by guilhermesilveira 2
  • Running without interface

    Running without interface

    It would be nice if you can use the library like a library without GUI. I would like to have my own interface in my Code editor I don't want any extra interface. Is something like this possible?

    opened by jcubic 2
  • Add support for instance mode

    Add support for instance mode

    In order to use p5 with several types of libraries, we need to restrict its usage to instance mode. For example, a react next project can not run p5 in global mode out of the box.

    The most common situation for instance mode is to have one single instance per page. I have submitted a pull request #17 that adds support for instance mode, allowing the recording of a single canvas at a time.

    In order to support multiple canvas recording at the same time, one needs to probably refactor the Singleton instance of p5.Capture, which I guess would be a different issue.

    opened by guilhermesilveira 1
  • Enables the UI to be moved by dragging

    Enables the UI to be moved by dragging

    Enables the UI to be moved by dragging.

    In Firefox, pageX / pageY does not work on drag event. (See 505521 - Set screen coordinates during HTML5 drag event) Therefore, I implemented it with the monsedown, mouseup, and mousemove events. There is a workaround using the dragover event, but I gave up on it because dragging in Firefox is not smooth.

    This PR is related to #1

    opened by tapioca24 0
  • MP4 format captures with glitches

    MP4 format captures with glitches

    Hi!

    I found problems with captured MP4 videos, the image starts to glitch when working with the video file in programs like Adobe After Effect / Photoshop / DaVinci Resolve. Just in case I've tried several computers and various versions of editing apps to avoid the possibility of a problem with a particular hardware or software.

    As an example, I recorded a one-minute video of the screen, about how the glitches occur using one of the programs. You can see that when you just play the captured video no glitches are detected, but when you work with it problems begin to emerge:

    https://user-images.githubusercontent.com/52974033/192270093-15b136a3-1f2f-4326-8143-86c523911f43.mp4

    It seems to be connected with the h264-mp4-encoder library itself because when I checked the captured video from the demo I found the same problem.

    I should probably report the problem to the developer of this MP4 encoder, but I am primarily interested in the functionality of your library, maybe you can find some other solution for making capture works properly for MP4 format.

    Thanks!

    opened by antlii 4
  • [feature suggestion] Make default frame rate from p5js

    [feature suggestion] Make default frame rate from p5js

    I'm not sure if this is possible but in my coding playground prototype:

    https://p5.javascript.org.pl/amused-loan?template=none

    To record a proper Gif I still need to put P5.capture code in my sketch. Capture frame rate should match frame rate from p5.js

    If I want to capture the animation I need to copy paste p5.capture default config:

    function setup() {
        createCanvas(400, 400);
        //noLoop();
        frameRate(5);
    }
    
    P5Capture.setDefaultOptions({
        disableUi: true,
        format: "gif",
        framerate: 5,
        quality: 0.5,
    });
    

    To not break the API, how about -1 value will mean that it should take frameRate from P5.js?

    opened by jcubic 3
  • [feature suggestion] stream saving

    [feature suggestion] stream saving

    I just came accross this https://github.com/jimmywarting/StreamSaver.js

    Wondering if stream saving directly to the file system would be an option as a more scalable alternative to segmented capture.

    opened by SableRaf 3
Owner
tapioca24
Front-end Engineer / Creative Coder
tapioca24
A super light, fast and simple tho advanced Music Bot

A super light, fast and simple tho advanced Music Bot, without any Music Manager Packages like Lavalink, discord-player or distube. Technically providing up to all filters of lavalink, but limited to 19 predefined ones, with speed and bassboost control, as well as everything in slash Commands and message Commands!

Tomato6966 43 Dec 17, 2022
Sharing the latest stellar Super Mario 64 runs verified on speedrun.com.

SM64-twitter-bot Sharing the latest stellar Super Mario 64 runs verified on speedrun.com. https://twitter.com/SuperMario64Bot Requirements You will ne

hippolyte 4 Jul 14, 2022
Easy and simple twitch bot in node.js.. very very easy..

How It Works identity: { username: 'YOUR BOTS USERNAME', <-- This is where you place the username that you gave the bot account password: '

Ventispurr 3 Dec 18, 2021
A lightweight, easy-to-use jQuery plugin for fluid width video embeds.

Introducing FitVids.js A lightweight, easy-to-use jQuery plugin for fluid width video embeds. FitVids automates the Intrinsic Ratio Method by Thierry

Dave Rupert 4.8k Dec 24, 2022
:musical_score: ts-audio is an agnostic library that makes it easy to work with AudioContext and create audio playlists in the browser

ts-audio · ts-audio is an agnostic and easy-to-use library to work with the AudioContext API and create Playlists. Features Simple API that abstracts

Evandro Leopoldino Gonçalves 284 Dec 25, 2022
An Easy to use and advanced working multiguild Waitingroom Bot written in discord.js v13 without any extra modules.

Multiguild-Waitingroom-v13 An Easy to use and advanced working multiguild Waitingroom Bot written in discord.js v13 without any extra modules. It is m

Tomato6966 17 Dec 11, 2022
An easy bot to create discord buttons easily.

Discord Buttons An easy bot to create discord buttons easily. Note: Node.js 16.6.0 or newer is required. Installation npm install You need to rename e

Fnr 7 Aug 19, 2022
Action broadcaster for easy multiplayer web applications.

Hummingbird Action broadcaster for easy multiplayer web applications. About Hummingbird is both an open-source software and a public live service that

Corenzan 5 May 23, 2022
Easy and automatic updating way

Changes: ENTER Intents for client! const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MEMBE

Akif Yüce 4 Jul 16, 2022
A easy way for making bots using Discord.js/Node.js

Discord.js-Bot-Template This is a very simple template for making bots using Discord.js/Node.js Tutorial: To begin, Install Node.js here. After Node.J

Prosperity 4 Nov 8, 2022
Easy-to-use , actively maintained discord bot written in dJS V13 with customizable features

Multi-purpose discord bot Found a bug? Notes There are some modules missing, you can still start the bot but there are some things within the source t

locus 7 Nov 28, 2022
Flexible and easy Dash/HLS/DRM integration for HTML5 video.

This project is made possible with Plyr, Hls.js, Dash.js. Features ?? HLS and DASH playback ?? Multi quality supported ?? Drm with custom header suppo

Tuhin Kanti Pal 25 Nov 11, 2022
A simple and easy-to-use WhatsApp bot project based on Multi-Device Baileys and written in JavaScript

MIZUHARA ANIME THEMED FULL FLEDGED MULTI DEVICE WHATSAPP BOT WITH COOL FEATURES A Full Fledged MD Bot For Bot Lovers REQUIREMENTS • HOW TO INSTALL? •

Arus~Bots 18 Oct 25, 2022
An easy way for users to appeal from a server ban. Hosted with Cloudflare workers.

Discord Ban Appeal Make it possible for users to appeal their bans online With a simple configuration to make your form unqiue to your server and with

Philip 5 Aug 10, 2022
A lightweight easy-to-use minecraft chatbridge

Kyuta Bot - Minecraft ChatBridge Kyuta is discord chat-bridge integration for minecraft based on the bedrock-protocol library and functions similarly

Sierrawastaken 7 Sep 27, 2022
A Discord music bot that's easy to set up and run yourself!

Mocha Music Bot Template A discord music bot template built using node.js. Feel free to edit and host your own version of this music bot. The prominen

ShivamKun 22 Oct 28, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
:dash: Simple yet powerful file-based mock server with recording abilities

?? smoke Simple yet powerful file-based mock server with recording abilities Just drop a bunch of (JSON) files in a folder and you're ready to go! Bas

Yohan Lasorsa 159 Dec 13, 2022