API Docs for: 6.0.1
Show:

window.scrawl Class

Module: scrawlCore

window.scrawl

The Scrawl library object. All objects, attributes and functions contained in the library can be accessed by any other JavaScript code running on the web page.

The library will expand and change as Scrawl extensions load.

Purpose:

  • Holds links to every substantive object created by Scrawl.js and user code
  • Also holds links to key DOM objects
  • Functions for loading canvas elements on initialization, and for dynamically creating canvases on the web page
  • Shorthand functions for rendering canvases
  • Some general helper functions for testing variables that can be used by coders

Core creates the following sections in the library:

  • scrawl.object - Contains key:value pairs for storing miscellaneous objects, for instance handles to DOM image elements imported into scrawl via scrawl.getImagesByClass()
  • scrawl.pad - Contains PADNAME:Object pairs for each instantiated Pad canvas controller object
  • scrawl.cell - Contains CELLNAME:Object pairs for each instantiated Cell canvas wrapper object
  • scrawl.canvas - Contains CELLNAME:object pairs linking to each Cell object's DOM <canvas> element
  • scrawl.context - Contains CELLNAME:Object pairs linking to each <canvas> element's context engine
  • scrawl.ctx - Contains CONTEXTNAME:Object pairs linking to each instantiated Scrawl Context object (used by Cell and Entity objects)
  • scrawl.imageData - Contains key:value pairs linking to JavaScript image data objects
  • scrawl.group - Contains GROUPNAME:Object pairs linking to each instantiated Group object
  • scrawl.design - Contains DESIGNNAME:Object pairs for each instantiated design object (Gradient, RadialGradient, Pattern, Color)
  • scrawl.dsn - Contains DESIGNNAME:precompiled gradient/pattern context object pairs (Gradient, RadialGradient, Pattern)
  • scrawl.entity - Contains SPRITENAME:Object pairs for each instantiated entity object (Block, Phrase, Picture, Wheel, Path, Shape, Particle)

Methods

addCanvasToPage

(
  • items
)

A general function to add a visible <canvas> element to the web page, and create a Pad controller and Cell wrappers for it

The argument object should include the following attributes:

  • stackName (String) - STACKNAME of existing or new stack (optional)
  • parentElement - (String) CSS #id of parent element, or the DOM element itself; default: document.body
  • any other legitimate Pad and/or Cell object attribute

(This function is replaced by the scrawlStacks extension)

Parameters:

  • items Object

    Object containing new Cell's parameters

Returns:

The new Pad object

Example:

<body>
    <div id="canvasholder"></div>
    <script src="js/scrawlCore-min.js"></script>
    <script>
        scrawl.addCanvasToPage({
            name:   'mycanvas',
            parentElement: 'canvasholder',
            width: 400,
            height: 200,
            }).makeCurrent();
    </script>
</body>

addEntitysToGroups

(
  • groups
  • entitys
)
chainable

A general function which adds supplied entitynames to Group.entitys attribute

Parameters:

  • groups Array

    Array of GROUPNAME Strings - can also be a String

  • entitys Array

    Array of SPRITENAME Strings - can also be a String

Returns:

The Scrawl library object (scrawl)

addListener

(
  • evt
  • fn
  • targ
)

Adds event listeners to the element

Parameters:

  • evt String
    • or an Array of Strings from: 'up', 'down', 'enter', 'leave', 'move'
  • fn Function
    • function to be called when event triggers
  • targ String
    • either a querySelectorAll string, or a DOM element, or an Array of DOM elements

Returns:

always true

addNativeListener

(
  • evt
  • fn
  • targ
)

A utility function for adding JavaScript event listeners to multiple elements

Parameters:

  • evt String
    • or an Array of Strings
  • fn Function
    • function to be called when event triggers
  • targ String
    • either a querySelectorAll string, or a DOM element, or an Array of DOM elements

Returns:

always true

addNativeListener

(
  • evt
  • fn
  • targ
)

A utility function for adding JavaScript event listeners to multiple elements

Parameters:

  • evt String
    • or an Array of Strings
  • fn Function
    • function to be called when event triggers
  • targ String
    • either a querySelectorAll string, or a DOM element, or an Array of DOM elements

Returns:

always true

addNewCell

(
  • data
  • pad
)

A general function which passes on requests to Pads to generate new <canvas> elements and associated objects - see Pad.addNewCell() for more details

Parameters:

  • data Object

    Initial attribute values for new object

  • pad String

    PADNAME

Returns:

New Cell object

addPercentages

(
  • a
  • b
)

A utility function to add two percent strings together

Parameters:

  • a String
    • first value
  • b String
    • second value

Returns:

String result

bucketSort

(
  • section
  • attribute
  • a
)
private

A utility function for performing bucket sorts on scrawl string arrays eg Group.entitys

Parameters:

  • section String

    scrawl library section name

  • attribute String

    on which sort will be performed

  • a Array

    array to be sorted

Returns:

sorted array

checkForPromise

() private

A general function that checks to see if the Promise API is supported by the browser

Returns:

true if Promise is supported natively; false otherwise

clear

(
  • [pads]
)
chainable

A display function to ask Pads to get their Cells to clear their <canvas> elements

Parameters:

  • [pads] Array optional

    Array of PADNAMEs - can also be a String

Returns:

The Scrawl library object (scrawl)

cloneTouchEventItem

() private

A custom event listener helper function

compile

(
  • [pads]
  • [mouse]
)
chainable

A display function to ask Pads to get their Cells to compile their scenes

Parameters:

  • [pads] Array optional

    Array of PADNAMEs - can also be a String

  • [mouse] Vector optional

    coordinates to be used for any entity currently pivoted to a mouse/touch event

Returns:

The Scrawl library object (scrawl)

contains

(
  • item
  • k
)

A utility function that checks an array to see if it contains a given value

Parameters:

  • item Array

    Reference array

  • k Mixed

    value to be checked

Returns:

True if value is in array; false otherwise

Example:

var myarray = ['apple', 'orange'];
scrawl.contains(myarray, 'apple');  //true
scrawl.contains(myarray, 'banana'); //false

correctCoordinates

(
  • coords
  • [cell]
)

General helper function - correct mouse coordinates if pad dimensions not equal to base cell dimensions

Parameters:

  • coords Object

    An object containing x and y attributes

  • [cell] String optional

    CELLNAME String

Returns:

Amended coordinate object; false on error

deleteCells

(
  • cells
)
chainable

A general function which deletes Cell objects and their associated paraphinalia - see Pad.deleteCells() for more details

Parameters:

  • cells Array

    Array of CELLNAMEs - can also be a String

Returns:

The Scrawl library object (scrawl)

deleteEntity

(
  • items
)
chainable

A general function to delete entity objects

Parameters:

  • items Array

    Array of SPRITENAME Strings - can also be a String

Returns:

The Scrawl library object (scrawl)

Example:

scrawl.makeBlock({
    name: 'myblock',
    });
scrawl.deleteEntity(['myblock']);

filtersInit

() private

scrawl.init hook function - modified by filters extension

getCanvases

() private

A private function that searches the DOM for canvas elements and generates Pad/Cell/Context objects for each of them

(This function is replaced by the scrawlStacks extension)

Returns:

True on success; false otherwise

init

() chainable

A general function that initializes (or resets) the Scrawl library and populates it with data, including existing <canvas> element data in the web page

Returns:

The Scrawl library object (scrawl)

Example:

scrawl.init();

isa

(
  • item
  • identifier
)

A utility function for variable type checking

Valid identifier Strings include:

  • num for numbers
  • str for strings
  • bool for booleans
  • fn for Function objects
  • arr for Array objects
  • obj for Object objects (excluding DOM objects)
  • dom for DOM objects
  • event for DOM event objects
  • date for Date objects
  • vector for Scrawl Vector objects
  • quaternion for Scrawl Quaternion objects

Parameters:

  • item Mixed

    Primative or object for identification

  • identifier String

    Identifier String

Returns:

True if item type matches the identifier

Example:

var mystring = 'string',
    myboolean = false;
scrawl.isa(mystring, 'bool');   //returns false
scrawl.isa(mystring, 'str');    //returns true
scrawl.isa(myboolean, 'bool');  //returns true
scrawl.isa(myboolean, 'str');   //returns false

isBetween

(
  • no
  • a
  • b
  • [e]
)

A utility function that checks to see if a number is between two other numbers

Parameters:

  • no Number

    Reference number

  • a Number

    Minimum or maximum number

  • b Number

    Maximum or minimum number

  • [e] Boolean optional

    If true, reference number can equal maximum/minimum number; on false, number must lie between the maximum and minimum (default: false)

Returns:

True if value is between maximum and minimum; false otherwise

Example:

scrawl.isBetween(3, 1, 5);          //returns true
scrawl.isBetween(3, 3, 5);          //returns false
scrawl.isBetween(3, 3, 5, true);    //returns true

loadExtensions

(
  • items
)
chainable

A general function that loads supporting extensions and integrates them into the core

Extension names are supplied as an array of Strings, each of which should be an alias string, as follows:

Scrawl currently supports the following extensions:

  • scrawlAnimation.js - alias animation - adds animation and tween functionality to the core
  • scrawlBlock.js - alias block - adds Block (square and rectangle) entitys to the core
  • scrawlCollisions.js - alias collisions - adds entity collision detection functionality to the core
  • scrawlColor.js - alias color - adds the Color Design object to the core
  • scrawlFilters.js - alias filters - adds image filter functionality to the core
  • scrawlFrame.js - alias frame - enhanced Picture entity
  • scrawlImages.js - alias images - adds all image functionality, including static and animated Picture entitys and the Pattern Design object, to the core
  • scrawlPath.js - alias path - adds Path (SVGTiny path data) entitys to the core
  • scrawlPathFactories.js - alias factories - adds user-friendly Path and Shape factory functions (for lines, quadratic and bezier curves, ellipses, round-corner rectangles, regular shapes such as stars, triangles, etc) to the core
  • scrawlPhrase.js - alias phrase - adds Phrase (single and multiline text) entitys to the core
  • scrawlPerspective.js - alias perspective - adds Perspective functionality to the core (experimental)
  • scrawlPhysics.js - alias physics - adds a physics engine to the core (experimental)
  • scrawlSaveLoad.js - alias saveload - adds JSON object save and load functionality to the core (experimental)
  • scrawlShape.js - alias shape - adds Shape (path-like shapes) entitys to the core
  • scrawlStacks.js - alias stacks - adds the ability to position, manipulate and animate <canvas> and other DOM elements in a 3d space on the web page
  • scrawlWheel.js - alias wheel - adds Wheel (circle and segment) entitys to the core
  • scrawlImageLoad.js - alias imageload - adds the ability to load img elements into the library
  • scrawlQuaternion.js - alias quaternion - adds quaternion maths functionality to the core

Where permitted, Scrawl will load extensions asynchronously. Extensions have no external dependencies beyond their need for the core module, and can be loaded in any order.

Any supplied callback function will only be run once all extensions have been loaded.

The argument object can include the following attributes:

  • path - String path-to-directory/folder where scrawl extension files are kept (default: '')
  • minified - Boolean - if true (default) minified extensions will be loaded; false for source extensions
  • extensions - an Array of extension alias Strings
  • callback - Function to run once all extension files have been loaded (defaults to an empty function)
  • error - Function to run if one or more extension files fails to load (defaults to an empty function)

Parameters:

  • items Object
    • JavaScript object containing key:value pairs

Returns:

The Scrawl library object (scrawl)

Example:

<!DOCTYPE html>
<html>
    <head></head>
    <body>
        <canvas></canvas>
        <script src="js/scrawlCore-min.js"></script>
        <script>
            var mycode = function(){
                scrawl.makeWheel({
                    startX: 50,
                    startY: 50,
                    radius: 40,
                    });
                scrawl.render();
                };
            scrawl.loadExtensions({
                path: 'js/',
                extensions: ['wheel'],
                callback: function(){
                    window.addEventListener('load', function(){
                        scrawl.init();
                        mycode();
                        }, false);
                    }
                });
        </script>
    </body>
</html>

loadExtensionsConcatenator

(
  • items
)
private

loadExtensions helper function

Parameters:

  • items Object
    • JavaScript object containing key:value pairs

Returns:

Array of extension aliases

loadExtensionsUsingPromise

(
  • items
)
private chainable

loadExtensions helper function - uses the new Promise api, if it is available

Parameters:

  • items Object
    • JavaScript object containing key:value pairs

Returns:

The Scrawl library object (scrawl)

loadExtensionsUsingVanilla

(
  • items
)
private chainable

loadExtensions helper function

Parameters:

  • items Object
    • JavaScript object containing key:value pairs

Returns:

The Scrawl library object (scrawl)

loadModules

(
  • items
)
deprecated chainable

A general function that loads supporting extensions and integrates them into the core

(function name changed from loadModules to loadExtensions because Scrawl 'modules' are not modules)

Parameters:

  • items Object
    • JavaScript object containing key:value pairs

Returns:

The Scrawl library object (scrawl)

makeCell

(
  • items
)
private

A factory function to generate new Cell objects

Parameters:

  • items Object

    Key:value Object argument for setting attributes

Returns:

Cell object

makeContext

(
  • items
)
private

A factory function to generate new Context objects

Parameters:

  • items Object

    Key:value Object argument for setting attributes

Returns:

Context object

makeGradient

(
  • items
)

A factory function to generate new Gradient objects

Parameters:

  • items Object

    Key:value Object argument for setting attributes

Returns:

Gradient object

makeGroup

(
  • items
)

A factory function to generate new Group objects

Parameters:

  • items Object

    Key:value Object argument for setting attributes

Returns:

Group object

makeName

(
  • [item]
)
private

Generate unique names for new Scrawl objects

Parameters:

  • [item] Object optional

    Object with attributes: name, type, target

Returns:

Unique generated name

makePad

(
  • items
)
private

A factory function to generate new Pad objects

Parameters:

  • items Object

    Key:value Object argument for setting attributes

Returns:

Pad object

makeRadialGradient

(
  • items
)

A factory function to generate new RadialGradient objects

Parameters:

  • items Object

    Key:value Object argument for setting attributes

Returns:

RadialGradient object

makeVector

(
  • items
)

A factory function to generate new Vector objects

Parameters:

  • items Object

    Key:value Object argument for setting attributes

Returns:

Vector object

Example:

var myVector = scrawl.makeVector({
    x: 100,
    y: 200,
    });

mergeInto

(
  • o1
  • o2
)

A utility function that adds the attributes of the additive object to those of the reference object, where those attributes don't already exist in the reference object

Parameters:

  • o1 Object

    reference object

  • o2 Object

    additive object

Returns:

Merged object

Example:

var old = {
        name: 'Peter',
        age: 42,
        job: 'lawyer'
        },
    new = {
        age: 32,
        job: 'coder',
        pet: 'cat'
        };
scrawl.mergeInto(old, new);
//result is {
//  name: 'Peter',
//  age: 42,
//  job: 'lawyer'
//  pet: 'cat'
//  }

mergeOver

(
  • o1
  • o2
)

A utility function that adds the attributes of the additive object to those of the reference object, overwriting attributes where necessary

Parameters:

  • o1 Object

    reference object

  • o2 Object

    additive object

Returns:

Merged object

Example:

var old = {
        name: 'Peter',
        age: 42,
        job: 'lawyer'
        },
    new = {
        age: 32,
        job: 'coder',
        pet: 'cat'
        };
scrawl.mergeOver(old, new);
//result is {
//  name: 'Peter',
//  age: 32,
//  job: 'coder'
//  pet: 'cat'
//  }

newCell

() deprecated private

Alias for makeCell()

newContext

() deprecated private

Alias for makeContext()

newGradient

() deprecated

Alias for makeGradient()

newGroup

() deprecated

Alias for makeGroup()

newPad

() deprecated private

Alias for makePad()

newRadialGradient

() deprecated

Alias for makeRadialGradient()

newVector

() deprecated

Alias for makeVector()

pageInit

() private

scrawl.init hook function - modified by stacks extension

pageInit

() private

scrawl.init hook function - modified by stacks extension

pathDeleteEntity

() private

scrawl.deleteEntity hook function - modified by path extension

physicsInit

() private

scrawl.init hook function - modified by physics extension

pushUnique

(
  • item
  • o
)

A utility function that adds a value to an array if the array doesn't already contain an element with that value

Parameters:

  • item Array

    Reference array

  • o Mixed

    value to be added to array

Returns:

Amended array

Example:

var myarray = ['apple', 'orange'];
scrawl.pushUnique(myarray, 'apple');    //returns ['apple', 'orange']
scrawl.pushUnique(myarray, 'banana');   //returns ['apple', 'orange', 'banana']

removeEntitysFromGroups

(
  • groups
  • entitys
)
chainable

A general function which removes supplied entitynames from Group.entitys attribute

Parameters:

  • groups Array

    Array of GROUPNAME Strings - can also be a String

  • entitys Array

    Array of SPRITENAME Strings - can also be a String

Returns:

The Scrawl library object (scrawl)

removeItem

(
  • item
  • o
)

A utility function that removes a value from an array

Parameters:

  • item Array

    Reference array

  • o Mixed

    value to be removed from array

Returns:

Amended array

Example:

var myarray = ['apple', 'orange'];
scrawl.removeItem(myarray, 'banana');   //returns ['apple', 'orange']
scrawl.removeItem(myarray, 'apple');    //returns ['orange']

removeListener

(
  • evt
  • fn
  • targ
)

Remove event listeners from the element

Parameters:

  • evt String
    • one from: 'up', 'down', 'enter', 'leave', 'move'
  • fn Function
    • function to be called when event triggers
  • targ String
    • either a querySelectorAll string, or a DOM element

Returns:

true on success; false otherwise

render

(
  • [pads]
  • [mouse]
)
chainable

A display function to ask Pads to undertake a complete clear-compile-show display cycle

Parameters:

  • [pads] Array optional

    Array of PADNAMEs - can also be a String

  • [mouse] Vector optional

    coordinates to be used for any entity currently pivoted to a mouse/touch event

Returns:

The Scrawl library object (scrawl)

reset

() chainable

A general function that resets the Scrawl library to empty arrays and objects

Returns:

The Scrawl library object (scrawl)

Example:

scrawl.reset();

reversePercentage

(
  • a
)

A utility function to reverse the value of a percentage string

Parameters:

  • a String
    • value

Returns:

String result

safeObject

(
  • items
)
private

Check to see if variable is an Object

Parameters:

  • items Mixed

    Variable for checking

Returns:

Parameter being checked, if it is an object; returns an empty object on failure

setDisplayOffsets

(
  • [item]
)
chainable

A general function to reset display offsets for all pads, stacks and elements

The argument is an optional String - permitted values include 'stack', 'pad', 'element'; default: 'all'

(This function is replaced by the scrawlStacks extension)

Parameters:

  • [item] String optional

    Command string detailing which element types are to be set

Returns:

The Scrawl library object (scrawl)

Example:

scrawl.setDisplayOffsets();

show

(
  • [pads]
)
chainable

A display function to ask Pads to show the results of their latest display cycle

Parameters:

  • [pads] Array optional

    Array of PADNAMEs - can also be a String

Returns:

The Scrawl library object (scrawl)

simpleLoader

() private

A general function for loading img, css and js files

Copied and pasted (a terrible example - don't do this!) from https://davidwalsh.name/javascript-loader

All assets are added to the body tag in the DOM

This function auto-runs when scrawl.core loads

Returns:

Javascript object containing .css(), .js() and .img() load functions

subtractPercentages

(
  • a
  • b
)

A utility function to subtract a percent string from another

Parameters:

  • a String
    • initial value
  • b String
    • value to be subtracted from initial value

Returns:

String result

toInt

(
  • item
)

A utility function to convert strings (such as percentages) to integer values

Parameters:

  • item String

Returns:

Integer number; 0 on error

triggerTouchEnter

() private

A custom event listener function

The touchenter event is deprecated, but necessary for scrawl functionality

triggerTouchFollow

() private

A custom event listener function

The touchfollow event is entirely custom, designed to allow elements to subscribe to an event that started in a different element

triggerTouchLeave

() private

A custom event listener function

The touchleave event is deprecated, but necessary for scrawl functionality

updateCustomTouch

() private

A custom event listener helper function

xt

(
  • item
)

A utility function for variable type checking

Parameters:

  • item Mixed

    Primative or object for identification

Returns:

False if item is 'undefined'

Example:

var mystring = 'string',
    myboolean;
scrawl.xt(mystring);    //returns true
scrawl.xt(myboolean);   //returns false

xta

(
  • item
)

A utility function for variable type checking

Parameters:

  • item Array

    Array of primatives or objects for identification

Returns:

False if any item is 'undefined'

Example:

var mystring = 'string',
    mynumber = 0,
    myboolean;
scrawl.xta([mystring, mynumber]);   //returns true
scrawl.xta([mystring, myboolean]);  //returns false

xtGet

()

A utility function that checks an argument list of values and returns the first value that exists

Returns:

first defined variable; null if all values are undefined

xtGetTrue

()

A utility function that checks an argument list values and returns the first value that evaluates to true

False: 0, -0, '', undefined, null, false, NaN

Returns:

first true variable; null if all values are false

xto

()

A utility function for variable type checking

Returns:

True if any item is not 'undefined'

Example:

var mystring = 'string',
    mynumber = 0,
    myboolean;
scrawl.xto(mystring, mynumber); //returns true
scrawl.xto(mystring, myboolean);    //returns true

Properties

activeListeners

Array private

A custom event listener helper array

colv1

Vector private

Work vector, for calculations

colv2

Vector private

Work vector, for calculations

d

Object private

An Object containing OBJECTTYPE:Object pairs which in turn contain default attribute values for each Scrawl object constructor

device

Object

Device object - holds details about the browser environment and viewport

extensions

Array private

Array of loaded extensions arrays

f

Object private

DOM document fragment

loadAlias

Object private

Key:value pairs of extension alias:filename Strings, used by scrawl.loadExtensions()

loadDependencies

Object private

Key:value pairs of extension alias:Array, used by scrawl.loadExtensions()

modules

Array deprecated private

Array of loaded extensions arrays (name changed from modules to extensions because Scrawl 'modules' are not modules)

nameslist

Array private

Array of array object keys used to define the sections of the Scrawl library

o

Object private

Default empty object - passed to various functions, to prevent them generating superfluous objects

promise

Boolean final

Flag - Promise API is supported by browser

Default: null

radian

Number final

For converting between degrees and radians

Default: Math.PI/180

sectionlist

Array private

Array of objects which define the sections of the Scrawl library

v

Vector private

Work vector, for calculations

version

String final

Scrawl.js version number

Default: 6.0.1

workquat

Object private

Work quaternions, for calculations