Creates a new Facade.js object with either a preexisting canvas tag or a unique name, width, and height.
[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.
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.
var stage = new Facade(document.querySelector('canvas'));
var stage = new Facade('stage', 500, 300);
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.');
}
}
Object
New Facade.js object.
Draws a Facade.js entity (or multiple entities) to the stage.
obj
Object
Array
Facade.js entity or an array of entities.
options
Object
Temporary options for rendering a Facade.js entity (or multiple entities).
stage.addToStage(circle);
stage.addToStage(circle, { x: 100, y: 100 });
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;
};
Object
Facade.js object.
Clears the canvas.
stage.clear();
Facade.prototype.clear = function () {
this.context.clearRect(0, 0, this.width(), this.height());
return this;
};
Object
Facade.js object.
Sets a callback function to run in a loop using requestAnimationFrame or available polyfill.
callback
Function
Function callback.
stage.draw(function () {
this.clear();
this.addToStage(circle, { x: 100, y: 100 });
});
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;
};
Object
Facade.js object.
Exports a base64 encoded representation of the current rendered canvas.
[type]
String
Optional
Image format: image/png
(Default), image/jpeg
, image/webp
(Google Chrome Only)
[quality]
Integer
Optional
Number between 0 and 100.
console.log(stage.exportBase64('image/png', 100));
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);
};
String
Base64 encoded string.
Gets and sets the canvas height.
[height]
Integer
Optional
Height in pixels.
console.log(stage.height()); // 300
console.log(stage.height(600)); // 600
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;
};
Integer
Height in pixels.
Applies key-value pairs to appropriate CanvasRenderingContext2D properties and methods.
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.
stage.renderWithContext({ fillStyle: '#f00', globalAlpha: 0.5, fillRect: [ 0, 0, 100, 100 ]});
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();
};
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.
[ratio]
Integer
Optional
Ratio to scale the canvas.
stage.resizeForHDPI();
stage.resizeForHDPI(2);
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;
};
Object
Facade.js object.
Starts the callback supplied in Facade.draw
.
stage.start();
Facade.prototype.start = function () {
this._requestAnimation = _requestAnimationFrame(this._animate.bind(this));
return this;
};
Object
Facade.js object.
Stops the callback supplied in Facade.draw
.
stage.stop();
Facade.prototype.stop = function () {
this.dt = null;
this.fps = null;
this.ftime = null;
_cancelAnimationFrame(this._requestAnimation);
this._requestAnimation = null;
return this;
};
Object
Facade.js object.
Gets and sets the canvas width.
[width]
Integer
Optional
Width in pixels.
console.log(stage.width()); // 400
console.log(stage.width(800)); // 800
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;
};
Integer
Width in pixels.
Method called by requestAnimationFrame. Sets Facade.dt
, Facade.fps
and Facade.ftime
.
time
Integer
DOMTimeStamp or DOMHighResTimeStamp (Google Chrome Only)
this._requestAnimation = _requestAnimationFrame(this._animate.bind(this));
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;
};
Object
Facade.js object.
The constructor for all Facade.js shape, image and text objects.
Facade.Entity = function (options) {
if (!(this instanceof Facade.Entity)) {
return new Facade.Entity();
}
this._options = this._defaultOptions();
this._metrics = this._defaultMetrics();
this.setOptions(options);
};
Object
New Facade.Entity object.
Returns a default set of options common to all Facade.js entities.
updated
Object
Additional options as key-value pairs.
console.log(Facade.Entity.prototype._defaultOptions());
console.log(Facade.Entity.prototype._defaultOptions({ lineWidth: 0 }));
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;
};
Object
Default set of options.
Returns a default set of metrics common to all Facade.js entities.
updated
Object
Additional metrics as key-value pairs.
console.log(Facade.Entity.prototype._defaultMetrics());
console.log(Facade.Entity.prototype._defaultMetrics({ scale: null }));
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;
};
Object
Default set of metrics.
Returns an array of the x and y anchor positions based on given options and metrics.
options
Object
Facade.Entity options.
metrics
Object
Facade.Entity metrics.
console.log(rect._getAnchorPoint(options, metrics));
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;
};
Array
Array with the x and y anchor positions.
Returns an integer for the stroke width offset. Used to calculate metrics.
options
Object
Facade.Entity options.
console.log(rect._getStrokeWidthOffset(options));
Facade.Entity.prototype._getStrokeWidthOffset = function (options) {
var strokeWidthOffset = 0;
if (options.lineWidth !== undefined) {
strokeWidthOffset = options.lineWidth / 2;
}
return strokeWidthOffset;
};
Integer
Integer representing the stroke width offset.
Applies transforms (translate, rotate and scale) to an entity.
context
Object
Reference to the CanvasRenderingContext2D object.
options
Object
Facade.Entity options.
metrics
Object
Facade.Entity metrics.
console.log(rect._applyTransforms(context, options, metrics));
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]);
}
};
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
.
key
String
The name of the option.
console.log(text.getOption('value'));
Facade.Entity.prototype.getOption = function (key) {
if (this._options[key] !== undefined) {
return this._options[key];
}
return undefined;
};
Object
Function
String
Integer
Value of the option requested.
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
.
console.log(text.getAllOptions());
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;
};
Object
Object containing all options.
Sets an option for a given entity.
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.
console.log(text._setOption('value', 'Hello world!'));
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;
};
Object
Function
String
Integer
Returns value of the updated option.
Sets a group of options as key-value pairs to an entity.
[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.
console.log(text.setOptions({ fontFamily: 'Georgia', fontSize: 20 }));
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;
};
Object
Updated options.
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
.
key
String
The name of the metric.
console.log(text.getMetric('width'));
Facade.Entity.prototype.getMetric = function (key) {
if (this._metrics[key] !== undefined) {
return this._metrics[key];
}
return undefined;
};
Integer
Value of the metric requested.
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
.
console.log(text.getAllMetrics());
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;
};
Object
Object containing all metrics.
Renders an entity to a canvas.
facade
Object
Facade.js object.
updated
Object
Temporary options for rendering a Facade.js entity.
entity.draw(stage);
entity.draw(stage, { x: 100, y: 100 });
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));
}
};
Create a polygon object. Inherits all methods from Facade.Entity.
[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"
[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"
[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"
[options.lineWidth]
Integer
Optional
Width of the stroke. Default: 0
[options.lineCap]
String
Optional
The style of line cap. Default: "butt"
[options.lineJoin]
String
Optional
The style of line join. Default: "miter"
[options.closePath]
Boolean
Optional
Boolean to determine if the polygon should be self closing or not. Default: true
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'
});
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);
};
Object
New Facade.Polygon object.
Returns a default set of options common to all Facade.js polygon entities.
updated
Object
Additional options as key-value pairs.
console.log(Facade.Polygon.prototype._defaultOptions());
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;
};
Object
Default set of options.
Renders a polygon entity to a canvas.
facade
Object
Facade.js object.
options
Object
Options used to render the polygon.
metrics
Object
Metrics used to render the polygon.
polygon._draw(facade, options, metrics);
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();
}
}
};
Custom configuration for options specific to a polygon entity.
options
Object
Complete set of polygon specific options.
console.log(polygon._configOptions(options));
Facade.Polygon.prototype._configOptions = function (options) {
options.translate = [ options.x, options.y ];
options.globalAlpha = options.opacity / 100;
return options;
};
Object
Converted options.
Set metrics based on the polygon's options.
[updated]
Object
Optional
Custom options used to render the polygon.
console.log(polygon._setMetrics());
console.log(polygon._setMetrics(options));
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;
};
Object
Object with metrics as key-value pairs.
Create a circle object. Inherits all methods from Facade.Polygon.
[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"
[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"
[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"
[options.lineWidth]
Integer
Optional
Width of the stroke. Default: 0
[options.lineCap]
String
Optional
The style of line cap. Default: "butt"
[options.lineJoin]
String
Optional
The style of line join. Default: "miter"
[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
var circle = new Facade.Circle({
x: 0,
y: 0,
radius: 100,
lineWidth: 10,
strokeStyle: '#333E4B',
fillStyle: '#1C73A8',
anchor: 'top/left'
});
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);
};
Object
New Facade.Circle object.
Custom configuration for options specific to a circle entity.
options
Object
Complete set of circle specific options.
console.log(circle._configOptions(options));
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;
};
Object
Converted options.
Returns an array of the x and y anchor positions based on given options and metrics.
options
Object
Facade.Circle options.
metrics
Object
Facade.Circle metrics.
console.log(circle._getAnchorPoint(options, metrics));
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;
};
Array
Array with the x and y anchor positions.
Set metrics based on the circle's options.
[updated]
Object
Optional
Custom options used to render the circle.
console.log(circle._setMetrics());
console.log(circle._setMetrics(options));
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;
};
Object
Object with metrics as key-value pairs.
Create a line object. Inherits all methods from Facade.Polygon.
[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"
[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"
[options.lineWidth]
Integer
Optional
Width of the stroke. Default: 0
[options.lineCap]
String
Optional
The style of line cap. Default: "butt"
[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
var line = new Facade.Line({
x: 0,
y: 0,
x1: 0,
x2: 200,
lineWidth: 10,
strokeStyle: '#333E4B',
anchor: 'top/left'
});
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);
};
Object
New Facade.Line object.
Custom configuration for options specific to a line entity.
options
Object
Complete set of line specific options.
console.log(line._configOptions(options));
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;
};
Object
Converted options.
Returns an array of the x and y anchor positions based on given options and metrics.
options
Object
Facade.Line options.
metrics
Object
Facade.Line metrics.
console.log(line._getAnchorPoint(options, metrics));
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;
};
Array
Array with the x and y anchor positions.
Create a rectangle object. Inherits all methods from Facade.Polygon.
[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"
[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"
[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"
[options.lineWidth]
Integer
Optional
Width of the stroke. Default: 0
[options.lineJoin]
String
Optional
The style of rectangle join. Default: "miter"
[options.width]
Integer
Optional
Width of the rectangle. Default: 0
[options.height]
Integer
Optional
Height of the rectangle. Default: 0
var rect = new Facade.Rect({
x: 0,
y: 0,
width: 200,
height: 200,
lineWidth: 10,
strokeStyle: '#333E4B',
fillStyle: '#1C73A8',
anchor: 'top/left'
});
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);
};
Object
New Facade.Rect object.
Custom configuration for options specific to a rectangle entity.
options
Object
Complete set of rectangle specific options.
console.log(rect._configOptions(options));
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;
};
Object
Converted options.
Create an image object. Inherits all methods from Facade.Entity.
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"
[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) { };
image
Object
Reference to the image element.
animating
Boolean
Boolean state of the animation.
currentFrame
Integer
Current frame of animation.
var image = new Facade.Image('images/sprite.png', {
x: 0,
y: 0,
width: 100,
height: 200,
anchor: 'top/left'
});
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);
};
Object
New Facade.Image object.
Loads either a reference to an image tag or an image URL into a Facade.Image entity.
source
Object
String
A reference to an image tag or an image URL.
console.log(image.load(document.querySelector('img')));
console.log(image.load('images/sprite.png'));
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));
}
};
Starts an image sprite animation.
image.play();
Facade.Image.prototype.play = function () {
this.animating = true;
return this;
};
Object
Facade.js image object.
Pauses an image sprite animation.
image.pause();
Facade.Image.prototype.pause = function () {
this.animating = false;
return this;
};
Object
Facade.js image object.
Resets an image sprite animation to the first frame.
image.reset();
Facade.Image.prototype.reset = function () {
this.currentFrame = 0;
return this;
};
Object
Facade.js image object.
Stops and resets an image sprite animation.
image.stop();
Facade.Image.prototype.stop = function () {
this.currentFrame = 0;
this.animating = false;
return this;
};
Object
Facade.js image object.
Custom configuration for options specific to a image entity.
options
Object
Complete set of image specific options.
console.log(image._configOptions(options));
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;
};
Object
Converted options.
Set metrics based on the image's options.
[updated]
Object
Optional
Custom options used to render the image.
console.log(image._setMetrics());
console.log(image._setMetrics(updated));
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;
};
Object
Object with metrics as key-value pairs.
Renders an image entity to a canvas.
facade
Object
Facade.js object.
options
Object
Options used to render the image.
metrics
Object
Metrics used to render the image.
image._draw(facade, options, metrics);
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]);
}
}
}
}
};
Create a text object. Inherits all methods from Facade.Entity.
[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"
[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"
[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"
[options.textBaseline]
String
Optional
Baseline to set the vertical alignment of the text drawn. Default: "top"
[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"
[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"
[options.lineWidth]
Integer
Optional
Width of the stroke. Default: 0
value
String
Current value of the text object.
var text = new Facade.Text('Hello World!', {
x: 0,
y: 0,
fontFamily: 'Helvetica',
fontSize: 40,
fillStyle: '#333',
anchor: 'top/left'
});
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);
}
};
Object
New Facade.Text object.
Sets the text entities value.
value
String
The new value of the text entity.
console.log(text.setText('Lorem ipsum dolor sit amet'));
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;
};
Array
An array of lines and the position to render using fillText() and strokeText().
Renders a text entity to a canvas.
facade
Object
Facade.js object.
options
Object
Options used to render the text entity.
metrics
Object
Metrics used to render the text entity.
text._draw(facade, options, metrics);
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]);
}
}
};
Custom configuration for options specific to a text entity.
options
Object
Complete set of text specific options.
console.log(text._configOptions(options));
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;
};
Object
Converted options.
Set metrics based on the text's options.
[updated]
Object
Optional
Custom options used to render the text entity.
console.log(text._setMetrics());
console.log(text._setMetrics(updated));
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;
};
Object
Object with metrics as key-value pairs.
Create a group object. Inherits all methods from Facade.Entity.
[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"
[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
var group = new Facade.Group({ x: 100, y: 100 });
group.addToGroup(polygon);
group.addToGroup(circle);
group.addToGroup(line);
group.addToGroup(rect);
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);
};
Object
New Facade.Group object.
Renders a group of entities to a canvas.
facade
Object
Facade.js object.
options
Object
Options used to render the group.
metrics
Object
Metrics used to render the group.
group._draw(stage, options, metrics);
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]);
}
};
Custom configuration for options specific to a group entity.
options
Object
Complete set of group specific options.
console.log(group._configOptions(options));
Facade.Group.prototype._configOptions = function (options) {
options.translate = [ options.x, options.y ];
return options;
};
Object
Converted options.
Adds a Facade.js entity to a group.
obj
Object
Array
Facade.js entity or an array of entities.
group.addToGroup(circle);
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.');
}
};
Tests the existence of an entity within a group.
obj
Object
Facade.js entity.
group.addToGroup(circle);
Facade.Group.prototype.hasEntity = function (obj) {
return this._objects.indexOf(obj) !== -1;
};
Boolean
Boolean result of the test.
Removes a Facade.js entity from a group.
obj
Object
Facade.js entity.
group.removeFromGroup(circle);
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();
}
}
};
Set metrics based on the groups's entities and options.
[updated]
Object
Optional
Custom options used to render the group.
console.log(group._setMetrics());
console.log(group._setMetrics(updated));
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;
};
Object
Object with metrics as key-value pairs.