Skip to content

Instantly share code, notes, and snippets.

@mattdesl
Last active February 27, 2018 04:46
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattdesl/abe7819bb4003e375efb2f4bfff87cb9 to your computer and use it in GitHub Desktop.
Save mattdesl/abe7819bb4003e375efb2f4bfff87cb9 to your computer and use it in GitHub Desktop.
Texel + Saving Canvas PNG

Saving GIF/MP4 Frames with Texel

The above GIF was rendered with Canvas2D and JavaScript. I used texel, a tool I am developing but have not yet released.

If you want to try this very experimental tool, install the latest working version like so:

npm install texel@1.0.15 --global

Copy the index.js example script (see next file) into a new directory:

pbpaste > index.js

Now, start a development server on that file and open the browser:

texel index.js --open

When the page loads, it will save 100 numbered PNG frames in a tmp/ folder relative to your current working directory.

Encode a Movie

To create a GIF with ffmpeg:

ffmpeg -framerate 24 -i tmp/%02d.png -y output.gif

To create an MP4 file:

ffmpeg -framerate 24 -i tmp/%02d.png -y -c:v libx264 -profile:v high -crf 20 -pix_fmt yuv420p output.mp4

Another one using the same technique:

// The devtool utility for saving canvas frames
import devtool from 'texel/devtool';
// Create canvas
const canvas = document.createElement('canvas');
document.body.appendChild(canvas);
const size = 256;
canvas.width = size;
canvas.height = size;
// Grab 2D canvas context
const context = canvas.getContext('2d');
// How many frames to draw
let frame = 0;
const totalFrames = 100;
// Start drawing
render();
function render () {
// Clear background to black
context.fillStyle = 'black';
context.fillRect(0, 0, size, size);
// Draw some shapes
const margin = 40;
context.strokeStyle = 'white';
context.beginPath();
context.moveTo(margin, margin);
context.lineTo(size - margin, size - margin);
context.lineWidth = Math.sin(frame / totalFrames * Math.PI) * 20;
context.stroke();
// Save a single frame
devtool.saveCanvas(canvas, {
// The output folder, relative to current working directory
output: 'tmp',
// The current frame index, the filename will be zero-padded
frame: frame++,
// The total number of frames in our sequence
totalFrames
}).then(() => {
// Render another frame if necessary
if (frame < totalFrames) window.requestAnimationFrame(render);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment