Skip to content

textmode.js / Textmodifier

Class: Textmodifier

The main textmode.js drawing context.

A Textmodifier manages a canvas, renderer, layers, fonts, media sources, input, animation, and the p5-style drawing API. When no canvas is supplied, it creates one; when a canvas is supplied, it renders into that element.

Extends

  • TextmodifierExtensions

2D drawing

Draw points, lines, curves, and planar primitives.

MethodDescription
arcDraw an arc with the current settings. Position is controlled via translate, push, and pop.
bezierCurveDraw a smooth cubic Bezier curve between two points. The curve thickness is controlled by the current lineWeight setting.
ellipseDraw an ellipse with the current settings. Position is controlled via translate, push, and pop.
lineDraw a line from (x1, y1) to (x2, y2).
lineWeightSet or get line thickness for subsequent line and curve drawing.
pointDraw one cell with the current settings.
rectDraw a rectangle with the current settings. Position is controlled via translate, push, and pop.
triangleDraw a triangle with the current settings.

3D drawing

Draw built-in three-dimensional primitives.

MethodDescription
boxDraw a box mesh primitive.
coneDraw a cone mesh primitive.
cylinderDraw a cylinder mesh primitive.
ellipsoidDraw an ellipsoid mesh primitive.
sphereDraw a sphere mesh primitive.
torusDraw a torus mesh primitive.

Animation & timing

Control rendering cadence and read elapsed sketch time.

NameDescription
frameCountCurrent frame count.
millisMilliseconds since the sketch started running.
secsSeconds since the sketch started running.
deltaTimeTime in milliseconds between the current frame and the previous frame.
frameRateSet the target frame rate, or get the current measured frame rate when called without arguments.
isLoopingWhether the automatic render loop is currently running.
loopResume the rendering loop if it was stopped by noLoop.
noLoopStop the automatic rendering loop.
redrawRender a fixed number of frames on demand.
targetFrameRateSet or get the target frame rate limit.

Cameras & projection

Control the camera and projection used for spatial drawing.

MethodDescription
cameraSet an explicit camera transform for subsequent draw calls.
createCameraCreate and activate a camera initialized from the current render camera state.
lookAtUpdate the look-at target and optional up vector for the active camera.
orthoEnable orthographic projection for subsequent shape drawing.
perspectiveEnable perspective projection and optionally set projection parameters.
resetCameraReset to the default auto camera behavior.
setCameraActivate a previously created camera object.

Canvas & display

Inspect and resize the canvas and display output.

NameDescription
displayHeightPhysical screen height in pixels.
displayWidthPhysical screen width in pixels.
windowHeightCurrent browser window height in pixels.
windowWidthCurrent browser window width in pixels.
canvasCanvas containing the rendered output.
heightCanvas height in pixels.
widthCanvas width in pixels.
pixelDensityGet the current pixel density for HiDPI rendering.
resizeCanvasResize the canvas and adjust all related components accordingly.
windowResizedSet the callback that runs after a window resize.

Characters & color

Set the glyph, colors, and per-character appearance for later drawing.

MethodDescription
backgroundCurrent background color.
cellColorCurrent cell background color.
charCurrent character string used for drawing.
charColorCurrent character color.
charRotationSet the character rotation for subsequent drawing, or get the current angle.
clearClear the layer currently drawing to.
colorCreate a reusable color object from a grayscale value.
colorModeCurrent color interpretation mode.
fillAlias for cellColor. Current fill (cell background) color.
flipXToggle horizontal flipping for subsequent characters, or get the current state.
flipYToggle vertical flipping for subsequent characters, or get the current state.
invertToggle character/cell color inversion, or get the current state.
strokeAlias for charColor. Current stroke (character) color.

Conversion

Convert source imagery and post-process rendered output.

AccessorDescription
conversionsAccess the conversion manager for this Textmodifier instance.

Custom geometry

Assemble vertex-based shapes with explicit topology.

NameDescription
LINE_LOOPDraw consecutive vertices as one connected closed loop.
LINE_STRIPDraw consecutive vertices as one connected open path.
LINESDraw each pair of recorded vertices as an independent line segment.
POINTSDraw each recorded vertex as a separate point.
QUAD_STRIPDraw paired vertices as a connected strip of quads.
QUADSDraw each group of four vertices as a quad split into two triangles.
TRIANGLE_FANDraw triangles that all share the first recorded vertex.
TRIANGLE_STRIPDraw overlapping triplets of vertices as a connected triangle strip.
TRIANGLESDraw each group of three vertices as an independent triangle.
beginShapeStart recording vertices for a custom 2D or 3D shape. Call vertex one or more times, then call endShape to draw the recorded shape.
endShapeFinish the active custom shape and enqueue its geometry.
vertexAdd a vertex to the active custom shape. The current transform, character, color, and line state are captured for this vertex.

Gamepad input

Read connected controllers and react to gamepad events.

NameDescription
gamepadsCurrently connected gamepads as a compact readonly list.
gamepadResolve a connected gamepad by its browser-assigned slot index.
gamepadAxisChangedRegister the single-callback handler for meaningful gamepad axis changes.
gamepadButtonPressedRegister the single-callback handler for gamepad button press events.
gamepadButtonReleasedRegister the single-callback handler for gamepad button release events.
gamepadConnectedRegister the single-callback handler for gamepad connection events.
gamepadDisconnectedRegister the single-callback handler for gamepad disconnection events.

Grid, fonts & glyphs

Configure the drawing grid and the glyph source that populates it.

NameDescription
fontFont or tileset used by the current drawing layer.
gridGrid for the layer currently being drawn.
createGlyphRampCreate a reusable glyph ramp from a character sequence.
fontSizeSet or get the base layer font size.
loadFontLoad a font and optionally set it as the base layer's active font.
loadTilesetLoad a tileset and optionally set it as the base layer's active glyph source.
projectClientToGridProject CSS viewport/client coordinates into a textmode grid.
useTileColorsConfigure authored tileset color preservation on the base layer.

Input events

Subscribe to input through the shared event interface.

MethodDescription
inputGridGet or set the grid used for mouse and touch coordinate mapping.
offRemove a previously registered input event listener.
onRegister an input event listener.
onceRegister an input event listener that removes itself after the first invocation.

Keyboard input

Read keyboard state and react to keyboard events.

NameDescription
lastKeyPressedLast key pressed, or null before any key press.
lastKeyReleasedLast key released, or null before any key release.
modifierStateCurrent modifier key state.
pressedKeysKeys currently being held down.
isKeyPressedCheck whether a key is currently pressed.
keyPressedRegister the single-callback handler for key press events.
keyReleasedRegister the single-callback handler for key release events.
keyTypedRegister the single-callback handler for printable character input.

Layers & compositing

Manage layer stacks and choose how their output combines.

NameDescription
BLEND_ADDITIVEAdd the layer's color channels to the layers below it.
BLEND_COLOR_BURNDarken the layers below by inverting the color dodge relationship.
BLEND_COLOR_DODGEBrighten the layers below by dividing around the layer color.
BLEND_DARKENKeep the darker channel from either the layer or the layers below it.
BLEND_DIFFERENCEUse the absolute channel difference between the layer and the layers below.
BLEND_EXCLUSIONUse a lower-contrast difference blend between the layer and the layers below.
BLEND_HARD_LIGHTApply an intense contrast blend driven by the layer's brightness.
BLEND_LIGHTENKeep the lighter channel from either the layer or the layers below it.
BLEND_MULTIPLYMultiply the layer's colors with the layers below it.
BLEND_NORMALDraw the layer with standard source-over alpha compositing.
BLEND_OVERLAYCombine multiply and screen based on the brightness below the layer.
BLEND_SCREENScreen the layer against the layers below it.
BLEND_SOFT_LIGHTApply a softer contrast blend based on the layer's brightness.
BLEND_SUBTRACTSubtract the layer's colors from the layers below it.
layersLayer manager for this Textmodifier instance.

Lighting

Illuminate three-dimensional geometry.

MethodDescription
ambientLightAdd an ambient light using a grayscale value.
lightFalloffConfigure distance attenuation used by point lights.
noLightsRemove all active lights (ambient and point) and reset light falloff to (1, 0, 0).
pointLightAdd a point light using RGB components and explicit XYZ position.

Loading & errors

Access built-in loading feedback and fatal-error controls.

AccessorDescription
errorsBuilt-in fatal error layer controller.
loadingBuilt-in loading layer controller.

Math & vectors

Use creative-coding math helpers and mutable vectors.

MethodDescription
absCalculate the absolute value of a number.
acosCalculate the arc cosine of a value.
asinCalculate the arc sine of a value.
atanCalculate the arc tangent of a value.
atan2Calculate the angle from a vector's y and x components.
ceilRound up to the closest integer.
clampClamp a value between a minimum and maximum range.
constrainConstrain a value between a minimum and maximum range.
cosCalculate the cosine of an angle.
createVectorCreate a mutable vector.
degreesConvert radians to degrees.
distCalculate the Euclidean distance between two points.
easeApply an easing curve to a normalized amount.
expCalculate Euler's number raised to a value.
floorRound down to the closest integer.
fractCalculate the fractional part of a number.
lerpLinear interpolation between two values.
logCalculate the natural logarithm of a value.
mapRe-map a number from one range to another.
maxReturn the largest value in a sequence.
minReturn the smallest value in a sequence.
normMap a number from a range to a normalized 0 to 1 range.
powRaise a base value to an exponent.
radiansConvert degrees to radians.
roundRound to the closest integer or decimal place.
sinCalculate the sine of an angle.
sqSquare a number.
sqrtCalculate the square root of a number.
tanCalculate the tangent of an angle.

Media & textures

Load visual sources and use them as drawing or texture input.

MethodDescription
createTextureCreate a dynamic texture from an external canvas or video element.
imageDraw a framebuffer, image, video, or texture source to the currently bound framebuffer.
loadImageLoad an image source that can be drawn with image.
loadVideoLoad a video source that can be drawn with image.
noTextureClear the active texture for later geometry draws.
textureBind a media source or framebuffer as the texture for later geometry draws.

Mouse input

Read pointer state, mouse events, and pointer-lock controls.

NameDescription
mouseCurrent mouse position in center-based grid coordinates.
mouseIsPressedWhether a mouse button is currently held down.
movedXHorizontal mouse movement accumulated since the previous rendered frame.
movedYVertical mouse movement accumulated since the previous rendered frame.
pmouseMouse position from the previous rendered frame.
cursorSet the mouse cursor for the textmode canvas.
doubleClickedRegister the single-callback handler for double-clicks.
exitPointerLockExit pointer lock if the textmode canvas currently owns it.
mouseClickedRegister the single-callback handler for mouse clicks.
mouseDraggedRegister the single-callback handler for mouse dragging.
mouseMovedRegister the single-callback handler for mouse movement.
mousePressedRegister the single-callback handler for mouse press events.
mouseReleasedRegister the single-callback handler for mouse release events.
mouseScrolledRegister the single-callback handler for mouse wheel scrolling.
requestPointerLockRequest browser pointer lock for the textmode canvas.

Randomness & noise

Generate deterministic random values and coherent noise.

MethodDescription
noiseReturn deterministic multi-octave noise for a coordinate.
noiseDetailAdjust noise octaves and falloff.
noiseSeedReset the noise lookup table to a seed.
randomReturn a random number from 0 up to, but not including, 1.
randomGaussianReturn a normally distributed random number.
randomSeedReset the main sketch random generator to a seed.
randomStreamGet an independent deterministic random stream for a name.

Shaders & framebuffers

Build GPU effects and offscreen rendering pipelines.

MethodDescription
createFramebufferCreate a framebuffer for offscreen rendering.
createMaterialShaderCreate a material shader from fragment shader source or a file path.
createShaderCreate a shader from vertex and fragment source, or from file paths.
resetShaderReset the current shader to the default solid color shader.
setUniformSet a uniform value on the current custom shader.
setUniformsSet multiple uniform values on the current custom shader.
shaderSet a custom shader for subsequent drawing operations.

Sketch lifecycle

Configure callbacks and manage the lifetime of a sketch.

NameDescription
isDisposedWhether this instance has been destroyed.
isRenderingFrameCheck if rendering is currently in progress for this frame.
destroyCompletely destroy this Textmodifier instance and free all associated resources.
drawSet the base layer draw callback.
postDrawSet the base layer post-draw callback.
setupSet the setup callback that runs once initialization is complete.

Text rendering

Lay out and draw strings on the active layer.

MethodDescription
printPrint a string of text onto the active drawing layer.
printAlignSets the text alignment rules for subsequent print calls.

Touch & gestures

React to touch lifecycle events and derived gestures.

NameDescription
touchesCurrently active touches in grid coordinates.
doubleTapRegister a callback for double tap gestures.
longPressRegister a callback for long press gestures.
pinchRegister a callback for pinch gestures, receiving scale deltas.
rotateGestureRegister a callback for rotate gestures, receiving rotation deltas in degrees.
swipeRegister a callback for swipe gestures.
tapRegister a callback for tap gestures.
touchCancelledRegister the single-callback handler for browser-cancelled touches.
touchEndedRegister the single-callback handler for touch end events.
touchMovedRegister the single-callback handler for touch movement.
touchStartedRegister the single-callback handler for touch start events.

Transforms & state

Position geometry and isolate changes to draw state.

MethodDescription
applyMatrixMultiply the current model transform by a custom 4x4 matrix.
popRestore the most recently saved rendering state, shader, and uniforms from the state stack. Use with push to isolate style changes within a block.
pushSave the current rendering state, shader, and uniforms to the state stack. Use with pop to isolate style changes within a block.
resetMatrixReset the current model transform to identity.
rotateSet rotation for subsequent shape drawing.
rotateXSet X-axis rotation for subsequent shape drawing, or get the current angle.
rotateYSet Y-axis rotation for subsequent shape drawing, or get the current angle.
rotateZSet Z-axis rotation for subsequent shape drawing, or get the current angle.
scaleScale subsequent geometry in model space.
translateTranslate subsequent shape drawing.
translateXCurrent accumulated X-axis translation.
translateYCurrent accumulated Y-axis translation.
translateZCurrent accumulated Z-axis translation.