• Stars
    star
    184
  • Rank 209,187 (Top 5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 5 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

πŸ’¬ Text plugin for Zdog - works with any .ttf font!


Zfont

A text plugin for the Zdog 3D engine! Renders TrueType fonts via Typr.js | jaames.github.io/zfont

Features | Caveats | Demo | Installation | Usage | API | Zdog.Font | Zdog.Text | Zdog.TextGroup | Todo | Building


Features

  • Built on top of Typr.js, which supports a wide range of .ttf and .otf fonts with speed and grace
  • Less than 14kB minified and gzipped
  • No need to worry about waiting for fonts to load; text automatically pops into existence once the font is ready
  • Includes support for multiline text
  • Update font, text, color, alignment, etc at any time
  • Bonus utilities for measuring text, waiting for font load & more!

Caveats

  • You have to provide a .ttf to use yourself; it isn't possible to use system fonts
  • Character range is limited to whichever glyphs are supported by your chosen font, and font stacks/fallbacks aren't supported yet

Demo

A live demo can be found here, there's also some more in-depth examples on Codepen!

Installation

Install with NPM

$ npm install zfont --save

If you are using a module bundler like Webpack or Rollup, import Zfont into your project:

// Using ES6 module syntax
import Zfont from 'zfont';

// Using CommonJS modules
const Zfont = require('zfont');

Using the jsDelivr CDN

<script src="https://cdn.jsdelivr.net/npm/zfont/dist/zfont.min.js"></script>

When manually including the library like this, it will be globally available on window.Zfont

Download and Host Yourself

Development version
Uncompressed at around 75kB, with source comments included

Production version
Minified to 45kB

Then add it to the <head> of your page with a <script> tag:

<html>
  <head>
    <!-- ... -->
    <script src="./path/to/zfont.min.js"></script>
  </head>
  <!-- ... -->
</html>

Usage

Register Plugin

After both Zdog and Zfont have been imported/downloaded, we need to initialize the Zfont plugin. Once it's initialized, the Zdog.Font, Zdog.Text and Zdog.TextGroup classes will be available:

Zfont.init(Zdog);

Hello World

(Pssst! If you prefer to dive in, check out the basic demo over on Codepen)

To draw some text in a Zdog scene, first we need to set up a new Zdog.Font object with the .ttf url for our desired font, then we can create a new Zdog.Text object and add it to the illustration like any other shape:

// Initialize Zfont
Zfont.init(Zdog);


// Create a Zdog illustration
let illo = new Zdog.Illustration({
  element: '.zdog-canvas'
});

// Set up a font to use
let myFont = new Zdog.Font({
  src: './path/to/font.ttf'
});

// Create a text object
// This is just a Zdog.Shape object with a couple of extra parameters!
new Zdog.Text({
  addTo: illo,
  font: myFont,
  value: 'Hey, Zdog!',
  fontSize: 64,
  color: '#fff'
});

// Animation loop
function animate() {
  illo.updateRenderGraph();
  requestAnimationFrame(animate);
}
animate();

Multiline Text

Both Zdog.Text and Zdog.TextGroup support multiline text, by inserting a newline character (\n) wherever you wish to add a line break:

new Zdog.Text({
  ...
  value: 'The quick brown fox\njumps over the\nlazy zdog',
});

For better readability you may prefer to use an array of strings for the value option. In this case, each string in the array will be treated as a seperate line of text:

new Zdog.Text({
  ...
  value: [
    'The quick brown fox'
    'jumps over the',
    'lazy zdog'
  ]
});

Waiting for Fonts to Load

In most cases you don't have to worry about waiting for fonts to load, as text objects will magically pop into existence once their font is ready to use. However, the plugin also provides a Zdog.waitForFonts() utility function if you need to delay anything until all the fonts in your scene have finished loading.

For example, let's modify the animation loop from the previous example so that it doesn't begin until the fonts are ready:

// Animation loop
function animate() {
  illo.updateRenderGraph();
  requestAnimationFrame(animate);
}
// Zdog.waitForFonts() returns a Promise which is resolved once all the fonts added to the scene so far have been loaded
Zdog.waitForFonts().then(() => {
  // Once the fonts are done, start the animation loop
  animate();
})

API

Zdog.Font

Represents a font that can be used by an instance of either Zdog.Text or Zdog.TextGroup.

let font = new Zdog.Font({
  src: './path/to/font.ttf'
})

Options

Param Details Default
src Font URL path. This can be a .ttf or .otf font, check out the Typr.js repo for more details about font support ''

Methods

measureText(text, fontSize)

Get the measurements for the specified string text when rendered at fontSize (measured in pixels), similar to Canvas​Rendering​Context2D.measure​Text().

Returns an object with width, height, descender, ascender.

getTextPath(text, fontSize, x=0, y=0, z=0, alignX='left', alignY='bottom')

Returns an array of Zdog path commands for the specified string text, when rendered at fontSize (measured in pixels).

  • (x, y, z) is the origin point of the path
  • alignX is the horizontal text alignment (equivalent to the CSS text-align property); either "left", "center" or "right".
  • alignY is the vertical text alignment; either "top", "middle" or "bottom".
waitForLoad()

Returns a Promise which resolves once this font has finished loading.

Zdog.Text

An object used for rendering text. It inherits everything from the Zdog.Shape class.

new Zdog.Text({
  addTo: illo,
  font: font,
  value: 'Hey, Zdog!',
  textAlign: 'center',
  textBaseline: 'middle',
  color: '#5222ee',
  stroke: 1,
})

Options

Zdog.Text inherits all the options from the Zdog.Shape class, plus a couple of extras:

Param Details Default
font Zdog.Font to use for this text. This is required. null
value Text string ''
fontSize Text size, measured in pixels 64
textAlign Horizontal text alignment, equivalent to the CSS text-align property. This can be either 'left', 'center' or 'right' 'left'
textBaseline Vertical text alignment, equivalent to the HTML5 canvas' textBaseline property. This can be either 'top', 'middle' or 'bottom' 'bottom'

Properties

Zdog.Text inherits all the properties from the Zdog.Shape class, as well as some extras. All of these properties can be updated at any time and the rendered text will update automatically.

font

The Zdog.Font instance being used for this text.

value

Text value as a string.

fontSize

Font size, measured in pixels.

textAlign

Horizontal text alignment, equivalent to the CSS text-align property. This can be either 'left', 'center' or 'right'

textBaseline

Vertical text alignment, equivalent to the HTML5 canvas' textBaseline property. This can be either 'top', 'middle' or 'bottom'

Zdog.TextGroup

This class is very similar to Zdog.Text, except it acts as a Zdog.Group instead, and each text glyph is rendered as its own shape. This is helpful for more advanced use-cases where you need control over each character.

new Zdog.TextGroup({
  addTo: illo,
  font: font,
  value: 'Hey, Zdog!',
  textAlign: 'center',
  color: '#5222ee',
  stroke: 2,
})

Options

Zdog.TextGroup inherits all the options from the Zdog.Group class, plus a few extras:

Param Details Default
font Zdog.Font to use for this text. This is required. null
value Text string ''
fontSize Text size, measured in pixels 64
textAlign Horizontal text alignment, equivalent to the CSS text-align property. This can be either 'left', 'center' or 'right' 'left'
textBaseline Vertical text alignment, equivalent to the HTML5 canvas' textBaseline property. This can be either 'top', 'middle' or 'bottom' 'bottom'
color Text color #333
fill Text fill false
stroke Text stroke stroke

Properties

Zdog.TextGroup inherits all the properties from the Zdog.Group class, as well as some extras. All of these properties can be updated at any time and the rendered text will update automatically.

font

The Zdog.Font instance being used for this text.

value

Text value as a string.

fontSize

Font size, measured in pixels.

textAlign

Horizontal text alignment, equivalent to the CSS text-align property. This can be either 'left', 'center' or 'right'

textBaseline

Vertical text alignment, equivalent to the HTML5 canvas' textBaseline property. This can be either 'top', 'middle' or 'bottom'

color

Text color, equivalent to Shape.color. Setting this will update the color for all of the group's children.

fill

Text fill, equivalent to Shape.fill. Setting this will update the fill for all of the group's children.

stroke

Text stroke, equivalent to Shape.stroke. Setting this will update the stroke for all of the group's children.

Zdog.waitForFonts

Returns a Promise which resolves as soon as all the fonts currently added to the scene are loaded and ready for use.

Zdog.waitForFonts().then(function() {
  // Do something once the font is ready
}

Todo

  • Google Fonts & Typekit integration?
  • Support for different text directions, e.g. right-to-left
  • Support for fallback fonts
  • Support for color (SVG) fonts

Building

Install Dependencies with NPM

$ npm install

Run Devserver

$ npm start

Build production files

$ npm run build

2019 James Daniel

More Repositories

1

iro.js

🎨 Modular color picker widget for JavaScript, with support for a bunch of color formats
JavaScript
1,303
star
2

playdate-reverse-engineering

Panic Playdate reverse-engineering notes/tools - covers file formats, server API and USB commands
Python
148
star
3

flipnote-player

🎬 Web player and video converter for animations made with Flipnote Studio; an animation app for the Nintendo DSi and 3DS
JavaScript
113
star
4

playnote-studio

An unofficial Flipnote Studio animation player for the Playdate console!
Lua
85
star
5

flipnote.js

JS library for decoding, converting, and in-browser playback of animations created with Nintendo's Flipnote Studio and Flipnote Studio 3D apps
TypeScript
68
star
6

dreams-api

API proxy & network reverse-engineering notes for Media Molecule's "Dreams" game
TypeScript
29
star
7

mii-assets

Extract textures and meshes from Nintendo's Mii rendering library
Python
24
star
8

fakenote-studio

Design files, assets and notes from the Flipnote Switch mockup that was part of our community's 2020 April Fools prank.
24
star
9

game-builder-garage-editor

(WIP) Experimental save editor for Nintendo's Game Builder Garage
TypeScript
22
star
10

pd-usb

JavaScript library for interacting with a Panic Playdate console over USB, wherever WebSerial is supported.
TypeScript
22
star
11

nx-hbmenu-mockup

design mockups and assets (including icons, color swatches, etc) for the nintendo switch homebrew menu
16
star
12

gb-operator-reverse-engineering

Reverse engineering notes for Epilogue's GB Operator
11
star
13

flipnote-video

Command-line tool and Node.js library for converting Flipnote Studio and Flipnote Studio 3D animations to video
JavaScript
10
star
14

flipclip

Web tool for converting Flipnote animations to the Clipnote file format
JavaScript
10
star
15

colors-drw-parser

Experiment in parsing/rendering the .drw painting format used by the Colors! art application for 3DS, iOS, Android and PS Vita
TypeScript
9
star
16

pdbug

Debug overlay utility for Lua-based Playdate games
Lua
9
star
17

flipnote-audio-tool

Tool for debugging audio from Flipnote Studio 3D's DSi Library notes
TypeScript
7
star
18

bitmap.scss

.bmp image encoder and a 2D raster drawing API implemented entirely in SCSS/SASS
CSS
6
star
19

kakimasu

Web-based reference app for people learning how to write Japanese
Vue
6
star
20

ugoFormats

JavaScript API for parsing and rendering the proprietary image and menu formats used by Flipnote Hatena
JavaScript
5
star
21

spriteFX

super fast image effects for javascript
JavaScript
5
star
22

labs

Setups and notes from the various animation experiments (and maybe other things) that I make for fun
5
star
23

playupdate

A bot that periodically checks for Playdate firmware updates and notifies a Discord channel when a new one is detected
TypeScript
3
star
24

pvr-model-extractor

Python decompiler for the .pod model format used in some of Nintendo's mobile games
Python
2
star
25

baba-levels

Browse user-created levels from the new Baba Is You level editor update, on the web!
Svelte
2
star
26

framer-easing-gradients

Enhance your Framer X gradients with non-linear color mixing and custom color spaces
TypeScript
1
star
27

jpeg-dot-biz

i realised i own the domain jpeg.biz so i am putting it to good use
HTML
1
star