← View all versions of documentation
Back to Top

Facade()

Creates a new Facade.js object with either a preexisting canvas tag or a unique name, width, and height.

Parameters

[canvas] Object String Optional

Reference to an HTML canvas element or a unique name.

[width] Integer Optional

Width of the canvas.

[height] Integer Optional

Height of the canvas.

Properties

canvas Object

Reference to the canvas element.

context Object

Reference to the CanvasRenderingContext2D object.

dt Integer

Current time in milliseconds since last canvas draw.

fps Integer

Current frames per second.

ftime Integer

Time of last canvas draw.

Examples

var stage = new Facade(document.querySelector('canvas'));
var stage = new Facade('stage', 500, 300);

Code

function Facade(canvas, width, height) {

    if (!(this instanceof Facade)) {

        return new Facade(canvas, width, height);

    }

    this.dt = null;
    this.fps = null;
    this.ftime = null;

    this._callback = null;

    this._requestAnimation = null;

    this._width = null;
    this._height = null;

    if (canvas && typeof canvas === 'object' && canvas.nodeType === 1) {

        this.canvas = canvas;

    } else {

        this.canvas = document.createElement('canvas');

        if (typeof canvas === 'string') {

            this.canvas.setAttribute('id', canvas);

        }

    }

    if (width) {

        this.width(width);

    } else if (this.canvas.hasAttribute('width')) {

        this._width = parseInt(this.canvas.getAttribute('width'), 10);

    } else {

        this.width(this.canvas.clientWidth);

    }

    if (height) {

        this.height(height);

    } else if (this.canvas.hasAttribute('height')) {

        this._height = parseInt(this.canvas.getAttribute('height'), 10);

    } else {

        this.height(this.canvas.clientHeight);

    }

    try {

        this.context = this.canvas.getContext('2d');

    } catch (e) {

        console.error('Object passed to Facade.js was not a valid canvas element.');

    }

}

Returns

Object

New Facade.js object.

Facade.addToStage()

Draws a Facade.js entity (or multiple entities) to the stage.

Parameters

obj Object Array

Facade.js entity or an array of entities.

options Object

Temporary options for rendering a Facade.js entity (or multiple entities).

Examples

stage.addToStage(circle);
stage.addToStage(circle, { x: 100, y: 100 });

Code

Facade.prototype.addToStage = function (obj, options) {

    var i,
        length;

    if (obj instanceof Facade.Entity) {

        obj.draw(this, options);

    } else if (Array.isArray(obj)) {

        for (i = 0, length = obj.length; i < length; i += 1) {

            this.addToStage(obj[i], options);

        }

    } else {

        console.error('Object passed to Facade.addToStage is not a valid Facade.js entity.');

    }

    return this;

};

Returns

Object

Facade.js object.

Facade.clear()

Clears the canvas.

Examples

 stage.clear();

Code

Facade.prototype.clear = function () {

    this.context.clearRect(0, 0, this.width(), this.height());

    return this;

};

Returns

Object

Facade.js object.

Facade.draw()

Sets a callback function to run in a loop using requestAnimationFrame or available polyfill.

Parameters

callback Function

Function callback.

Examples

stage.draw(function () {

    this.clear();

    this.addToStage(circle, { x: 100, y: 100 });

});

Code

Facade.prototype.draw = function (callback) {

    if (typeof callback === 'function') {

        this._callback = callback;

        this.start();

    } else {

        console.error('Parameter passed to Facade.draw is not a valid function.');

    }

    return this;

};

Returns

Object

Facade.js object.

Facade.exportBase64()

Exports a base64 encoded representation of the current rendered canvas.

Parameters

[type] String Optional

Image format: image/png (Default), image/jpeg, image/webp (Google Chrome Only)

[quality] Integer Optional

Number between 0 and 100.

Examples

console.log(stage.exportBase64('image/png', 100));

Code

Facade.prototype.exportBase64 = function (type, quality) {

    if (!type) {

        type = 'image/png';

    }

    if (typeof quality === 'number') {

        quality = quality / 100;

    } else {

        quality = 1;

    }

    return this.canvas.toDataURL(type, quality);

};

Returns

String

Base64 encoded string.

Facade.height()

Gets and sets the canvas height.

Parameters

[height] Integer Optional

Height in pixels.

Examples

console.log(stage.height()); // 300
console.log(stage.height(600)); // 600

Code

Facade.prototype.height = function (height) {

    if (height) {

        this._height = parseInt(height, 10);

        if (this.canvas.hasAttribute('data-resized-for-hdpi')) {

            this.resizeForHDPI();

        } else {

            this.canvas.setAttribute('height', this._height);

        }

    }

    return this._height;

};

Returns

Integer

Height in pixels.

Facade.renderWithContext()

Applies key-value pairs to appropriate CanvasRenderingContext2D properties and methods.

Parameters

options Object

Object containing context property and/or method names with corresponding values.

[callback] Function Optional

Function to be called when context options have been rendered to the canvas.

Examples

stage.renderWithContext({ fillStyle: '#f00', globalAlpha: 0.5, fillRect: [ 0, 0, 100, 100 ]});

Code

Facade.prototype.renderWithContext = function (options, callback) {

    var keys = Object.keys(options),
        i,
        length;

    this.context.save();

    for (i = 0, length = keys.length; i < length; i += 1) {

        if (_contextProperties.indexOf(keys[i]) !== -1) {

            this.context[keys[i]] = options[keys[i]];

        } else if (Array.isArray(options[keys[i]]) && typeof this.context[keys[i]] === 'function') {

            this.context[keys[i]].apply(this.context, options[keys[i]]);

        }

    }

    if (callback) {

        callback.call(null, this);

    }

    this.context.restore();

};

Returns

Facade.resizeForHDPI()

Resizes the canvas width and height to be multiplied by the pixel ratio of the device to allow for sub-pixel aliasing. Canvas tag maintains original width and height through CSS. Must be called before creating/adding any Facade entities as scaling is applied to the canvas context.

Parameters

[ratio] Integer Optional

Ratio to scale the canvas.

Examples

stage.resizeForHDPI();
stage.resizeForHDPI(2);

Code

Facade.prototype.resizeForHDPI = function (ratio) {

    if (ratio === undefined) {

        ratio = window.devicePixelRatio;

    } else {

        ratio = parseFloat(ratio);

    }

    if (ratio > 1) {

        this.canvas.setAttribute('style', 'width: ' + this.width() + 'px; height: ' + this.height() + 'px;');

        this.canvas.setAttribute('width', this.width() * ratio);
        this.canvas.setAttribute('height', this.height() * ratio);

        this.context.scale(ratio, ratio);

        this.canvas.setAttribute('data-resized-for-hdpi', true);

    }

    return this;

};

Returns

Object

Facade.js object.

Facade.start()

Starts the callback supplied in Facade.draw.

Examples

stage.start();

Code

Facade.prototype.start = function () {

    this._requestAnimation = _requestAnimationFrame(this._animate.bind(this));

    return this;

};

Returns

Object

Facade.js object.

Facade.stop()

Stops the callback supplied in Facade.draw.

Examples

stage.stop();

Code

Facade.prototype.stop = function () {

    this.dt = null;
    this.fps = null;
    this.ftime = null;

    _cancelAnimationFrame(this._requestAnimation);

    this._requestAnimation = null;

    return this;

};

Returns

Object

Facade.js object.

Facade.width()

Gets and sets the canvas width.

Parameters

[width] Integer Optional

Width in pixels.

Examples

console.log(stage.width()); // 400
console.log(stage.width(800)); // 800

Code

Facade.prototype.width = function (width) {

    if (width) {

        this._width = parseInt(width, 10);

        if (this.canvas.hasAttribute('data-resized-for-hdpi')) {

            this.resizeForHDPI();

        } else {

            this.canvas.setAttribute('width', this._width);

        }

    }

    return this._width;

};

Returns

Integer

Width in pixels.

Facade._animate() private method

Method called by requestAnimationFrame. Sets Facade.dt, Facade.fps and Facade.ftime.

Parameters

time Integer

DOMTimeStamp or DOMHighResTimeStamp (Google Chrome Only)

Examples

this._requestAnimation = _requestAnimationFrame(this._animate.bind(this));

Code

Facade.prototype._animate = function (time) {

    if (typeof this._callback === 'function') {

        if (this.ftime) {

            this.dt = time - this.ftime;

            this.fps = (1000 / this.dt).toFixed(2);

        }

        this.ftime = time;

        this._requestAnimation = _requestAnimationFrame(this._animate.bind(this));

        this.context.save();

        this._callback();

        this.context.restore();

    } else {

        this.stop();

    }

    return this;

};

Returns

Object

Facade.js object.

Facade.Entity()

The constructor for all Facade.js shape, image and text objects.

Examples

Code

Facade.Entity = function (options) {

    if (!(this instanceof Facade.Entity)) {

        return new Facade.Entity();

    }

    this._options = this._defaultOptions();
    this._metrics = this._defaultMetrics();

    this.setOptions(options);

};

Returns

Object

New Facade.Entity object.

Facade.Entity._defaultOptions() private method

Returns a default set of options common to all Facade.js entities.

Parameters

updated Object

Additional options as key-value pairs.

Examples

console.log(Facade.Entity.prototype._defaultOptions());
console.log(Facade.Entity.prototype._defaultOptions({ lineWidth: 0 }));

Code

Facade.Entity.prototype._defaultOptions = function (updated) {

    var options,
        keys,
        i,
        length;

    options = {
        x: 0,
        y: 0,
        anchor: 'top/left',
        rotate: 0,
        scale: 1
    };

    if (typeof updated === 'object') {

        keys = Object.keys(updated);

        for (i = 0, length = keys.length; i < length; i += 1) {

            options[keys[i]] = updated[keys[i]];

        }

    }

    return options;

};

Returns

Object

Default set of options.

Facade.Entity._defaultMetrics() private method

Returns a default set of metrics common to all Facade.js entities.

Parameters

updated Object

Additional metrics as key-value pairs.

Examples

console.log(Facade.Entity.prototype._defaultMetrics());
console.log(Facade.Entity.prototype._defaultMetrics({ scale: null }));

Code

Facade.Entity.prototype._defaultMetrics = function (updated) {

    var metrics,
        keys,
        i,
        length;

    metrics = {
        x: null,
        y: null,
        width: null,
        height: null
    };

    if (typeof updated === 'object') {

        keys = Object.keys(updated);

        for (i = 0, length = keys.length; i < length; i += 1) {

            metrics[keys[i]] = updated[keys[i]];

        }

    }

    return metrics;

};

Returns

Object

Default set of metrics.

Facade.Entity._getAnchorPoint() private method

Returns an array of the x and y anchor positions based on given options and metrics.

Parameters

options Object

Facade.Entity options.

metrics Object

Facade.Entity metrics.

Examples

console.log(rect._getAnchorPoint(options, metrics));

Code

Facade.Entity.prototype._getAnchorPoint = function (options, metrics) {

    var pos = [0, 0],
        strokeWidthOffset;

    if (options.anchor.match(/center$/)) {

        pos[0] = -metrics.width / 2;

    } else if (options.anchor.match(/right$/)) {

        pos[0] = -metrics.width;

    }

    if (options.anchor.match(/^center/)) {

        pos[1] = -metrics.height / 2;

    } else if (options.anchor.match(/^bottom/)) {

        pos[1] = -metrics.height;

    }

    if (this instanceof Facade.Polygon) {

        strokeWidthOffset = this._getStrokeWidthOffset(options);

        pos[0] = pos[0] + strokeWidthOffset;
        pos[1] = pos[1] + strokeWidthOffset;

    }

    return pos;

};

Returns

Array

Array with the x and y anchor positions.

Facade.Entity._getStrokeWidthOffset() private method

Returns an integer for the stroke width offset. Used to calculate metrics.

Parameters

options Object

Facade.Entity options.

Examples

console.log(rect._getStrokeWidthOffset(options));

Code

Facade.Entity.prototype._getStrokeWidthOffset = function (options) {

    var strokeWidthOffset = 0;

    if (options.lineWidth !== undefined) {

        strokeWidthOffset = options.lineWidth / 2;

    }

    return strokeWidthOffset;

};

Returns

Integer

Integer representing the stroke width offset.

Facade.Entity._applyTransforms() private method

Applies transforms (translate, rotate and scale) to an entity.

Parameters

context Object

Reference to the CanvasRenderingContext2D object.

options Object

Facade.Entity options.

metrics Object

Facade.Entity metrics.

Examples

console.log(rect._applyTransforms(context, options, metrics));

Code

Facade.Entity.prototype._applyTransforms = function (context, options, metrics) {

    var anchor = this._getAnchorPoint(options, {
        x: metrics.x,
        y: metrics.y,
        width: metrics.width / options.scale,
        height: metrics.height / options.scale
    });

    context.translate.apply(context, anchor);

    if (options.rotate) {

        context.translate(-anchor[0], -anchor[1]);
        context.rotate(options.rotate * _TO_RADIANS);
        context.translate(anchor[0], anchor[1]);

    }

    if (options.scale !== 1) {

        context.translate(-anchor[0], -anchor[1]);
        context.scale(options.scale, options.scale);
        context.translate(anchor[0], anchor[1]);

    }

};

Returns

Facade.Entity.getOption()

Retrieves the value of a given option. Only retrieves options set when creating a new Facade.js entity or using setOptions not through temporary options set when using Facade.addToStage.

Parameters

key String

The name of the option.

Examples

console.log(text.getOption('value'));

Code

Facade.Entity.prototype.getOption = function (key) {

    if (this._options[key] !== undefined) {

        return this._options[key];

    }

    return undefined;

};

Returns

Object Function String Integer

Value of the option requested.

Facade.Entity.getAllOptions()

Retrieves the value of all options. Only retrieves options set when creating a new Facade.js entity or using setOptions not through temporary options set when using Facade.addToStage.

Examples

console.log(text.getAllOptions());

Code

Facade.Entity.prototype.getAllOptions = function () {

    var options = {},
        keys = Object.keys(this._options),
        i,
        length;

    for (i = 0, length = keys.length; i < length; i += 1) {

        options[keys[i]] = this._options[keys[i]];

    }

    return options;

};

Returns

Object

Object containing all options.

Facade.Entity._setOption() private method

Sets an option for a given entity.

Parameters

key String

The option to update.

value Object Function String Integer

The new value of the specified option.

test Boolean

Flag to determine if options are to be persisted in the entity or just returned.

Examples

console.log(text._setOption('value', 'Hello world!'));

Code

Facade.Entity.prototype._setOption = function (key, value, test) {

    var results;

    if (this._options[key] !== undefined) {

        if (typeof this._options[key] === 'number') {

            if (typeof value === 'string') {

                results = value.match(_OPERATOR_TEST);

                if (results) {

                    value = parseFloat(value.replace(_OPERATOR_TEST, ''));

                    if (results[1] === '+') {

                        value = this._options[key] + value;

                    } else if (results[1] === '-') {

                        value = this._options[key] - value;

                    }

                } else {

                    value = parseFloat(value);

                }

            }

            if (isNaN(value)) {

                value = this._options[key];

                console.error('The value for ' + key + ' was not a valid number.');

            }

        }

        if (String(typeof this._options[key]) === String(typeof value)) {

            if (!test) {

                this._options[key] = value;

            }

        } else {

            console.error('The value for ' + key + ' (' + value + ') was a ' + String(typeof value) + ' not a ' + String(typeof this._options[key]) + '.');

        }

        return value;

    }

    return undefined;

};

Returns

Object Function String Integer

Returns value of the updated option.

Facade.Entity.setOptions()

Sets a group of options as key-value pairs to an entity.

Parameters

[updated] Object Optional

The options to update. Does not need to be entire set of options.

[test] Boolean Optional

Flag to determine if options are to be persisted in the entity or just returned.

Examples

console.log(text.setOptions({ fontFamily: 'Georgia', fontSize: 20 }));

Code

Facade.Entity.prototype.setOptions = function (updated, test) {

    var options = this.getAllOptions(),
        keys,
        i,
        length;

    if (updated) {

        keys = Object.keys(updated);

        for (i = 0, length = keys.length; i < length; i += 1) {

            if (options[keys[i]] !== undefined) {

                options[keys[i]] = this._setOption(keys[i], updated[keys[i]], test);

            }

        }

        if (!test) {

            this._setMetrics();

        }

    }

    return options;

};

Returns

Object

Updated options.

Facade.Entity.getMetric()

Retrieves the value of a given metric. Only retrieves metrics set when creating a new Facade.js entity or using setOptions not through temporary options set when using Facade.addToStage.

Parameters

key String

The name of the metric.

Examples

console.log(text.getMetric('width'));

Code

Facade.Entity.prototype.getMetric = function (key) {

    if (this._metrics[key] !== undefined) {

        return this._metrics[key];

    }

    return undefined;

};

Returns

Integer

Value of the metric requested.

Facade.Entity.getAllMetrics()

Retrieves the value of all metrics. Only retrieves metrics set when creating a new Facade.js entity or using setOptions not through temporary options set when using Facade.addToStage.

Examples

console.log(text.getAllMetrics());

Code

Facade.Entity.prototype.getAllMetrics = function () {

    var metrics = {},
        keys = Object.keys(this._metrics),
        i,
        length;

    for (i = 0, length = keys.length; i < length; i += 1) {

        metrics[keys[i]] = this._metrics[keys[i]];

    }

    return metrics;

};

Returns

Object

Object containing all metrics.

Facade.Entity.draw()

Renders an entity to a canvas.

Parameters

facade Object

Facade.js object.

updated Object

Temporary options for rendering a Facade.js entity.

Examples

entity.draw(stage);
entity.draw(stage, { x: 100, y: 100 });

Code

Facade.Entity.prototype.draw = function (facade, updated) {

    var options = this.setOptions(updated, true),
        metrics;

    if (typeof this._configOptions === 'function') {

        options = this._configOptions(options);

    }

    metrics = updated ? this._setMetrics(options) : this.getAllMetrics();

    if (typeof this._draw === 'function') {

        facade.renderWithContext(options, this._draw.bind(this, facade, options, metrics));

    }

};

Returns

Facade.Polygon()

Create a polygon object. Inherits all methods from Facade.Entity.

Parameters

[options] Object Optional

Options to create the polygon with.

[options.x] Integer Optional

X coordinate to position the polygon. Default: 0

[options.y] Integer Optional

Y coordinate to position the polygon. Default: 0

[options.anchor] String Optional

Position to anchor the polygon. Default: "top/left"

  • top/left
  • top/center
  • top/right
  • center/left
  • center
  • center/right
  • bottom/left
  • bottom/center
  • bottom/right

[options.rotate] Integer Optional

Degrees to rotate the polygon. Default: 0

[options.scale] Integer Optional

A float representing the scale of a polygon. Default: 1

[options.opacity] Integer Optional

Opacity of the polygon. Integer between 0 and 100. Default: 100

[options.points] Array Optional

Multi-dimensional array of points used to render a polygon. Point arrays with 2 values is rendered as a line, 5 values is rendered as an arc and 6 values is rendered as a bezier curve.

[options.fillStyle] String Optional

Fill color for the polygon. Can be a text representation of a color, HEX, RGB(a), HSL(a). Default: "#000"

  • HTML Colors: red, green, blue, etc.
  • HEX: #f00, #ff0000
  • RGB(a): rgb(255, 0, 0), rgba(0, 255, 0, 0.5)
  • HSL(a): hsl(100, 100%, 50%), hsla(100, 100%, 50%, 0.5)

[options.strokeStyle] String Optional

Color of a polygon's stroke. Can be a text representation of a color, HEX, RGB(a), HSL(a). Default: "#000"

  • HTML Colors: red, green, blue, etc.
  • HEX: #f00, #ff0000
  • RGB(a): rgb(255, 0, 0), rgba(0, 255, 0, 0.5)
  • HSL(a): hsl(100, 100%, 50%), hsla(100, 100%, 50%, 0.5)

[options.lineWidth] Integer Optional

Width of the stroke. Default: 0

[options.lineCap] String Optional

The style of line cap. Default: "butt"

  • butt
  • round
  • square

[options.lineJoin] String Optional

The style of line join. Default: "miter"

  • miter
  • round
  • bevel

[options.closePath] Boolean Optional

Boolean to determine if the polygon should be self closing or not. Default: true

Examples

var polygon = new Facade.Polygon({
    x: 0,
    y: 0,
    points: [ [100, 0], [200, 100], [100, 200], [0, 100] ],
    lineWidth: 10,
    strokeStyle: '#333E4B',
    fillStyle: '#1C73A8',
    anchor: 'top/left'
});

Code

Facade.Polygon = function (options) {

    if (!(this instanceof Facade.Polygon)) {

        return new Facade.Polygon(options);

    }

    this._options = this._defaultOptions();
    this._metrics = this._defaultMetrics();

    this.setOptions(options);

};

Returns

Object

New Facade.Polygon object.

Facade.Polygon._defaultOptions() private method

Returns a default set of options common to all Facade.js polygon entities.

Parameters

updated Object

Additional options as key-value pairs.

Examples

console.log(Facade.Polygon.prototype._defaultOptions());

Code

Facade.Polygon.prototype._defaultOptions = function (updated) {

    var options,
        keys,
        i,
        length;

    options = Facade.Entity.prototype._defaultOptions({
        opacity: 100,
        points: [],
        fillStyle: '#000',
        strokeStyle: '',
        lineWidth: 0,
        lineCap: 'butt',
        lineJoin: 'miter',
        closePath: true
    });

    if (updated) {

        keys = Object.keys(updated);

        for (i = 0, length = keys.length; i < length; i += 1) {

            options[keys[i]] = updated[keys[i]];

        }

    }

    return options;

};

Returns

Object

Default set of options.

Facade.Polygon._draw() private method

Renders a polygon entity to a canvas.

Parameters

facade Object

Facade.js object.

options Object

Options used to render the polygon.

metrics Object

Metrics used to render the polygon.

Examples

polygon._draw(facade, options, metrics);

Code

Facade.Polygon.prototype._draw = function (facade, options, metrics) {

    var context = facade.context,
        i,
        length;

    this._applyTransforms(context, options, metrics);

    if (options.points.length) {

        context.beginPath();

        for (i = 0, length = options.points.length; i < length; i += 1) {

            if (options.points[i].length === 6) {

                context.bezierCurveTo.apply(context, options.points[i]);

            } else if (options.points[i].length === 5) {

                context.arc.apply(context, options.points[i]);

            } else if (options.points[i].length === 2) {

                context.lineTo.apply(context, options.points[i]);

            }

        }

        if (options.closePath) {

            context.closePath();

        } else {

            context.moveTo.apply(context, options.points[length - 1]);

        }

        if (options.fillStyle) {

            context.fill();

        }

        if (options.lineWidth > 0) {

            context.stroke();

        }

    }

};

Returns

Facade.Polygon._configOptions() private method

Custom configuration for options specific to a polygon entity.

Parameters

options Object

Complete set of polygon specific options.

Examples

console.log(polygon._configOptions(options));

Code

Facade.Polygon.prototype._configOptions = function (options) {

    options.translate = [ options.x, options.y ];
    options.globalAlpha = options.opacity / 100;

    return options;

};

Returns

Object

Converted options.

Facade.Polygon._setMetrics() private method

Set metrics based on the polygon's options.

Parameters

[updated] Object Optional

Custom options used to render the polygon.

Examples

console.log(polygon._setMetrics());
console.log(polygon._setMetrics(options));

Code

Facade.Polygon.prototype._setMetrics = function (updated) {

    var metrics = this._defaultMetrics(),
        options = updated || this.getAllOptions(),
        bounds = { top: null, right: null, bottom: null, left: null },
        point,
        i,
        length,
        anchor,
        strokeWidthOffset = this._getStrokeWidthOffset(options);

    if (typeof this._configOptions === 'function') {

        options = this._configOptions(options);

    }

    for (i = 0, length = options.points.length; i < length; i += 1) {

        if (options.points[i].length === 2) { // Rect

            point = { x: options.points[i][0], y: options.points[i][1] };

        } else if (options.points[i].length === 5) { // Circle

            metrics.width = options.points[i][2] * 2;
            metrics.height = options.points[i][2] * 2;

            point = {
                x: options.points[i][0] - options.points[i][2],
                y: options.points[i][1] - options.points[i][2]
            };

        }

        if (point.x < bounds.left || bounds.left === null) {

            bounds.left = point.x;

        }

        if (point.y < bounds.top || bounds.top === null) {

            bounds.top = point.y;

        }

        if (point.x > bounds.right || bounds.right === null) {

            bounds.right = point.x;

        }

        if (point.y > bounds.bottom || bounds.bottom === null) {

            bounds.bottom = point.y;

        }

    }

    metrics.x = options.x + bounds.left;
    metrics.y = options.y + bounds.top;

    if (metrics.width === null && metrics.height === null) {

        metrics.width = bounds.right - bounds.left;
        metrics.height = bounds.bottom - bounds.top;

    }

    metrics.width = (metrics.width + strokeWidthOffset * 2) * options.scale;
    metrics.height = (metrics.height + strokeWidthOffset * 2) * options.scale;

    anchor = this._getAnchorPoint(options, metrics);

    metrics.x = metrics.x + anchor[0] - strokeWidthOffset;
    metrics.y = metrics.y + anchor[1] - strokeWidthOffset;

    if (this instanceof Facade.Circle) {

        metrics.x = metrics.x + options.radius;
        metrics.y = metrics.y + options.radius;

    }

    if (!updated) {

        this._metrics = metrics;

    }

    return metrics;

};

Returns

Object

Object with metrics as key-value pairs.

Facade.Circle()

Create a circle object. Inherits all methods from Facade.Polygon.

Parameters

[options] Object Optional

Options to create the circle with.

[options.x] Integer Optional

X coordinate to position the circle. Default: 0

[options.y] Integer Optional

Y coordinate to position the circle. Default: 0

[options.anchor] String Optional

Position to anchor the circle. Default: "top/left"

  • top/left
  • top/center
  • top/right
  • center/left
  • center
  • center/right
  • bottom/left
  • bottom/center
  • bottom/right

[options.rotate] Integer Optional

Degrees to rotate the circle. Default: 0

[options.scale] Integer Optional

A float representing the scale of a circle. Default: 1

[options.opacity] Integer Optional

Opacity of the circle. Integer between 0 and 100. Default: 100

[options.fillStyle] String Optional

Fill color for the circle. Can be a text representation of a color, HEX, RGB(a), HSL(a). Default: "#000"

  • HTML Colors: red, green, blue, etc.
  • HEX: #f00, #ff0000
  • RGB(a): rgb(255, 0, 0), rgba(0, 255, 0, 0.5)
  • HSL(a): hsl(100, 100%, 50%), hsla(100, 100%, 50%, 0.5)

[options.strokeStyle] String Optional

Color of a circle's stroke. Can be a text representation of a color, HEX, RGB(a), HSL(a). Default: "#000"

  • HTML Colors: red, green, blue, etc.
  • HEX: #f00, #ff0000
  • RGB(a): rgb(255, 0, 0), rgba(0, 255, 0, 0.5)
  • HSL(a): hsl(100, 100%, 50%), hsla(100, 100%, 50%, 0.5)

[options.lineWidth] Integer Optional

Width of the stroke. Default: 0

[options.lineCap] String Optional

The style of line cap. Default: "butt"

  • butt
  • round
  • square

[options.lineJoin] String Optional

The style of line join. Default: "miter"

  • miter
  • round
  • bevel

[options.radius] Integer Optional

Radius of the circle. Default: 0

[options.start] Integer Optional

Degree at which the circle begins. Default: 0

[options.end] Integer Optional

Degree at which the circle ends. Default: 360

[options.counterclockwise] Boolean Optional

Boolean determining if the circle will be drawn in a counter clockwise direction. Default: false

Examples

var circle = new Facade.Circle({
    x: 0,
    y: 0,
    radius: 100,
    lineWidth: 10,
    strokeStyle: '#333E4B',
    fillStyle: '#1C73A8',
    anchor: 'top/left'
});

Code

Facade.Circle = function (options) {

    if (!(this instanceof Facade.Circle)) {

        return new Facade.Circle(options);

    }

    this._options = this._defaultOptions({
        radius: 0,
        begin: 0,
        end: 360,
        counterclockwise: false
    });
    this._metrics = this._defaultMetrics();

    this.setOptions(options);

};

Returns

Object

New Facade.Circle object.

Facade.Circle._configOptions() private method

Custom configuration for options specific to a circle entity.

Parameters

options Object

Complete set of circle specific options.

Examples

console.log(circle._configOptions(options));

Code

Facade.Circle.prototype._configOptions = function (options) {

    options.translate = [ options.x, options.y ];
    options.globalAlpha = options.opacity / 100;

    if (options.counterclockwise) {

        options.points = [ [ 0, 0, options.radius, options.end * _TO_RADIANS, options.begin * _TO_RADIANS ] ];

    } else {

        options.points = [ [ 0, 0, options.radius, options.begin * _TO_RADIANS, options.end * _TO_RADIANS ] ];

    }

    return options;

};

Returns

Object

Converted options.

Facade.Circle._getAnchorPoint() private method

Returns an array of the x and y anchor positions based on given options and metrics.

Parameters

options Object

Facade.Circle options.

metrics Object

Facade.Circle metrics.

Examples

console.log(circle._getAnchorPoint(options, metrics));

Code

Facade.Circle.prototype._getAnchorPoint = function (options, metrics) {

    var pos = Facade.Polygon.prototype._getAnchorPoint.call(this, options, metrics);

    pos[0] = pos[0] + options.radius;
    pos[1] = pos[1] + options.radius;

    return pos;

};

Returns

Array

Array with the x and y anchor positions.

Facade.Circle._setMetrics() private method

Set metrics based on the circle's options.

Parameters

[updated] Object Optional

Custom options used to render the circle.

Examples

console.log(circle._setMetrics());
console.log(circle._setMetrics(options));

Code

Facade.Circle.prototype._setMetrics = function (updated) {

    var metrics = Facade.Polygon.prototype._setMetrics.call(this, updated),
        options = updated || this.getAllOptions();

    metrics.x = metrics.x - options.radius;
    metrics.y = metrics.y - options.radius;

    if (!updated) {

        this._metrics = metrics;

    }

    return metrics;

};

Returns

Object

Object with metrics as key-value pairs.

Facade.Line()

Create a line object. Inherits all methods from Facade.Polygon.

Parameters

[options] Object Optional

Options to create the line with.

[options.x] Integer Optional

X coordinate to position the line. Default: 0

[options.y] Integer Optional

Y coordinate to position the line. Default: 0

[options.anchor] String Optional

Position to anchor the line. Default: "top/left"

  • top/left
  • top/center
  • top/right
  • center/left
  • center
  • center/right
  • bottom/left
  • bottom/center
  • bottom/right

[options.rotate] Integer Optional

Degrees to rotate the line. Default: 0

[options.scale] Integer Optional

A float representing the scale of a line. Default: 1

[options.opacity] Integer Optional

Opacity of the line. Integer between 0 and 100. Default: 100

[options.strokeStyle] String Optional

Color of a line. Can be a text representation of a color, HEX, RGB(a), HSL(a). Default: "#000"

  • HTML Colors: red, green, blue, etc.
  • HEX: #f00, #ff0000
  • RGB(a): rgb(255, 0, 0), rgba(0, 255, 0, 0.5)
  • HSL(a): hsl(100, 100%, 50%), hsla(100, 100%, 50%, 0.5)

[options.lineWidth] Integer Optional

Width of the stroke. Default: 0

[options.lineCap] String Optional

The style of line cap. Default: "butt"

  • butt
  • round
  • square

[options.x1] Integer Optional

X coordinate where line begins. Default: 0

[options.y1] Integer Optional

Y coordinate where line begins. Default: 0

[options.x2] Integer Optional

X coordinate where line ends. Default: 0

[options.y2] Integer Optional

Y coordinate where line ends. Default: 0

Examples

var line = new Facade.Line({
    x: 0,
    y: 0,
    x1: 0,
    x2: 200,
    lineWidth: 10,
    strokeStyle: '#333E4B',
    anchor: 'top/left'
});

Code

Facade.Line = function (options) {

    if (!(this instanceof Facade.Line)) {

        return new Facade.Line(options);

    }

    this._options = this._defaultOptions({
        x1: 0,
        y1: 0,
        x2: 0,
        y2: 0,
        lineWidth: 1
    });
    this._metrics = this._defaultMetrics();

    this.setOptions(options);

};

Returns

Object

New Facade.Line object.

Facade.Line._configOptions() private method

Custom configuration for options specific to a line entity.

Parameters

options Object

Complete set of line specific options.

Examples

console.log(line._configOptions(options));

Code

Facade.Line.prototype._configOptions = function (options) {

    options.translate = [ options.x, options.y ];
    options.globalAlpha = options.opacity / 100;
    options.closePath = false;

    options.points = [ [ options.x1, options.y1 ], [ options.x2, options.y2 ] ];

    return options;

};

Returns

Object

Converted options.

Facade.Line._getAnchorPoint() private method

Returns an array of the x and y anchor positions based on given options and metrics.

Parameters

options Object

Facade.Line options.

metrics Object

Facade.Line metrics.

Examples

console.log(line._getAnchorPoint(options, metrics));

Code

Facade.Line.prototype._getAnchorPoint = function (options, metrics) {

    var pos = [0, 0];

    if (options.anchor.match(/center$/)) {

        pos[0] = -(metrics.width / 2 - options.lineWidth / 2);

    } else if (options.anchor.match(/right$/)) {

        pos[0] = -(metrics.width - options.lineWidth);

    }

    if (options.anchor.match(/^center/)) {

        pos[1] = -(metrics.height / 2 - options.lineWidth / 2);

    } else if (options.anchor.match(/^bottom/)) {

        pos[1] = -(metrics.height - options.lineWidth);

    }

    return pos;

};

Returns

Array

Array with the x and y anchor positions.

Facade.Rect()

Create a rectangle object. Inherits all methods from Facade.Polygon.

Parameters

[options] Object Optional

Options to create the rectangle with.

[options.x] Integer Optional

X coordinate to position the rectangle. Default: 0

[options.y] Integer Optional

Y coordinate to position the rectangle. Default: 0

[options.anchor] String Optional

Position to anchor the rectangle. Default: "top/left"

  • top/left
  • top/center
  • top/right
  • center/left
  • center
  • center/right
  • bottom/left
  • bottom/center
  • bottom/right

[options.rotate] Integer Optional

Degrees to rotate the rectangle. Default: 0

[options.scale] Integer Optional

A float representing the scale of a rectangle. Default: 1

[options.opacity] Integer Optional

Opacity of the rectangle. Integer between 0 and 100. Default: 100

[options.fillStyle] String Optional

Fill color for the rectangle. Can be a text representation of a color, HEX, RGB(a), HSL(a). Default: "#000"

  • HTML Colors: red, green, blue, etc.
  • HEX: #f00, #ff0000
  • RGB(a): rgb(255, 0, 0), rgba(0, 255, 0, 0.5)
  • HSL(a): hsl(100, 100%, 50%), hsla(100, 100%, 50%, 0.5)

[options.strokeStyle] String Optional

Color of a rectangle's stroke. Can be a text representation of a color, HEX, RGB(a), HSL(a). Default: "#000"

  • HTML Colors: red, green, blue, etc.
  • HEX: #f00, #ff0000
  • RGB(a): rgb(255, 0, 0), rgba(0, 255, 0, 0.5)
  • HSL(a): hsl(100, 100%, 50%), hsla(100, 100%, 50%, 0.5)

[options.lineWidth] Integer Optional

Width of the stroke. Default: 0

[options.lineJoin] String Optional

The style of rectangle join. Default: "miter"

  • miter
  • round
  • bevel

[options.width] Integer Optional

Width of the rectangle. Default: 0

[options.height] Integer Optional

Height of the rectangle. Default: 0

Examples

var rect = new Facade.Rect({
    x: 0,
    y: 0,
    width: 200,
    height: 200,
    lineWidth: 10,
    strokeStyle: '#333E4B',
    fillStyle: '#1C73A8',
    anchor: 'top/left'
});

Code

Facade.Rect = function (options) {

    if (!(this instanceof Facade.Rect)) {

        return new Facade.Rect(options);

    }

    this._options = this._defaultOptions({
        width: 0,
        height: 0
    });
    this._metrics = this._defaultMetrics();

    this.setOptions(options);

};

Returns

Object

New Facade.Rect object.

Facade.Rect._configOptions() private method

Custom configuration for options specific to a rectangle entity.

Parameters

options Object

Complete set of rectangle specific options.

Examples

console.log(rect._configOptions(options));

Code

Facade.Rect.prototype._configOptions = function (options) {

    options.translate = [ options.x, options.y ];
    options.globalAlpha = options.opacity / 100;

    options.points = [ [ 0, 0 ], [ options.width, 0 ], [ options.width, options.height ], [ 0, options.height ] ];

    return options;

};

Returns

Object

Converted options.

Facade.Image()

Create an image object. Inherits all methods from Facade.Entity.

Parameters

source Object String

Local image file or reference to an HTML image element.

[options] Object Optional

Options to create the image with.

[options.x] Integer Optional

X coordinate to position an image. Default: 0

[options.y] Integer Optional

Y coordinate to position an image. Default: 0

[options.anchor] String Optional

Position to anchor the image. Default: "top/left"

  • top/left
  • top/center
  • top/right
  • center/left
  • center
  • center/right
  • bottom/left
  • bottom/center
  • bottom/right

[options.rotate] Integer Optional

Degrees to rotate the image. Default: 0

[options.scale] Integer Optional

A float representing the scale of an image. Default: 1

[options.width] Integer Optional

Width of the image. Default: 0

[options.height] Integer Optional

Height of the image. Default: 0

[options.tileX] Integer Optional

Number of times to tile the image horizontally. Default: 1

[options.tileY] Integer Optional

Number of times to tile the image vertically. Default: 1

[options.offsetX] Integer Optional

Starting X coordinate within the image. Default: 0

[options.offsetY] Integer Optional

Starting Y coordinate within the image. Default: 0

[options.frames] Array Optional

Array of frame numbers (integers starting at 0) for sprite animation. Default: [0]

[options.speed] Integer Optional

Speed of sprite animation. Default: 120

[options.loop] Boolean Optional

Determines if the animation should loop. Default: true

[options.callback] Function Optional

Function called for every frame of a sprite animation. Default: function (frame) { };

Properties

image Object

Reference to the image element.

animating Boolean

Boolean state of the animation.

currentFrame Integer

Current frame of animation.

Examples

var image = new Facade.Image('images/sprite.png', {
    x: 0,
    y: 0,
    width: 100,
    height: 200,
    anchor: 'top/left'
});

Code

Facade.Image = function (img, options) {

    if (!(this instanceof Facade.Image)) {

        return new Facade.Image(img, options);

    }

    this._options = this._defaultOptions({
        width: 0,
        height: 0,
        tileX: 1,
        tileY: 1,
        offsetX: 0,
        offsetY: 0,
        frames: [0],
        speed: 120,
        loop: true,
        callback: function () { return undefined; }
    });
    this._metrics = this._defaultMetrics();

    this.animating = false;
    this.currentFrame = 0;

    this.setOptions(options);

    this.load(img);

};

Returns

Object

New Facade.Image object.

Facade.Image.load()

Loads either a reference to an image tag or an image URL into a Facade.Image entity.

Parameters

source Object String

A reference to an image tag or an image URL.

Examples

console.log(image.load(document.querySelector('img')));
console.log(image.load('images/sprite.png'));

Code

Facade.Image.prototype.load = function (source) {

    if (typeof source === 'object' && source.nodeType === 1) {

        this.image = source;

    } else {

        this.image = document.createElement('img');
        this.image.setAttribute('src', source);

    }

    if (this.image.complete) {

        this._setMetrics();

    } else {

        this.image.addEventListener('load', this._setMetrics.bind(this, null));

    }

};

Returns

Facade.Image.play()

Starts an image sprite animation.

Examples

image.play();

Code

Facade.Image.prototype.play = function () {

    this.animating = true;

    return this;

};

Returns

Object

Facade.js image object.

Facade.Image.pause()

Pauses an image sprite animation.

Examples

image.pause();

Code

Facade.Image.prototype.pause = function () {

    this.animating = false;

    return this;

};

Returns

Object

Facade.js image object.

Facade.Image.reset()

Resets an image sprite animation to the first frame.

Examples

image.reset();

Code

Facade.Image.prototype.reset = function () {

    this.currentFrame = 0;

    return this;

};

Returns

Object

Facade.js image object.

Facade.Image.stop()

Stops and resets an image sprite animation.

Examples

image.stop();

Code

Facade.Image.prototype.stop = function () {

    this.currentFrame = 0;

    this.animating = false;

    return this;

};

Returns

Object

Facade.js image object.

Facade.Image._configOptions() private method

Custom configuration for options specific to a image entity.

Parameters

options Object

Complete set of image specific options.

Examples

console.log(image._configOptions(options));

Code

Facade.Image.prototype._configOptions = function (options) {

    options.translate = [ options.x, options.y ];

    if (this.image && this.image.complete) {

        if (!options.width) {

            options.width = this.image.width;

        }

        if (!options.height) {

            options.height = this.image.height;

        }

    }

    return options;

};

Returns

Object

Converted options.

Facade.Image._setMetrics() private method

Set metrics based on the image's options.

Parameters

[updated] Object Optional

Custom options used to render the image.

Examples

console.log(image._setMetrics());
console.log(image._setMetrics(updated));

Code

Facade.Image.prototype._setMetrics = function (updated) {

    var metrics = this._defaultMetrics(),
        options = updated || this.getAllOptions(),
        anchor;

    if (typeof this._configOptions === 'function') {

        options = this._configOptions(options);

    }

    metrics.width = options.width * options.tileX * options.scale;
    metrics.height = options.height * options.tileY * options.scale;

    anchor = this._getAnchorPoint(options, metrics);

    metrics.x = options.x + anchor[0];
    metrics.y = options.y + anchor[1];

    if (!updated) {

        this._metrics = metrics;

    }

    return metrics;

};

Returns

Object

Object with metrics as key-value pairs.

Facade.Image._draw() private method

Renders an image entity to a canvas.

Parameters

facade Object

Facade.js object.

options Object

Options used to render the image.

metrics Object

Metrics used to render the image.

Examples

image._draw(facade, options, metrics);

Code

Facade.Image.prototype._draw = function (facade, options, metrics) {

    var context = facade.context,
        currentOffsetX = options.offsetX,
        currentOffsetY = options.offsetY,
        currentWidth = options.width,
        currentHeight = options.height,
        originalWidth = this.image.width,
        originalHeight = this.image.height,
        x,
        y;

    if (this.image.complete) {

        this._applyTransforms(context, options, metrics);

        if (options.frames.length) {

            currentOffsetX += options.frames[this.currentFrame] * options.width;

            if (currentOffsetX + options.width > originalWidth) {

                currentOffsetY += Math.floor(currentOffsetX / originalWidth) * options.height;

                currentOffsetX = currentOffsetX % originalWidth;

            }

        }

        if (currentOffsetX + currentWidth > originalWidth) {

            currentWidth = currentOffsetX + currentWidth - originalWidth;

        }

        if (currentOffsetY + currentHeight > originalHeight) {

            currentHeight = currentOffsetY + currentHeight - originalHeight;

        }

        for (x = 0; x < options.tileX; x += 1) {

            for (y = 0; y < options.tileY; y += 1) {

                context.drawImage(
                    this.image,
                    currentOffsetX,
                    currentOffsetY,
                    currentWidth,
                    currentHeight,
                    options.width * x,
                    options.height * y,
                    currentWidth,
                    currentHeight
                );

            }

        }

        if (this.animating) {

            if (!this.ftime || facade.ftime - this.ftime >= options.speed) {

                if (this.ftime) {

                    this.currentFrame += 1;

                }

                this.ftime = facade.ftime;

                if (this.currentFrame >= options.frames.length) {

                    if (options.loop) {

                        this.currentFrame = 0;

                    } else {

                        this.currentFrame = options.frames.length - 1;

                        this.isAnimating = false;

                    }

                }

                if (typeof options.callback === 'function') {

                    options.callback.call(this, options.frames[this.currentFrame]);

                }

            }

        }

    }

};

Returns

Facade.Text()

Create a text object. Inherits all methods from Facade.Entity.

Parameters

[value] Object Optional

Value of the text object.

[options] Object Optional

Options to create the text entity with.

[options.x] Integer Optional

X coordinate to position a text object. Default: 0

[options.y] Integer Optional

Y coordinate to position a text object. Default: 0

[options.anchor] String Optional

Position to anchor the text object. Default: "top/left"

  • top/left
  • top/center
  • top/right
  • center/left
  • center
  • center/right
  • bottom/left
  • bottom/center
  • bottom/right

[options.rotate] Integer Optional

Degrees to rotate the text object. Default: 0

[options.scale] Integer Optional

A float representing the scale of a text object. Default: 1

[options.opacity] Integer Optional

Opacity of the text object. Integer between 0 and 100. Default: 100

[options.width] Integer Optional

Max width of the text object. Will cause text to wrap onto a new line if necessary. No wrapping will occur if the value is set to 0. Default: 0

[options.fontFamily] String Optional

Sets the font family of the text. Only one font can be specified at a time. Default: "Arial"

[options.fontStyle] String Optional

Font style of the text. Default: "normal"

  • normal
  • bold
  • italic

[options.fontSize] Integer Optional

Font size in pixels. Default: 30

[options.lineHeight] String Optional

Line height of the text. Default: 1

[options.textAlignment] String Optional

Horizontal alignment of the text. Default: "left"

  • left
  • center
  • right

[options.textBaseline] String Optional

Baseline to set the vertical alignment of the text drawn. Default: "top"

  • top
  • hanging
  • middle
  • alphabetic
  • ideographic
  • bottom

[options.fillStyle] String Optional

Fill color for the text object. Can be a text representation of a color, HEX, RGB(a), HSL(a). Default: "#000"

  • HTML Colors: red, green, blue, etc.
  • HEX: #f00, #ff0000
  • RGB(a): rgb(255, 0, 0), rgba(0, 255, 0, 0.5)
  • HSL(a): hsl(100, 100%, 50%), hsla(100, 100%, 50%, 0.5)

[options.strokeStyle] String Optional

Color of a text object's stroke. Can be a text representation of a color, HEX, RGB(a), HSL(a). Default: "#000"

  • HTML Colors: red, green, blue, etc.
  • HEX: #f00, #ff0000
  • RGB(a): rgb(255, 0, 0), rgba(0, 255, 0, 0.5)
  • HSL(a): hsl(100, 100%, 50%), hsla(100, 100%, 50%, 0.5)

[options.lineWidth] Integer Optional

Width of the stroke. Default: 0

Properties

value String

Current value of the text object.

Examples

var text = new Facade.Text('Hello World!', {
    x: 0,
    y: 0,
    fontFamily: 'Helvetica',
    fontSize: 40,
    fillStyle: '#333',
    anchor: 'top/left'
});

Code

Facade.Text = function (value, options) {

    if (!(this instanceof Facade.Text)) {

        return new Facade.Text(value, options);

    }

    this._options = this._defaultOptions({
        opacity: 100,
        width: 0,
        fontFamily: 'Arial',
        fontStyle: 'normal',
        fontSize: 16,
        lineHeight: 1,
        textAlignment: 'left',
        textBaseline: 'top',
        fillStyle: '#000',
        strokeStyle: '#000',
        lineWidth: 0
    });
    this._metrics = this._defaultMetrics();

    this._maxLineWidth = 0;

    this._lines = [];

    this.setOptions(options);

    if (value !== undefined) {

        this.setText(value);

    }

};

Returns

Object

New Facade.Text object.

Facade.Text.setText()

Sets the text entities value.

Parameters

value String

The new value of the text entity.

Examples

console.log(text.setText('Lorem ipsum dolor sit amet'));

Code

Facade.Text.prototype.setText = function (value) {

    var options = this.getAllOptions(),
        words = [],
        currentWord = null,
        currentLine = '',
        currentLineWidth = 0,
        i,
        length;

    this.value = value;

    this._maxLineWidth = options.width;

    this._lines = [];

    if (value) {

        words = String(value).match(/\n|[\S]+ ?/g);

    }

    if (typeof this._configOptions === 'function') {

        options = this._configOptions(options);

    }

    _context.save();

    _context.font = options.font;

    while (words.length) {

        currentWord = words.shift();
        currentLineWidth = _context.measureText(currentLine + currentWord.replace(/\s$/, '')).width;

        if ((options.width > 0 && currentLineWidth > options.width) || currentWord.match(/\n/)) {

            this._lines.push([currentLine.replace(/\s$/, ''), 0, this._lines.length * (options.fontSize * options.lineHeight)]);

            currentLine = currentWord.replace(/\n/, '');

        } else {

            currentLine = currentLine + currentWord;

            if (currentLineWidth > this._maxLineWidth) {

                this._maxLineWidth = currentLineWidth;

            }

        }

    }

    this._lines.push([currentLine.replace(/\s$/, ''), 0, this._lines.length * (options.fontSize * options.lineHeight)]);

    for (i = 0, length = this._lines.length; i < length; i += 1) {

        currentLineWidth = _context.measureText(this._lines[i][0]).width;

        if (options.textAlignment === 'center') {

            this._lines[i][1] = (this._maxLineWidth - currentLineWidth) / 2;

        } else if (options.textAlignment === 'right') {

            this._lines[i][1] = this._maxLineWidth - currentLineWidth;

        }

    }

    _context.restore();

    this._setMetrics();

    return this._lines;

};

Returns

Array

An array of lines and the position to render using fillText() and strokeText().

Facade.Text._draw() private method

Renders a text entity to a canvas.

Parameters

facade Object

Facade.js object.

options Object

Options used to render the text entity.

metrics Object

Metrics used to render the text entity.

Examples

text._draw(facade, options, metrics);

Code

Facade.Text.prototype._draw = function (facade, options, metrics) {

    var context = facade.context,
        i,
        length;

    this._applyTransforms(context, options, metrics);

    for (i = 0, length = this._lines.length; i < length; i += 1) {

        if (options.fillStyle) {

            context.fillText.apply(context, this._lines[i]);

        }

        if (options.lineWidth) {

            context.strokeText.apply(context, this._lines[i]);

        }

    }

};

Returns

Facade.Text._configOptions() private method

Custom configuration for options specific to a text entity.

Parameters

options Object

Complete set of text specific options.

Examples

console.log(text._configOptions(options));

Code

Facade.Text.prototype._configOptions = function (options) {

    options.translate = [ options.x, options.y ];
    options.globalAlpha = options.opacity / 100;
    options.font = options.fontStyle + ' ' + parseInt(options.fontSize, 10) + 'px ' + options.fontFamily;

    if (options.width === 0) {

        options.width = this._maxLineWidth;

    }

    return options;

};

Returns

Object

Converted options.

Facade.Text._setMetrics() private method

Set metrics based on the text's options.

Parameters

[updated] Object Optional

Custom options used to render the text entity.

Examples

console.log(text._setMetrics());
console.log(text._setMetrics(updated));

Code

Facade.Text.prototype._setMetrics = function (updated) {

    var metrics = this._defaultMetrics(),
        options = updated || this.getAllOptions(),
        anchor;

    if (typeof this._configOptions === 'function') {

        options = this._configOptions(options);

    }

    if (this._lines) {

        metrics.width = options.width * options.scale;
        metrics.height = this._lines.length * (options.fontSize * options.lineHeight) * options.scale;

    }

    anchor = this._getAnchorPoint(options, metrics);

    metrics.x = options.x + anchor[0];
    metrics.y = options.y + anchor[1];

    if (!updated) {

        this._metrics = metrics;

    }

    return metrics;

};

Returns

Object

Object with metrics as key-value pairs.

Facade.Group()

Create a group object. Inherits all methods from Facade.Entity.

Parameters

[options] Object Optional

Options to create the group with.

[options.x] Integer Optional

X coordinate to position a group. Default: 0

[options.y] Integer Optional

Y coordinate to position a group. Default: 0

[options.anchor] String Optional

Position to anchor the group. Default: "top/left"

  • top/left
  • top/center
  • top/right
  • center/left
  • center
  • center/right
  • bottom/left
  • bottom/center
  • bottom/right

[options.rotate] Integer Optional

Degrees to rotate the group. Default: 0

[options.scale] Integer Optional

A float representing the scale of a group. Default: 1

Examples

var group = new Facade.Group({ x: 100, y: 100 });

group.addToGroup(polygon);
group.addToGroup(circle);
group.addToGroup(line);
group.addToGroup(rect);

Code

Facade.Group = function (options) {

    if (!(this instanceof Facade.Group)) {

        return new Facade.Group(options);

    }

    this._options = this._defaultOptions();
    this._metrics = this._defaultMetrics();

    this._objects = [];

    this.setOptions(options);

};

Returns

Object

New Facade.Group object.

Facade.Group._draw() private method

Renders a group of entities to a canvas.

Parameters

facade Object

Facade.js object.

options Object

Options used to render the group.

metrics Object

Metrics used to render the group.

Examples

group._draw(stage, options, metrics);

Code

Facade.Group.prototype._draw = function (facade, options, metrics) {

    var context = facade.context,
        i,
        length;

    this._applyTransforms(context, options, metrics);

    for (i = 0, length = this._objects.length; i < length; i += 1) {

        facade.addToStage(this._objects[i]);

    }

};

Returns

Facade.Group._configOptions() private method

Custom configuration for options specific to a group entity.

Parameters

options Object

Complete set of group specific options.

Examples

console.log(group._configOptions(options));

Code

Facade.Group.prototype._configOptions = function (options) {

    options.translate = [ options.x, options.y ];

    return options;

};

Returns

Object

Converted options.

Facade.Group.addToGroup()

Adds a Facade.js entity to a group.

Parameters

obj Object Array

Facade.js entity or an array of entities.

Examples

group.addToGroup(circle);

Code

Facade.Group.prototype.addToGroup = function (obj) {

    var i,
        length;

    if (obj instanceof Facade.Entity) {

        if (!this.hasEntity(obj)) {

            this._objects.push(obj);

            this._setMetrics();

        }

    } else if (Array.isArray(obj)) {

        for (i = 0, length = obj.length; i < length; i += 1) {

            this.addToGroup(obj[i]);

        }

    } else {

        console.error('Object passed to Facade.addToStage is not a valid Facade.js entity.');

    }

};

Returns

Facade.Group.hasEntity()

Tests the existence of an entity within a group.

Parameters

obj Object

Facade.js entity.

Examples

group.addToGroup(circle);

Code

Facade.Group.prototype.hasEntity = function (obj) {

    return this._objects.indexOf(obj) !== -1;

};

Returns

Boolean

Boolean result of the test.

Facade.Group.removeFromGroup()

Removes a Facade.js entity from a group.

Parameters

obj Object

Facade.js entity.

Examples

group.removeFromGroup(circle);

Code

Facade.Group.prototype.removeFromGroup = function (obj) {

    if (obj instanceof Facade.Entity) {

        if (this.hasEntity(obj)) {

            this._objects.splice(this._objects.indexOf(obj), 1);

            this._setMetrics();

        }

    }

};

Returns

Facade.Group._setMetrics() private method

Set metrics based on the groups's entities and options.

Parameters

[updated] Object Optional

Custom options used to render the group.

Examples

console.log(group._setMetrics());
console.log(group._setMetrics(updated));

Code

Facade.Group.prototype._setMetrics = function (updated) {

    var metrics = this._defaultMetrics(),
        options = updated || this.getAllOptions(),
        bounds = { top: null, right: null, bottom: null, left: null },
        i,
        length,
        anchor,
        obj_metrics;

    for (i = 0, length = this._objects.length; i < length; i += 1) {

        obj_metrics = this._objects[i].getAllMetrics();

        if (obj_metrics.x < bounds.left || bounds.left === null) {

            bounds.left = obj_metrics.x;

        }

        if (obj_metrics.y < bounds.top || bounds.top === null) {

            bounds.top = obj_metrics.y;

        }

        if (obj_metrics.x + obj_metrics.width > bounds.right || bounds.right === null) {

            bounds.right = obj_metrics.x + obj_metrics.width;

        }

        if (obj_metrics.y + obj_metrics.height > bounds.bottom || bounds.bottom === null) {

            bounds.bottom = obj_metrics.y + obj_metrics.height;

        }

    }

    metrics.x = options.x + bounds.left;
    metrics.y = options.y + bounds.top;

    metrics.width = (bounds.right - bounds.left) * options.scale;
    metrics.height = (bounds.bottom - bounds.top) * options.scale;

    anchor = this._getAnchorPoint(options, metrics);

    metrics.x = options.x + anchor[0];
    metrics.y = options.y + anchor[1];

    if (!updated) {

        this._metrics = metrics;

    }

    return metrics;

};

Returns

Object

Object with metrics as key-value pairs.