Skip to main content

Integrating p5.asciify with p5.js 2.0

With p5.js 2.0, and it's introduction to use async/await for asset loading, we have to make use of this in certain scenarios too when using p5.asciify with p5.js versions >=2.0.2.

Adding additional asciifiers

When adding additional asciifiers, similar to the example in the Running multiple rendering pipelines in parallel guide, it's necessary to add the async keyword to the setupAsciify function header. When then adding a new asciifier, we need to use the await keyword when calling p5asciify.add().

let defaultAsciifier; // Define a variable to store the default `P5Asciifier` instance
let customAsciifier; // Define a variable to store the custom `P5Asciifier` instance

let customFramebuffer; // Framebuffer the custom asciifier will asciify

function setup() {
setAttributes('antialias', false);
createCanvas(windowWidth, windowHeight, WEBGL);
};

async function setupAsciify() {
// Fetch the default `P5Asciifier` instance provided by the library
defaultAsciifier = p5asciify.asciifier();

customFramebuffer = createFramebuffer();
customAsciifier = await p5asciify.add(customFramebuffer);

defaultAsciifier.fontSize(finalDefaultOptions.fontSize);
customAsciifier.fontSize(finalCustomOptions.fontSize);

// Make the background of both asciifiers fully transparent.
defaultAsciifier.background([0, 0, 0, 0]);
customAsciifier.background([0, 0, 0, 0]);
};

function draw() {
directionalLight(255, 255, 255, 0, 0, -1);

// Draw anything on the custom framebuffer for the custom asciifier to asciify
customFramebuffer.begin();
clear();
fill(255);
rotateX(radians(frameCount * 3));
rotateZ(radians(frameCount));
box(800, 100, 100);
customFramebuffer.end();

// Draw anything on the canvas for the default asciifier to asciify
clear();
normalMaterial();
rotateX(radians(frameCount * 3));
rotateY(radians(frameCount));
torus(300, 100);
};

// After the asciified content is drawn to the canvas, use `drawAsciify()` to draw on top of it
function drawAsciify() {
background(0); // Set the background to black, removing everything previously drawn

// Draw both asciifier textures on top of each other
image(defaultAsciifier.texture, -width / 2, -height / 2);
image(customAsciifier.texture, -width / 2, -height / 2);
};

function windowResized() {
resizeCanvas(windowWidth, windowHeight);
};

note

This is currently the only scenario where async/await is required with p5.js 2.0. For all other p5.asciify functionality, the standard usage patterns work as before. If you encounter any other situations requiring async handling, please report them in the GitHub repository of the library.