API Documentation for: 1.0.0
Show:

FontLoader Class

Extends AbstractLoader
Defined in: FontLoader:41
Module: PreloadJS

A loader that handles font files, CSS definitions, and CSS paths. FontLoader doesn't actually preload fonts themselves, but rather generates CSS definitions, and then tests the size changes on an HTML5 Canvas element.

Note that FontLoader does not support tag-based loading due to the requirement that CSS be read to determine the font definitions to test for.

Constructor

FontLoader

(
  • loadItem
)

Defined in FontLoader:41

Parameters:

Methods

_calculateReferenceSizes

(
  • def
)
protected

Determine the default size of the reference fonts used to compare against loaded fonts.

Parameters:

  • def Object

    The font definition to get the size of.

_createRequest

() protected

Create an internal request used for loading. By default, an XHRRequest or TagRequest is created, depending on the value of PreferXHR:property. Other loaders may override this to use different request types, such as ManifestLoader, which uses JSONLoader or JSONPLoader under the hood.

_createTag

(
  • src
)
HTMLElement protected

Inherited from AbstractLoader: _createTag:425

Create the HTML tag used for loading. This method does nothing by default, and needs to be implemented by loaders that require tag loading.

Parameters:

Returns:

HTMLElement:

The tag that was created

_cssFromDef

(
  • def
)
String protected

Defined in _cssFromDef:528

Get CSS from a font definition.

Parameters:

  • def Object

    A font definition

Returns:

String:

A CSS string representing the object

_defFromObj

(
  • o
)
Object protected

Defined in _defFromObj:510

Get a font definition from a raw font object.

Parameters:

  • o Object

    A raw object provided to the FontLoader

Returns:

Object:

A standard font object that the FontLoader understands

_defFromSrc

(
  • src
)
protected

Defined in _defFromSrc:461

Get a CSS definition from a font source and name.

Parameters:

_dispatchEvent

(
  • eventObj
  • eventPhase
)
protected

Parameters:

_getCSSValue

(
  • str
  • propName
)
String protected

Defined in _getCSSValue:559

Get the value of a property from a CSS string. For example, searches a CSS string for the value of the "font-family" property.

Parameters:

  • str String

    The CSS string to search

  • propName String

    The property name to get the value for

Returns:

String:

The value in the CSS for the provided property name

_getTextWidth

(
  • family
  • weight
  • style
)
Number protected

Defined in _getTextWidth:544

Get the text width of text using the family, weight, and style

Parameters:

Returns:

Number:

The pixel measurement of the font.

_handleTimeout

() protected

Defined in _handleTimeout:237

The font load has timed out. This is called via a setTimeout. callback.

_injectStyleTag

(
  • css
)
protected

Defined in _injectStyleTag:331

Inject any style definitions into the document head. This is necessary when the definition is just a string or object definition in order for the styles to be applied to the document. If the loaded fonts are already HTML CSS elements, they don't need to be appended again.

Parameters:

  • css String

    The CSS string content to be appended to the

_isCanceled

() Boolean protected

Determine if the load has been canceled. This is important to ensure that method calls or asynchronous events do not cause issues after the queue has been cleaned up.

Returns:

Boolean:

If the loader has been canceled.

_parseCSS

(
  • css
)
protected

Defined in _parseCSS:298

Parse a CSS string to determine the fonts to load.

Parameters:

  • css String

    The CSS string to parse

_parseFontFace

(
  • str
)
String protected

Defined in _parseFontFace:352

Determine the font face from a CSS definition.

Parameters:

  • str String

    The CSS string definition

Returns:

String:

A modified CSS object containing family name, src, style, and weight

_resultFormatSuccess

(
  • result
)
private

Inherited from AbstractLoader but overwritten in _resultFormatSuccess:568

The "success" callback passed to AbstractLoader/resultFormatter asynchronous functions.

Parameters:

  • result Object

    The formatted result

_sendComplete

() protected

Dispatch a complete Event. Please see the complete event

_sendError

(
  • event
)
protected

Inherited from AbstractLoader: _sendError:488

Dispatch an error Event. Please see the error event for details on the event payload.

Parameters:

  • event ErrorEvent

    The event object containing specific error properties.

_sendLoadStart

() protected

Dispatch a loadstart Event. Please see the loadstart event for details on the event payload.

_sendProgress

(
  • value
)
protected

Dispatch a ProgressEvent.

Parameters:

  • value Number | Object

    The progress of the loaded item, or an object containing loaded and total properties.

_startWatching

() protected

Defined in _startWatching:387

Create a interval to check for loaded fonts. Only one interval is used for all fonts. The fonts are checked based on the WATCH_DURATION.

_stopWatching

() protected

Defined in _stopWatching:398

Clear the interval used to check fonts. This happens when all fonts are loaded, or an error occurs, such as a CSS file error, or a load timeout.

_watch

() protected

Defined in _watch:410

Check all the fonts that have not been loaded. The fonts are drawn to a canvas in memory, and if their font size varies from the default text size, then the font is considered loaded.

A AbstractLoader/fileload event will be dispatched when each file is loaded, along with the font family name as the item value. A ProgressEvent is dispatched a maximum of one time per check when any fonts are loaded, with the progress value showing the percentage of fonts that have loaded.

_watchCSS

() Boolean protected

Defined in _watchCSS:270

Determine if the provided CSS is a string definition, CSS HTML element, or a CSS file URI. Depending on the format, the CSS will be parsed, or loaded.

Returns:

Boolean:

Whether or not the CSS is ready

_watchFont

(
  • def
)
protected

Defined in _watchFont:370

Add a font to the list of fonts currently being watched. If the font is already watched or loaded, it won't be added again.

Parameters:

  • def Object

    The font definition

_watchFontArray

() protected

Defined in _watchFontArray:314

The provided fonts were an array of object or string definitions. Parse them, and inject any that are ready.

addEventListener

(
  • type
  • listener
  • [useCapture]
)
Function | Object

Adds the specified event listener. Note that adding multiple listeners to the same function will result in multiple callbacks getting fired.

Example

 displayObject.addEventListener("click", handleClick);
 function handleClick(event) {
    // Click happened.
 }

Parameters:

  • type String

    The string type of the event.

  • listener Function | Object

    An object with a handleEvent method, or a function that will be called when the event is dispatched.

  • [useCapture] Boolean optional

    For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.

Returns:

Function | Object:

Returns the listener for chaining or assignment.

cancel

()

Inherited from AbstractLoader: cancel:365

Close the the item. This will stop any open requests (although downloads using HTML tags may still continue in the background), but events will not longer be dispatched.

canLoadItem

(
  • item
)
Boolean static

Defined in canLoadItem:110

Determines if the loader can load a specific item. This loader can only load items that are of type FONT.

Parameters:

  • item LoadItem | Object

    The LoadItem that a LoadQueue is trying to load.

Returns:

Boolean:

Whether the loader can load the item.

destroy

()

Inherited from AbstractLoader: destroy:375

Clean up the loader.

dispatchEvent

(
  • eventObj
  • [bubbles]
  • [cancelable]
)
Boolean

Dispatches the specified event to all listeners.

Example

 // Use a string event
 this.dispatchEvent("complete");

 // Use an Event instance
 var event = new createjs.Event("progress");
 this.dispatchEvent(event);

Parameters:

  • eventObj Object | String | Event

    An object with a "type" property, or a string type. While a generic object will work, it is recommended to use a CreateJS Event instance. If a string is used, dispatchEvent will construct an Event instance if necessary with the specified type. This latter approach can be used to avoid event object instantiation for non-bubbling events that may not have any listeners.

  • [bubbles] Boolean optional

    Specifies the bubbles value when a string was passed to eventObj.

  • [cancelable] Boolean optional

    Specifies the cancelable value when a string was passed to eventObj.

Returns:

Boolean:

Returns false if preventDefault() was called on a cancelable event, true otherwise.

getItem

() Object

Inherited from AbstractLoader: getItem:290

Available since 0.6.0

Get a reference to the manifest item that is loaded by this loader. In some cases this will be the value that was passed into LoadQueue using loadFile or loadManifest. However if only a String path was passed in, then it will be a LoadItem.

Returns:

Object:

The manifest item that this loader is responsible for loading.

getLoadedItems

() Array

Inherited from AbstractLoader: getLoadedItems:396

Available since 0.6.0

Get any items loaded internally by the loader. The enables loaders such as ManifestLoader to expose items it loads internally.

Returns:

Array:

A list of the items loaded by the loader.

getResult

(
  • [raw=false]
)
Object

Inherited from AbstractLoader: getResult:303

Available since 0.6.0

Get a reference to the content that was loaded by the loader (only available after the Complete:event event is dispatched.

Parameters:

  • [raw=false] Boolean optional

    Determines if the returned result will be the formatted content, or the raw loaded data (if it exists).

Returns:

getTag

() Object

Inherited from AbstractLoader: getTag:316

Available since 0.6.0

Return the tag this object creates or uses for loading.

Returns:

Object:

The tag instance

handleEvent

(
  • event
)
protected

Inherited from AbstractLoader: handleEvent:525

Available since 0.6.0

Handle events from internal requests. By default, loaders will handle, and redispatch the necessary events, but this method can be overridden for custom behaviours.

Parameters:

  • event Event

    The event that the internal request dispatches.

hasEventListener

(
  • type
)
Boolean

Indicates whether there is at least one listener for the specified event type.

Parameters:

  • type String

    The string type of the event.

Returns:

Boolean:

Returns true if there is at least one listener for the specified event.

load

()

Inherited from AbstractLoader: load:336

Begin loading the item. This method is required when using a loader by itself.

Example

 var queue = new createjs.LoadQueue();
 queue.on("complete", handleComplete);
 queue.loadManifest(fileArray, false); // Note the 2nd argument that tells the queue not to start loading yet
 queue.load();

off

(
  • type
  • listener
  • [useCapture]
)

Inherited from EventDispatcher: off:249

A shortcut to the removeEventListener method, with the same parameters and return value. This is a companion to the .on method.

IMPORTANT: To remove a listener added with on, you must pass in the returned wrapper function as the listener. See on for an example.

Parameters:

  • type String

    The string type of the event.

  • listener Function | Object

    The listener function or object.

  • [useCapture] Boolean optional

    For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.

on

(
  • type
  • listener
  • [scope]
  • [once=false]
  • [data]
  • [useCapture=false]
)
Function

Inherited from EventDispatcher: on:173

A shortcut method for using addEventListener that makes it easier to specify an execution scope, have a listener only run once, associate arbitrary data with the listener, and remove the listener.

This method works by creating an anonymous wrapper function and subscribing it with addEventListener. The wrapper function is returned for use with removeEventListener (or off).

IMPORTANT: To remove a listener added with on, you must pass in the returned wrapper function as the listener, or use remove. Likewise, each time you call on a NEW wrapper function is subscribed, so multiple calls to on with the same params will create multiple listeners.

Example

    var listener = myBtn.on("click", handleClick, null, false, {count:3});
    function handleClick(evt, data) {
        data.count -= 1;
        console.log(this == myBtn); // true - scope defaults to the dispatcher
        if (data.count == 0) {
            alert("clicked 3 times!");
            myBtn.off("click", listener);
            // alternately: evt.remove();
        }
    }

Parameters:

  • type String

    The string type of the event.

  • listener Function | Object

    An object with a handleEvent method, or a function that will be called when the event is dispatched.

  • [scope] Object optional

    The scope to execute the listener in. Defaults to the dispatcher/currentTarget for function listeners, and to the listener itself for object listeners (ie. using handleEvent).

  • [once=false] Boolean optional

    If true, the listener will remove itself after the first time it is triggered.

  • [data] optional

    Arbitrary data that will be included as the second parameter when the listener is called.

  • [useCapture=false] Boolean optional

    For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.

Returns:

Function:

Returns the anonymous function that was created and assigned as the listener. This is needed to remove the listener later using .removeEventListener.

removeAllEventListeners

(
  • [type]
)

Removes all listeners for the specified type, or all listeners of all types.

Example

 // Remove all listeners
 displayObject.removeAllEventListeners();

 // Remove all click listeners
 displayObject.removeAllEventListeners("click");

Parameters:

  • [type] String optional

    The string type of the event. If omitted, all listeners for all types will be removed.

removeEventListener

(
  • type
  • listener
  • [useCapture]
)

Removes the specified event listener.

Important Note: that you must pass the exact function reference used when the event was added. If a proxy function, or function closure is used as the callback, the proxy/closure reference must be used - a new proxy or closure will not work.

Example

 displayObject.removeEventListener("click", handleClick);

Parameters:

  • type String

    The string type of the event.

  • listener Function | Object

    The listener function or object.

  • [useCapture] Boolean optional

    For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.

setTag

(
  • tag
)

Inherited from AbstractLoader: setTag:326

Available since 0.6.0

Set the tag this item uses for loading.

Parameters:

toString

() String

Inherited from EventDispatcher but overwritten in toString:591

Returns:

String:

a string representation of the instance.

willTrigger

(
  • type
)
Boolean

Indicates whether there is at least one listener for the specified event type on this object or any of its ancestors (parent, parent's parent, etc). A return value of true indicates that if a bubbling event of the specified type is dispatched from this object, it will trigger at least one listener.

This is similar to hasEventListener, but it searches the entire event flow for a listener, not just this object.

Parameters:

  • type String

    The string type of the event.

Returns:

Boolean:

Returns true if there is at least one listener for the specified event.

Properties

_captureListeners

Object protected

_count

Number protected

Defined in _count:73

A count of the total font faces to load.

Default: 0

_ctx

CanvasRenderingContext2D private static

Defined in _ctx:134

The canvas context used to test the font size. Note that this currently requires an HTML DOM.

_faces

Object protected

Defined in _faces:56

A lookup of font faces to load.

_injectCSS

Boolean protected

Defined in _injectCSS:98

Determines if generated CSS should be injected into the document.

_item

LoadItem | Object private

Inherited from AbstractLoader: _item:127

The LoadItem this loader represents. Note that this is null in a LoadQueue, but will be available on loaders such as XMLLoader and ImageLoader.

_listeners

Object protected

Inherited from EventDispatcher: _listeners:99

_loadItems

Null protected

Inherited from AbstractLoader: _loadItems:167

A list of items that loaders load behind the scenes. This does not include the main item the loader is responsible for loading. Examples of loaders that have sub-items include the SpriteSheetLoader and ManifestLoader.

_loadTimeout

Number protected

Defined in _loadTimeout:90

The timeout for determining if a font can't be loaded. Uses the LoadItem LoadImte/timeout:property value.

_preferXHR

Boolean private

Inherited from AbstractLoader: _preferXHR:140

Whether the loader will try and load content using XHR (true) or HTML tags (false).

_rawResult

Object | String private

Inherited from AbstractLoader: _rawResult:158

The loaded result before it is formatted. The rawResult is accessed using the GetResult method, and passing true.

_referenceFonts

Array private

Defined in _referenceFonts:143

A list of reference fonts to test. Multiple faces are tested to address the rare case of a loaded font being the exact same dimensions as the test font.

Default: ["serif", "monospace"]

_result

Object | String private

Inherited from AbstractLoader: _result:148

The loaded result after it is formatted by an optional ResultFormatter. For items that are not formatted, this will be the same as the _rawResult:property. The result is accessed using the GetResult method.

_tag

Object private

Inherited from AbstractLoader: _tag:185

An HTML tag (or similar) that a loader may use to load HTML content, such as images, scripts, etc.

_watchInterval

Number protected

Defined in _watchInterval:82

The interval for checking if fonts have been loaded.

canceled

Boolean readonly

Inherited from AbstractLoader: canceled:66

Determine if the loader was canceled. Canceled loads will not fire complete events. Note that this property is readonly, so LoadQueue queues should be closed using close instead.

Default: false

FONT_FORMAT

Object static

Defined in FONT_FORMAT:189

A lookup of font types for generating a CSS definition. For example, TTF fonts requires a "truetype" type.

FONT_WEIGHT

Object static

Defined in FONT_WEIGHT:197

A lookup of font weights based on a name. These values are from http://www.w3.org/TR/css3-fonts/#font-weight-numeric-values.

loaded

Boolean

Inherited from AbstractLoader: loaded:57

If the loader has completed loading. This provides a quick check, but also ensures that the different approaches used for loading do not pile up resulting in more than one complete Event.

Default: false

progress

Number

Inherited from AbstractLoader: progress:77

The current load progress (percentage) for this item. This will be a number between 0 and 1.

Example

var queue = new createjs.LoadQueue();
queue.loadFile("largeImage.png");
queue.on("progress", function() {
    console.log("Progress:", queue.progress, event.progress);
});

Default: 0

resultFormatter

Function

Inherited from AbstractLoader but overwritten in resultFormatter:102

A formatter function that converts the loaded raw result into the final result. For example, the JSONLoader converts a string of text into a JavaScript object. Not all loaders have a resultFormatter, and this property can be overridden to provide custom formatting.

Optionally, a resultFormatter can return a callback function in cases where the formatting needs to be asynchronous, such as creating a new image. The callback function is passed 2 parameters, which are callbacks to handle success and error conditions in the resultFormatter. Note that the resultFormatter method is called in the current scope, as well as the success and error callbacks.

Example asynchronous resultFormatter

function _formatResult(loader) {
    return function(success, error) {
        if (errorCondition) { error(errorDetailEvent); }
        success(result);
    }
}

Default: null

sampleText

String private static

Defined in sampleText:123

Sample text used by the FontLoader to determine if the font has been loaded. The sample text size is compared to the loaded font size, and a change indicates that the font has completed.

Default: abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ

STYLE_REGEX

RegExp static

Defined in STYLE_REGEX:180

A regular expression that pulls out possible style values from the font name. These include "italic" and "oblique".

type

String

Inherited from AbstractLoader: type:94

The type of item this loader will load. See AbstractLoader for a full list of supported types.

WATCH_DURATION

Number static

Defined in WATCH_DURATION:205

The frequency in milliseconds to check for loaded fonts.

Default: 10

WEIGHT_REGEX

RegExp static

Defined in WEIGHT_REGEX:153

A regular expression that pulls out possible style values from the font name.

  • This includes font names that include thin, normal, book, regular, medium, black, and heavy (such as "Arial Black")
  • Weight modifiers including extra, ultra, semi, demi, light, and bold (such as "WorkSans SemiBold")

Weight descriptions map to font weight values by default using the following (from http://www.w3.org/TR/css3-fonts/#font-weight-numeric-values):

  • 100 - Thin
  • 200 - Extra Light, Ultra Light
  • 300 - Light, Semi Light, Demi Light
  • 400 - Normal, Book, Regular
  • 500 - Medium
  • 600 - Semi Bold, Demi Bold
  • 700 - Bold
  • 800 - Extra Bold, Ultra Bold
  • 900 - Black, Heavy

Events

complete

Inherited from AbstractLoader: complete:237

Available since 0.3.0

The Event that is fired when the entire queue has been loaded.

Event Payload:

  • target Object

    The object that dispatched the event.

  • type String

    The event type.

error

Inherited from AbstractLoader: error:245

Available since 0.3.0

The ErrorEvent that is fired when the loader encounters an error. If the error was encountered by a file, the event will contain the item that caused the error. Prior to version 0.6.0, this was just a regular Event.

fileerror

Inherited from AbstractLoader: fileerror:253

Available since 0.6.0

The Event that is fired when the loader encounters an internal file load error. This enables loaders to maintain internal queues, and surface file load errors.

Event Payload:

  • target Object

    The object that dispatched the event.

  • type String

    The event type ("fileerror")

  • The LoadItem | Object

    item that encountered the error

fileload

Inherited from AbstractLoader: fileload:263

Available since 0.6.0

The Event that is fired when a loader internally loads a file. This enables loaders such as ManifestLoader to maintain internal LoadQueues and notify when they have loaded a file. The LoadQueue class dispatches a slightly different fileload event.

Event Payload:

  • target Object

    The object that dispatched the event.

  • type String

    The event type ("fileload")

  • item Object

    The file item which was specified in the loadFile or loadManifest call. If only a string path or tag was specified, the object will contain that value as a src property.

  • result Object

    The HTML tag or parsed result of the loaded item.

  • rawResult Object

    The unprocessed result, usually the raw text or binary data before it is converted to a usable object.

initialize

Inherited from AbstractLoader: initialize:280

The Event that is fired after the internal request is created, but before a load. This allows updates to the loader for specific loading needs, such as binary or XHR image loading.

Event Payload:

  • target Object

    The object that dispatched the event.

  • type String

    The event type ("initialize")

  • loader AbstractLoader

    The loader that has been initialized.

loadstart

Inherited from AbstractLoader: loadstart:229

Available since 0.3.1

The Event that is fired when a load starts.

Event Payload:

  • target Object

    The object that dispatched the event.

  • type String

    The event type.

progress

Inherited from AbstractLoader: progress:222

Available since 0.3.0

The ProgressEvent that is fired when the overall progress changes. Prior to version 0.6.0, this was just a regular Event.