Usage
This guide will walk you through the fundamentals of using textmode.js
to transform your HTML canvas graphics into ASCII art. Whether you're new to the library or looking to understand advanced features, this page covers everything you need to know.
Quick Start
The most basic usage of textmode.js
requires just two steps:
import { textmode } from 'textmode.js';
// 1. Get your canvas element
const canvas = document.querySelector('canvas#myCanvas');
// 2. Create a textmodifier instance
const textmodifier = await textmode.create(canvas);
That's it! Your canvas will now display as ASCII art in real-time.
Basic Concepts
textmode
The textmode
object is the main entry point for using the library. It provides methods to create and manage Textmodifier
instances, which handle the conversion of canvas graphics to textmode art.
// Print the version of textmode.js
console.log('textmode.js version:', textmode.version);
// Fetch an existing canvas element
const canvas = document.querySelector('canvas#myCanvas');
// Create a textmodifier instance
const textmodifier = await textmode.create(canvas);
Textmodifier
The Textmodifier
is the main class you'll work with. Each instance is tied to a specific HTML canvas and handles its ASCII conversion process.
// Create with default options
const textmodifier = await textmode.create(canvas);
// Create with custom options
const textmodifier = await textmode.create(canvas, {
fontSize: 8,
renderMode: 'manual'
});
// Update options at any time
textmodifier.fontSize(32);
textmodifier.renderMode('auto');
Converters
Converters transform your canvas pixels into ASCII characters. Within each Textmodifier
instance, you can manage a pipeline of converters which are applied in sequence to generate the final ASCII output.
By default, each created Textmodifier
instance has a pre-configured TextmodeBrightnessConverter
active in the pipeline that converts pixel brightness to ASCII characters.
INFO
As textmode.js
is still early in development, the only available built-in converter currently is the mentioned brightness converter. In your converter pipeline you can still stack multiple brightness converters when utilizing the brightnessRange
method.
// Get the default brightness converter
const brightnessConverter1 = textmodifier.converter('brightness');
// Add a second brightness converter to the pipeline
// This allows you to stack multiple converters for more complex effects
// The first parameter is a unique name for the converter, the second is the type
const brightnessConverter2 = textmodifier.add("brightness2", "brightness");
// Configure and update the converter at any time during its lifecycle
brightnessConverter1.enabled(true);
brightnessConverter1.characters(" .:-=+*%@#");
brightnessConverter1.characterColor(255, 255, 255, 255);
brightnessConverter1.characterColorMode("fixed");
brightnessConverter1.cellColor(0, 0, 0, 255);
brightnessConverter1.cellColorMode("fixed");
brightnessConverter1.invert(false);
brightnessConverter1.rotation(0);
brightnessConverter1.flipHorizontally(false);
brightnessConverter1.flipVertically(false);
brightnessConverter1.brightnessRange([0, 127]);
brightnessConverter2.brightnessRange([128, 255]);
Rendering Modes
textmode.js
supports two rendering modes:
Auto Mode (Default)
- Automatically renders using
requestAnimationFrame
- Perfect for most applications
- Handles rendering loop for you
Manual Mode
- You control when rendering happens
- Call
textmodifier.render()
in your animation loop - Better for integration in certain scenarios
// Switch to manual mode
textmodifier.renderMode('manual');
// Your draw loop
function draw() {
// Draw your graphics
drawMyGraphics();
// Apply textmode conversion
textmodifier.render();
}
INFO
textmode.js
always resizes automatically to fit the given canvas size, so you don't need to worry about resizing logic.
Framework Integration
textmode.js
is designed to be framework-agnostic, meaning you can use it with any JavaScript framework or even vanilla JavaScript. Below are examples of how to integrate textmode.js
in different environments.
p5.js (WEBGL)
p5.js (P2D)
hydra-synth
Vanilla Canvas 2D
Three.js
Video
Standalone
Injection
As seen in the examples above, textmode.js
can work with any existing canvas element.
We can have some fun with this by injecting textmode.js
into websites that use canvas elements, such as games (Happy Wheels, ...) or any other web application that contains a canvas.
INFO
When injecting textmode.js
into external websites, you may encounter some limitations:
- Security Restrictions: Many websites block external scripts for security reasons
- Canvas Protection: Some canvases may be protected and won't allow access to their content
- Limited Access: Canvases inside frames or certain containers might not be reachable
Best results: Try injection on simple websites or games without strict security settings. For your own projects, you won't face these limitations.
A script to run in the browser console to inject textmode.js
into a canvas element might look like this:
function loadScript(url) {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = url;
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
});
}
let textmodifier;
async function injectTextmode() {
try {
await loadScript('https://cdn.jsdelivr.net/npm/textmode.js@0.1.0/dist/textmode.umd.min.js');
// Fetch the first canvas element on the page
// You can modify this selector to target a specific canvas if needed
const targetCanvas = document.querySelectorAll('canvas')[0];
if (targetCanvas) {
textmodifier = await textmode.create(targetCanvas, { fontSize: 8 });
console.log('textmode.js initialized on the canvas:', textmodifier);
// Now you can use the textmodifier object
} else {
console.error('Could not find the target canvas element.');
}
} catch (error) {
console.error('Failed to load script or initialize textmode:', error);
}
}
// Call the function to inject textmode.js
injectTextmode();
If successful, you will see the canvas element transformed into ASCII art in real-time. You can then customize the Textmodifier
instance as needed.
Examples
YouTube injection
async function injectTextmodeWithTrustedTypes() {
try {
// Create a trusted types policy
const policy = window.trustedTypes?.createPolicy('textmode-injection', {
createScriptURL: (url) => url
});
const script = document.createElement('script');
const trustedURL = policy.createScriptURL('https://cdn.jsdelivr.net/npm/textmode.js@latest/dist/textmode.umd.js');
script.src = trustedURL;
script.onload = async () => {
console.log('Textmode.js loaded successfully!');
// Apply to YouTube video
const video = document.querySelector('video');
if (video) {
const textmodifier = await textmode.create(video, {
fontSize: 8,
});
console.log('Textmode applied to YouTube video!');
}
};
document.head.appendChild(script);
} catch (error) {
console.error('Failed to inject with trusted types:', error);
}
}
injectTextmodeWithTrustedTypes();
Next Steps
Now that you understand the basics, explore these advanced topics:
- API Reference - Complete API documentation
- Examples - Interactive demos and code samples
Ready to create amazing ASCII art? Check out our examples to see textmode.js
in action!