/* build: `node build.js modules=ALL exclude=gestures` */
/*! Fabric.js Copyright 2008-2013, Printio (Juriy Zaytsev, Maxim Chernyak) */
var fabric = fabric || { version: "1.3.7" };
if (typeof exports !== 'undefined') {
exports.fabric = fabric;
}
if (typeof document !== 'undefined' && typeof window !== 'undefined') {
fabric.document = document;
fabric.window = window;
}
else {
// assume we're running under node.js when document/window are not present
fabric.document = require("jsdom").jsdom("
");
fabric.window = fabric.document.createWindow();
}
/**
* True when in environment that supports touch events
* @type boolean
*/
fabric.isTouchSupported = "ontouchstart" in fabric.document.documentElement;
/**
* True when in environment that's probably Node.js
* @type boolean
*/
fabric.isLikelyNode = typeof Buffer !== 'undefined' && typeof window === 'undefined';
/*!
* Copyright (c) 2009 Simo Kinnunen.
* Licensed under the MIT license.
*/
var Cufon = (function() {
/** @ignore */
var api = function() {
return api.replace.apply(null, arguments);
};
/** @ignore */
var DOM = api.DOM = {
ready: (function() {
var complete = false, readyStatus = { loaded: 1, complete: 1 };
var queue = [], /** @ignore */ perform = function() {
if (complete) return;
complete = true;
for (var fn; fn = queue.shift(); fn());
};
// Gecko, Opera, WebKit r26101+
if (fabric.document.addEventListener) {
fabric.document.addEventListener('DOMContentLoaded', perform, false);
fabric.window.addEventListener('pageshow', perform, false); // For cached Gecko pages
}
// Old WebKit, Internet Explorer
if (!fabric.window.opera && fabric.document.readyState) (function() {
readyStatus[fabric.document.readyState] ? perform() : setTimeout(arguments.callee, 10);
})();
// Internet Explorer
if (fabric.document.readyState && fabric.document.createStyleSheet) (function() {
try {
fabric.document.body.doScroll('left');
perform();
}
catch (e) {
setTimeout(arguments.callee, 1);
}
})();
addEvent(fabric.window, 'load', perform); // Fallback
return function(listener) {
if (!arguments.length) perform();
else complete ? listener() : queue.push(listener);
};
})()
};
/** @ignore */
var CSS = api.CSS = /** @ignore */ {
/** @ignore */
Size: function(value, base) {
this.value = parseFloat(value);
this.unit = String(value).match(/[a-z%]*$/)[0] || 'px';
/** @ignore */
this.convert = function(value) {
return value / base * this.value;
};
/** @ignore */
this.convertFrom = function(value) {
return value / this.value * base;
};
/** @ignore */
this.toString = function() {
return this.value + this.unit;
};
},
/** @ignore */
getStyle: function(el) {
return new Style(el.style);
/*
var view = document.defaultView;
if (view && view.getComputedStyle) return new Style(view.getComputedStyle(el, null));
if (el.currentStyle) return new Style(el.currentStyle);
return new Style(el.style);
*/
},
quotedList: cached(function(value) {
// doesn't work properly with empty quoted strings (""), but
// it's not worth the extra code.
var list = [], re = /\s*((["'])([\s\S]*?[^\\])\2|[^,]+)\s*/g, match;
while (match = re.exec(value)) list.push(match[3] || match[1]);
return list;
}),
ready: (function() {
var complete = false;
var queue = [], perform = function() {
complete = true;
for (var fn; fn = queue.shift(); fn());
};
// Safari 2 does not include ');
function getFontSizeInPixels(el, value) {
return getSizeInPixels(el, /(?:em|ex|%)$/i.test(value) ? '1em' : value);
}
// Original by Dead Edwards.
// Combined with getFontSizeInPixels it also works with relative units.
function getSizeInPixels(el, value) {
if (/px$/i.test(value)) return parseFloat(value);
var style = el.style.left, runtimeStyle = el.runtimeStyle.left;
el.runtimeStyle.left = el.currentStyle.left;
el.style.left = value;
var result = el.style.pixelLeft;
el.style.left = style;
el.runtimeStyle.left = runtimeStyle;
return result;
}
return function(font, text, style, options, node, el, hasNext) {
var redraw = (text === null);
if (redraw) text = node.alt;
// @todo word-spacing, text-decoration
var viewBox = font.viewBox;
var size = style.computedFontSize ||
(style.computedFontSize = new Cufon.CSS.Size(getFontSizeInPixels(el, style.get('fontSize')) + 'px', font.baseSize));
var letterSpacing = style.computedLSpacing;
if (letterSpacing == undefined) {
letterSpacing = style.get('letterSpacing');
style.computedLSpacing = letterSpacing =
(letterSpacing == 'normal') ? 0 : ~~size.convertFrom(getSizeInPixels(el, letterSpacing));
}
var wrapper, canvas;
if (redraw) {
wrapper = node;
canvas = node.firstChild;
}
else {
wrapper = fabric.document.createElement('span');
wrapper.className = 'cufon cufon-vml';
wrapper.alt = text;
canvas = fabric.document.createElement('span');
canvas.className = 'cufon-vml-canvas';
wrapper.appendChild(canvas);
if (options.printable) {
var print = fabric.document.createElement('span');
print.className = 'cufon-alt';
print.appendChild(fabric.document.createTextNode(text));
wrapper.appendChild(print);
}
// ie6, for some reason, has trouble rendering the last VML element in the document.
// we can work around this by injecting a dummy element where needed.
// @todo find a better solution
if (!hasNext) wrapper.appendChild(fabric.document.createElement('cvml:shape'));
}
var wStyle = wrapper.style;
var cStyle = canvas.style;
var height = size.convert(viewBox.height), roundedHeight = Math.ceil(height);
var roundingFactor = roundedHeight / height;
var minX = viewBox.minX, minY = viewBox.minY;
cStyle.height = roundedHeight;
cStyle.top = Math.round(size.convert(minY - font.ascent));
cStyle.left = Math.round(size.convert(minX));
wStyle.height = size.convert(font.height) + 'px';
var textDecoration = Cufon.getTextDecoration(options);
var color = style.get('color');
var chars = Cufon.CSS.textTransform(text, style).split('');
var width = 0, offsetX = 0, advance = null;
var glyph, shape, shadows = options.textShadow;
// pre-calculate width
for (var i = 0, k = 0, l = chars.length; i < l; ++i) {
glyph = font.glyphs[chars[i]] || font.missingGlyph;
if (glyph) width += advance = ~~(glyph.w || font.w) + letterSpacing;
}
if (advance === null) return null;
var fullWidth = -minX + width + (viewBox.width - advance);
var shapeWidth = size.convert(fullWidth * roundingFactor), roundedShapeWidth = Math.round(shapeWidth);
var coordSize = fullWidth + ',' + viewBox.height, coordOrigin;
var stretch = 'r' + coordSize + 'nsnf';
for (i = 0; i < l; ++i) {
glyph = font.glyphs[chars[i]] || font.missingGlyph;
if (!glyph) continue;
if (redraw) {
// some glyphs may be missing so we can't use i
shape = canvas.childNodes[k];
if (shape.firstChild) shape.removeChild(shape.firstChild); // shadow
}
else {
shape = fabric.document.createElement('cvml:shape');
canvas.appendChild(shape);
}
shape.stroked = 'f';
shape.coordsize = coordSize;
shape.coordorigin = coordOrigin = (minX - offsetX) + ',' + minY;
shape.path = (glyph.d ? 'm' + glyph.d + 'xe' : '') + 'm' + coordOrigin + stretch;
shape.fillcolor = color;
// it's important to not set top/left or IE8 will grind to a halt
var sStyle = shape.style;
sStyle.width = roundedShapeWidth;
sStyle.height = roundedHeight;
if (shadows) {
// due to the limitations of the VML shadow element there
// can only be two visible shadows. opacity is shared
// for all shadows.
var shadow1 = shadows[0], shadow2 = shadows[1];
var color1 = Cufon.CSS.color(shadow1.color), color2;
var shadow = fabric.document.createElement('cvml:shadow');
shadow.on = 't';
shadow.color = color1.color;
shadow.offset = shadow1.offX + ',' + shadow1.offY;
if (shadow2) {
color2 = Cufon.CSS.color(shadow2.color);
shadow.type = 'double';
shadow.color2 = color2.color;
shadow.offset2 = shadow2.offX + ',' + shadow2.offY;
}
shadow.opacity = color1.opacity || (color2 && color2.opacity) || 1;
shape.appendChild(shadow);
}
offsetX += ~~(glyph.w || font.w) + letterSpacing;
++k;
}
wStyle.width = Math.max(Math.ceil(size.convert(width * roundingFactor)), 0);
return wrapper;
};
})());
Cufon.getTextDecoration = function(options) {
return {
underline: options.textDecoration === 'underline',
overline: options.textDecoration === 'overline',
'line-through': options.textDecoration === 'line-through'
};
};
if (typeof exports != 'undefined') {
exports.Cufon = Cufon;
}
/*
json2.js
2011-10-19
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or ' '),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, regexp: true */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
var JSON;
if (!JSON) {
JSON = {};
}
(function () {
'use strict';
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
/** @ignore */
Date.prototype.toJSON = function (key) {
return isFinite(this.valueOf())
? this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z'
: null;
};
String.prototype.toJSON =
Number.prototype.toJSON =
/** @ignore */
Boolean.prototype.toJSON = function (key) {
return this.valueOf();
};
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string'
? c
: '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0
? '[]'
: gap
? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
: '[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0
? '{}'
: gap
? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
: '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
/** @ignore */
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
/** @ignore */
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function'
? walk({'': j}, '')
: j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
}());
/**
* Wrapper around `console.log` (when available)
* @param {Any} values Values to log
*/
fabric.log = function() { };
/**
* Wrapper around `console.warn` (when available)
* @param {Any} Values to log as a warning
*/
fabric.warn = function() { };
if (typeof console !== 'undefined') {
if (typeof console.log !== 'undefined' && console.log.apply) {
fabric.log = function() {
return console.log.apply(console, arguments);
};
}
if (typeof console.warn !== 'undefined' && console.warn.apply) {
fabric.warn = function() {
return console.warn.apply(console, arguments);
};
}
}
(function(){
/**
* @private
* @param {String} eventName
* @param {Function} handler
*/
function _removeEventListener(eventName, handler) {
if (!this.__eventListeners[eventName]) return;
if (handler) {
fabric.util.removeFromArray(this.__eventListeners[eventName], handler);
}
else {
this.__eventListeners[eventName].length = 0;
}
}
/**
* Observes specified event
* @deprecated `observe` deprecated since 0.8.34 (use `on` instead)
* @memberOf fabric.Observable
* @alias on
* @param {String|Object} eventName Event name (eg. 'after:render') or object with key/value pairs (eg. {'after:render': handler, 'selection:cleared': handler})
* @param {Function} handler Function that receives a notification when an event of the specified type occurs
* @return {Self} thisArg
* @chainable
*/
function observe(eventName, handler) {
if (!this.__eventListeners) {
this.__eventListeners = { };
}
// one object with key/value pairs was passed
if (arguments.length === 1) {
for (var prop in eventName) {
this.on(prop, eventName[prop]);
}
}
else {
if (!this.__eventListeners[eventName]) {
this.__eventListeners[eventName] = [ ];
}
this.__eventListeners[eventName].push(handler);
}
return this;
}
/**
* Stops event observing for a particular event handler
* @deprecated `stopObserving` deprecated since 0.8.34 (use `off` instead)
* @memberOf fabric.Observable
* @alias off
* @param {String|Object} eventName Event name (eg. 'after:render') or object with key/value pairs (eg. {'after:render': handler, 'selection:cleared': handler})
* @param {Function} handler Function to be deleted from EventListeners
* @return {Self} thisArg
* @chainable
*/
function stopObserving(eventName, handler) {
if (!this.__eventListeners) return;
// one object with key/value pairs was passed
if (arguments.length === 1 && typeof arguments[0] === 'object') {
for (var prop in eventName) {
_removeEventListener.call(this, prop, eventName[prop]);
}
}
else {
_removeEventListener.call(this, eventName, handler);
}
return this;
}
/**
* Fires event with an optional options object
* @deprecated `fire` deprecated since 1.0.7 (use `trigger` instead)
* @memberOf fabric.Observable
* @alias trigger
* @param {String} eventName Event name to fire
* @param {Object} [options] Options object
* @return {Self} thisArg
* @chainable
*/
function fire(eventName, options) {
if (!this.__eventListeners) return;
var listenersForEvent = this.__eventListeners[eventName];
if (!listenersForEvent) return;
for (var i = 0, len = listenersForEvent.length; i < len; i++) {
// avoiding try/catch for perf. reasons
listenersForEvent[i].call(this, options || { });
}
return this;
}
/**
* @namespace fabric.Observable
* @tutorial {@link http://fabricjs.com/fabric-intro-part-2/#events}
* @see {@link http://fabricjs.com/events/|Events demo}
*/
fabric.Observable = {
observe: observe,
stopObserving: stopObserving,
fire: fire,
on: observe,
off: stopObserving,
trigger: fire
};
})();
/**
* @namespace fabric.Collection
*/
fabric.Collection = {
/**
* Adds objects to collection, then renders canvas (if `renderOnAddRemove` is not `false`)
* Objects should be instances of (or inherit from) fabric.Object
* @param [...] Zero or more fabric instances
* @return {Self} thisArg
*/
add: function () {
this._objects.push.apply(this._objects, arguments);
for (var i = arguments.length; i--; ) {
this._onObjectAdded(arguments[i]);
}
this.renderOnAddRemove && this.renderAll();
return this;
},
/**
* Inserts an object into collection at specified index, then renders canvas (if `renderOnAddRemove` is not `false`)
* An object should be an instance of (or inherit from) fabric.Object
* @param {Object} object Object to insert
* @param {Number} index Index to insert object at
* @param {Boolean} nonSplicing When `true`, no splicing (shifting) of objects occurs
* @return {Self} thisArg
*/
insertAt: function (object, index, nonSplicing) {
var objects = this.getObjects();
if (nonSplicing) {
objects[index] = object;
}
else {
objects.splice(index, 0, object);
}
this._onObjectAdded(object);
this.renderOnAddRemove && this.renderAll();
return this;
},
/**
* Removes an object from a collection, then renders canvas (if `renderOnAddRemove` is not `false`)
* @param {Object} object Object to remove
* @return {Self} thisArg
*/
remove: function(object) {
var objects = this.getObjects(),
index = objects.indexOf(object);
// only call onObjectRemoved if an object was actually removed
if (index !== -1) {
objects.splice(index, 1);
this._onObjectRemoved(object);
}
this.renderOnAddRemove && this.renderAll();
return object;
},
/**
* Executes given function for each object in this group
* @param {Function} callback
* Callback invoked with current object as first argument,
* index - as second and an array of all objects - as third.
* Iteration happens in reverse order (for performance reasons).
* Callback is invoked in a context of Global Object (e.g. `window`)
* when no `context` argument is given
*
* @param {Object} context Context (aka thisObject)
* @return {Self} thisArg
*/
forEachObject: function(callback, context) {
var objects = this.getObjects(),
i = objects.length;
while (i--) {
callback.call(context, objects[i], i, objects);
}
return this;
},
/**
* Returns object at specified index
* @param {Number} index
* @return {Self} thisArg
*/
item: function (index) {
return this.getObjects()[index];
},
/**
* Returns true if collection contains no objects
* @return {Boolean} true if collection is empty
*/
isEmpty: function () {
return this.getObjects().length === 0;
},
/**
* Returns a size of a collection (i.e: length of an array containing its objects)
* @return {Number} Collection size
*/
size: function() {
return this.getObjects().length;
},
/**
* Returns true if collection contains an object
* @param {Object} object Object to check against
* @return {Boolean} `true` if collection contains an object
*/
contains: function(object) {
return this.getObjects().indexOf(object) > -1;
},
/**
* Returns number representation of a collection complexity
* @return {Number} complexity
*/
complexity: function () {
return this.getObjects().reduce(function (memo, current) {
memo += current.complexity ? current.complexity() : 0;
return memo;
}, 0);
}
};
(function(global) {
var sqrt = Math.sqrt,
atan2 = Math.atan2;
/**
* @namespace fabric.util
*/
fabric.util = { };
/**
* Removes value from an array.
* Presence of value (and its position in an array) is determined via `Array.prototype.indexOf`
* @static
* @memberOf fabric.util
* @param {Array} array
* @param {Any} value
* @return {Array} original array
*/
function removeFromArray(array, value) {
var idx = array.indexOf(value);
if (idx !== -1) {
array.splice(idx, 1);
}
return array;
}
/**
* Returns random number between 2 specified ones.
* @static
* @memberOf fabric.util
* @param {Number} min lower limit
* @param {Number} max upper limit
* @return {Number} random value (between min and max)
*/
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var PiBy180 = Math.PI / 180;
/**
* Transforms degrees to radians.
* @static
* @memberOf fabric.util
* @param {Number} degrees value in degrees
* @return {Number} value in radians
*/
function degreesToRadians(degrees) {
return degrees * PiBy180;
}
/**
* Transforms radians to degrees.
* @static
* @memberOf fabric.util
* @param {Number} radians value in radians
* @return {Number} value in degrees
*/
function radiansToDegrees(radians) {
return radians / PiBy180;
}
/**
* Rotates `point` around `origin` with `radians`
* @static
* @memberOf fabric.util
* @param {fabric.Point} The point to rotate
* @param {fabric.Point} The origin of the rotation
* @param {Number} The radians of the angle for the rotation
* @return {fabric.Point} The new rotated point
*/
function rotatePoint(point, origin, radians) {
var sin = Math.sin(radians),
cos = Math.cos(radians);
point.subtractEquals(origin);
var rx = point.x * cos - point.y * sin;
var ry = point.x * sin + point.y * cos;
return new fabric.Point(rx, ry).addEquals(origin);
}
/**
* A wrapper around Number#toFixed, which contrary to native method returns number, not string.
* @static
* @memberOf fabric.util
* @param {Number | String} number number to operate on
* @param {Number} fractionDigits number of fraction digits to "leave"
* @return {Number}
*/
function toFixed(number, fractionDigits) {
return parseFloat(Number(number).toFixed(fractionDigits));
}
/**
* Function which always returns `false`.
* @static
* @memberOf fabric.util
* @return {Boolean}
*/
function falseFunction() {
return false;
}
/**
* Returns klass "Class" object of given namespace
* @memberOf fabric.util
* @param {String} type Type of object (eg. 'circle')
* @param {String} namespace Namespace to get klass "Class" object from
* @return {Object} klass "Class"
*/
function getKlass(type, namespace) {
// capitalize first letter only
type = fabric.util.string.camelize(type.charAt(0).toUpperCase() + type.slice(1));
return resolveNamespace(namespace)[type];
}
/**
* Returns object of given namespace
* @memberOf fabric.util
* @param {String} namespace Namespace string e.g. 'fabric.Image.filter' or 'fabric'
* @return {Object} Object for given namespace (default fabric)
*/
function resolveNamespace(namespace) {
if (!namespace) return fabric;
var parts = namespace.split('.'),
len = parts.length,
obj = global || fabric.window;
for (var i = 0; i < len; ++i) {
obj = obj[parts[i]];
}
return obj;
}
/**
* Loads image element from given url and passes it to a callback
* @memberOf fabric.util
* @param {String} url URL representing an image
* @param {Function} callback Callback; invoked with loaded image
* @param {Any} context optional Context to invoke callback in
*/
function loadImage(url, callback, context) {
if (url) {
var img = fabric.util.createImage();
/** @ignore */
img.onload = function () {
callback && callback.call(context, img);
img = img.onload = null;
};
img.src = url;
}
else {
callback && callback.call(context, url);
}
}
/**
* Creates corresponding fabric instances from their object representations
* @static
* @memberOf fabric.util
* @param {Array} objects Objects to enliven
* @param {Function} callback Callback to invoke when all objects are created
* @param {Function} [reviver] Method for further parsing of object elements, called after each fabric object created.
*/
function enlivenObjects(objects, callback, namespace, reviver) {
function onLoaded() {
if (++numLoadedObjects === numTotalObjects) {
if (callback) {
callback(enlivenedObjects);
}
}
}
var enlivenedObjects = [ ],
numLoadedObjects = 0,
numTotalObjects = objects.length;
objects.forEach(function (o, index) {
// if sparse array
if (!o || !o.type) {
onLoaded();
return;
}
var klass = fabric.util.getKlass(o.type, namespace);
if (klass.async) {
klass.fromObject(o, function (obj, error) {
if (!error) {
enlivenedObjects[index] = obj;
reviver && reviver(o, enlivenedObjects[index]);
}
onLoaded();
});
}
else {
enlivenedObjects[index] = klass.fromObject(o);
reviver && reviver(o, enlivenedObjects[index]);
onLoaded();
}
});
}
/**
* Groups SVG elements (usually those retrieved from SVG document)
* @static
* @memberOf fabric.util
* @param {Array} elements SVG elements to group
* @param {Object} [options] Options object
* @return {fabric.Object|fabric.PathGroup}
*/
function groupSVGElements(elements, options, path) {
var object;
if (elements.length > 1) {
object = new fabric.PathGroup(elements, options);
}
else {
object = elements[0];
}
if (typeof path !== 'undefined') {
object.setSourcePath(path);
}
return object;
}
/**
* Populates an object with properties of another object
* @static
* @memberOf fabric.util
* @param {Object} source Source object
* @param {Object} destination Destination object
* @return {Array} properties Propertie names to include
*/
function populateWithProperties(source, destination, properties) {
if (properties && Object.prototype.toString.call(properties) === '[object Array]') {
for (var i = 0, len = properties.length; i < len; i++) {
if (properties[i] in source) {
destination[properties[i]] = source[properties[i]];
}
}
}
}
/**
* Draws a dashed line between two points
*
* This method is used to draw dashed line around selection area.
* See dotted stroke in canvas
*
* @param ctx {Canvas} context
* @param x {Number} start x coordinate
* @param y {Number} start y coordinate
* @param x2 {Number} end x coordinate
* @param y2 {Number} end y coordinate
* @param da {Array} dash array pattern
*/
function drawDashedLine(ctx, x, y, x2, y2, da) {
var dx = x2 - x,
dy = y2 - y,
len = sqrt(dx*dx + dy*dy),
rot = atan2(dy, dx),
dc = da.length,
di = 0,
draw = true;
ctx.save();
ctx.translate(x, y);
ctx.moveTo(0, 0);
ctx.rotate(rot);
x = 0;
while (len > x) {
x += da[di++ % dc];
if (x > len) {
x = len;
}
ctx[draw ? 'lineTo' : 'moveTo'](x, 0);
draw = !draw;
}
ctx.restore();
}
/**
* Creates canvas element and initializes it via excanvas if necessary
* @static
* @memberOf fabric.util
* @param {CanvasElement} [canvasEl] optional canvas element to initialize; when not given, element is created implicitly
* @return {CanvasElement} initialized canvas element
*/
function createCanvasElement(canvasEl) {
canvasEl || (canvasEl = fabric.document.createElement('canvas'));
if (!canvasEl.getContext && typeof G_vmlCanvasManager !== 'undefined') {
G_vmlCanvasManager.initElement(canvasEl);
}
return canvasEl;
}
/**
* Creates image element (works on client and node)
* @static
* @memberOf fabric.util
* @return {HTMLImageElement} HTML image element
*/
function createImage() {
return fabric.isLikelyNode
? new (require('canvas').Image)()
: fabric.document.createElement('img');
}
/**
* Creates accessors (getXXX, setXXX) for a "class", based on "stateProperties" array
* @static
* @memberOf fabric.util
* @param {Object} klass "Class" to create accessors for
*/
function createAccessors(klass) {
var proto = klass.prototype;
for (var i = proto.stateProperties.length; i--; ) {
var propName = proto.stateProperties[i],
capitalizedPropName = propName.charAt(0).toUpperCase() + propName.slice(1),
setterName = 'set' + capitalizedPropName,
getterName = 'get' + capitalizedPropName;
// using `new Function` for better introspection
if (!proto[getterName]) {
proto[getterName] = (function(property) {
return new Function('return this.get("' + property + '")');
})(propName);
}
if (!proto[setterName]) {
proto[setterName] = (function(property) {
return new Function('value', 'return this.set("' + property + '", value)');
})(propName);
}
}
}
/**
* @static
* @memberOf fabric.util
* @param {fabric.Object} receiver Object implementing `clipTo` method
* @param {CanvasRenderingContext2D} ctx Context to clip
*/
function clipContext(receiver, ctx) {
ctx.save();
ctx.beginPath();
receiver.clipTo(ctx);
ctx.clip();
}
/**
* Multiply matrix A by matrix B to nest transformations
* @static
* @memberOf fabric.util
* @param {Array} matrixA First transformMatrix
* @param {Array} matrixB Second transformMatrix
* @return {Array} The product of the two transform matrices
*/
function multiplyTransformMatrices(matrixA, matrixB) {
// Matrix multiply matrixA * matrixB
var a = [
[matrixA[0], matrixA[2], matrixA[4]],
[matrixA[1], matrixA[3], matrixA[5]],
[0 , 0 , 1 ]
];
var b = [
[matrixB[0], matrixB[2], matrixB[4]],
[matrixB[1], matrixB[3], matrixB[5]],
[0 , 0 , 1 ]
];
var result = [];
for (var r=0; r<3; r++) {
result[r] = [];
for (var c=0; c<3; c++) {
var sum = 0;
for (var k=0; k<3; k++) {
sum += a[r][k]*b[k][c];
}
result[r][c] = sum;
}
}
return [
result[0][0],
result[1][0],
result[0][1],
result[1][1],
result[0][2],
result[1][2]
];
}
function getFunctionBody(fn) {
return (String(fn).match(/function[^{]*\{([\s\S]*)\}/) || {})[1];
}
function drawArc(ctx, x, y, coords) {
var rx = coords[0];
var ry = coords[1];
var rot = coords[2];
var large = coords[3];
var sweep = coords[4];
var ex = coords[5];
var ey = coords[6];
var segs = arcToSegments(ex, ey, rx, ry, large, sweep, rot, x, y);
for (var i=0; i 1) {
pl = Math.sqrt(pl);
rx *= pl;
ry *= pl;
}
var a00 = cos_th / rx;
var a01 = sin_th / rx;
var a10 = (-sin_th) / ry;
var a11 = (cos_th) / ry;
var x0 = a00 * ox + a01 * oy;
var y0 = a10 * ox + a11 * oy;
var x1 = a00 * x + a01 * y;
var y1 = a10 * x + a11 * y;
var d = (x1-x0) * (x1-x0) + (y1-y0) * (y1-y0);
var sfactor_sq = 1 / d - 0.25;
if (sfactor_sq < 0) sfactor_sq = 0;
var sfactor = Math.sqrt(sfactor_sq);
if (sweep === large) sfactor = -sfactor;
var xc = 0.5 * (x0 + x1) - sfactor * (y1-y0);
var yc = 0.5 * (y0 + y1) + sfactor * (x1-x0);
var th0 = Math.atan2(y0-yc, x0-xc);
var th1 = Math.atan2(y1-yc, x1-xc);
var th_arc = th1-th0;
if (th_arc < 0 && sweep === 1){
th_arc += 2*Math.PI;
} else if (th_arc > 0 && sweep === 0) {
th_arc -= 2 * Math.PI;
}
var segments = Math.ceil(Math.abs(th_arc / (Math.PI * 0.5 + 0.001)));
var result = [];
for (var i=0; i>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 0) {
n = Number(arguments[1]);
if (n !== n) { // shortcut for verifying if it's NaN
n = 0;
}
else if (n !== 0 && n !== Number.POSITIVE_INFINITY && n !== Number.NEGATIVE_INFINITY) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
};
}
if (!Array.prototype.forEach) {
/**
* Iterates an array, invoking callback for each element
* @param {Function} fn Callback to invoke for each element
* @param {Object} [context] Context to invoke callback in
* @return {Array}
*/
Array.prototype.forEach = function(fn, context) {
for (var i = 0, len = this.length >>> 0; i < len; i++) {
if (i in this) {
fn.call(context, this[i], i, this);
}
}
};
}
if (!Array.prototype.map) {
/**
* Returns a result of iterating over an array, invoking callback for each element
* @param {Function} fn Callback to invoke for each element
* @param {Object} [context] Context to invoke callback in
* @return {Array}
*/
Array.prototype.map = function(fn, context) {
var result = [ ];
for (var i = 0, len = this.length >>> 0; i < len; i++) {
if (i in this) {
result[i] = fn.call(context, this[i], i, this);
}
}
return result;
};
}
if (!Array.prototype.every) {
/**
* Returns true if a callback returns truthy value for all elements in an array
* @param {Function} fn Callback to invoke for each element
* @param {Object} [context] Context to invoke callback in
* @return {Boolean}
*/
Array.prototype.every = function(fn, context) {
for (var i = 0, len = this.length >>> 0; i < len; i++) {
if (i in this && !fn.call(context, this[i], i, this)) {
return false;
}
}
return true;
};
}
if (!Array.prototype.some) {
/**
* Returns true if a callback returns truthy value for at least one element in an array
* @param {Function} fn Callback to invoke for each element
* @param {Object} [context] Context to invoke callback in
* @return {Boolean}
*/
Array.prototype.some = function(fn, context) {
for (var i = 0, len = this.length >>> 0; i < len; i++) {
if (i in this && fn.call(context, this[i], i, this)) {
return true;
}
}
return false;
};
}
if (!Array.prototype.filter) {
/**
* Returns the result of iterating over elements in an array
* @param {Function} fn Callback to invoke for each element
* @param {Object} [context] Context to invoke callback in
* @return {Array}
*/
Array.prototype.filter = function(fn, context) {
var result = [ ], val;
for (var i = 0, len = this.length >>> 0; i < len; i++) {
if (i in this) {
val = this[i]; // in case fn mutates this
if (fn.call(context, val, i, this)) {
result.push(val);
}
}
}
return result;
};
}
if (!Array.prototype.reduce) {
/**
* Returns "folded" (reduced) result of iterating over elements in an array
* @param {Function} fn Callback to invoke for each element
* @param {Object} [context] Context to invoke callback in
* @return {Any}
*/
Array.prototype.reduce = function(fn /*, initial*/) {
var len = this.length >>> 0,
i = 0,
rv;
if (arguments.length > 1) {
rv = arguments[1];
}
else {
do {
if (i in this) {
rv = this[i++];
break;
}
// if array contains no values, no initial value to return
if (++i >= len) {
throw new TypeError();
}
}
while (true);
}
for (; i < len; i++) {
if (i in this) {
rv = fn.call(null, rv, this[i], i, this);
}
}
return rv;
};
}
/* _ES5_COMPAT_END_ */
/**
* Invokes method on all items in a given array
* @memberOf fabric.util.array
* @param {Array} array Array to iterate over
* @param {String} method Name of a method to invoke
* @return {Array}
*/
function invoke(array, method) {
var args = slice.call(arguments, 2), result = [ ];
for (var i = 0, len = array.length; i < len; i++) {
result[i] = args.length ? array[i][method].apply(array[i], args) : array[i][method].call(array[i]);
}
return result;
}
/**
* Finds maximum value in array (not necessarily "first" one)
* @memberOf fabric.util.array
* @param {Array} array Array to iterate over
* @param {String} byProperty
* @return {Any}
*/
function max(array, byProperty) {
if (!array || array.length === 0) return undefined;
var i = array.length - 1,
result = byProperty ? array[i][byProperty] : array[i];
if (byProperty) {
while (i--) {
if (array[i][byProperty] >= result) {
result = array[i][byProperty];
}
}
}
else {
while (i--) {
if (array[i] >= result) {
result = array[i];
}
}
}
return result;
}
/**
* Finds minimum value in array (not necessarily "first" one)
* @memberOf fabric.util.array
* @param {Array} array Array to iterate over
* @param {String} byProperty
* @return {Any}
*/
function min(array, byProperty) {
if (!array || array.length === 0) return undefined;
var i = array.length - 1,
result = byProperty ? array[i][byProperty] : array[i];
if (byProperty) {
while (i--) {
if (array[i][byProperty] < result) {
result = array[i][byProperty];
}
}
}
else {
while (i--) {
if (array[i] < result) {
result = array[i];
}
}
}
return result;
}
/**
* @namespace fabric.util.array
*/
fabric.util.array = {
invoke: invoke,
min: min,
max: max
};
})();
(function(){
/**
* Copies all enumerable properties of one object to another
* @memberOf fabric.util.object
* @param {Object} destination Where to copy to
* @param {Object} source Where to copy from
* @return {Object}
*/
function extend(destination, source) {
// JScript DontEnum bug is not taken care of
for (var property in source) {
destination[property] = source[property];
}
return destination;
}
/**
* Creates an empty object and copies all enumerable properties of another object to it
* @memberOf fabric.util.object
* @param {Object} object Object to clone
* @return {Object}
*/
function clone(object) {
return extend({ }, object);
}
/** @namespace fabric.util.object */
fabric.util.object = {
extend: extend,
clone: clone
};
})();
(function() {
/* _ES5_COMPAT_START_ */
if (!String.prototype.trim) {
/**
* Trims a string (removing whitespace from the beginning and the end)
* @function external:String#trim
* @see String#trim on MDN
*/
String.prototype.trim = function () {
// this trim is not fully ES3 or ES5 compliant, but it should cover most cases for now
return this.replace(/^[\s\xA0]+/, '').replace(/[\s\xA0]+$/, '');
};
}
/* _ES5_COMPAT_END_ */
/**
* Camelizes a string
* @memberOf fabric.util.string
* @param {String} string String to camelize
* @return {String} Camelized version of a string
*/
function camelize(string) {
return string.replace(/-+(.)?/g, function(match, character) {
return character ? character.toUpperCase() : '';
});
}
/**
* Capitalizes a string
* @memberOf fabric.util.string
* @param {String} string String to capitalize
* @return {String} Capitalized version of a string
*/
function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
/**
* Escapes XML in a string
* @memberOf fabric.util.string
* @param {String} string String to escape
* @return {String} Escaped version of a string
*/
function escapeXml(string) {
return string.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(//g, '>');
}
/**
* String utilities
* @namespace fabric.util.string
*/
fabric.util.string = {
camelize: camelize,
capitalize: capitalize,
escapeXml: escapeXml
};
}());
/* _ES5_COMPAT_START_ */
(function() {
var slice = Array.prototype.slice,
apply = Function.prototype.apply,
Dummy = function() { };
if (!Function.prototype.bind) {
/**
* Cross-browser approximation of ES5 Function.prototype.bind (not fully spec conforming)
* @see Function#bind on MDN
* @param {Object} thisArg Object to bind function to
* @param {Any[]} [...] Values to pass to a bound function
* @return {Function}
*/
Function.prototype.bind = function(thisArg) {
var fn = this, args = slice.call(arguments, 1), bound;
if (args.length) {
bound = function() {
return apply.call(fn, this instanceof Dummy ? this : thisArg, args.concat(slice.call(arguments)));
};
}
else {
/** @ignore */
bound = function() {
return apply.call(fn, this instanceof Dummy ? this : thisArg, arguments);
};
}
Dummy.prototype = this.prototype;
bound.prototype = new Dummy();
return bound;
};
}
})();
/* _ES5_COMPAT_END_ */
(function() {
var slice = Array.prototype.slice, emptyFunction = function() { };
var IS_DONTENUM_BUGGY = (function(){
for (var p in { toString: 1 }) {
if (p === 'toString') return false;
}
return true;
})();
/** @ignore */
var addMethods = function(klass, source, parent) {
for (var property in source) {
if (property in klass.prototype &&
typeof klass.prototype[property] === 'function' &&
(source[property] + '').indexOf('callSuper') > -1) {
klass.prototype[property] = (function(property) {
return function() {
var superclass = this.constructor.superclass;
this.constructor.superclass = parent;
var returnValue = source[property].apply(this, arguments);
this.constructor.superclass = superclass;
if (property !== 'initialize') {
return returnValue;
}
};
})(property);
}
else {
klass.prototype[property] = source[property];
}
if (IS_DONTENUM_BUGGY) {
if (source.toString !== Object.prototype.toString) {
klass.prototype.toString = source.toString;
}
if (source.valueOf !== Object.prototype.valueOf) {
klass.prototype.valueOf = source.valueOf;
}
}
}
};
function Subclass() { }
function callSuper(methodName) {
var fn = this.constructor.superclass.prototype[methodName];
return (arguments.length > 1)
? fn.apply(this, slice.call(arguments, 1))
: fn.call(this);
}
/**
* Helper for creation of "classes".
* @memberOf fabric.util
* @param parent optional "Class" to inherit from
* @param properties Properties shared by all instances of this class
* (be careful modifying objects defined here as this would affect all instances)
*/
function createClass() {
var parent = null,
properties = slice.call(arguments, 0);
if (typeof properties[0] === 'function') {
parent = properties.shift();
}
function klass() {
this.initialize.apply(this, arguments);
}
klass.superclass = parent;
klass.subclasses = [ ];
if (parent) {
Subclass.prototype = parent.prototype;
klass.prototype = new Subclass();
parent.subclasses.push(klass);
}
for (var i = 0, length = properties.length; i < length; i++) {
addMethods(klass, properties[i], parent);
}
if (!klass.prototype.initialize) {
klass.prototype.initialize = emptyFunction;
}
klass.prototype.constructor = klass;
klass.prototype.callSuper = callSuper;
return klass;
}
fabric.util.createClass = createClass;
})();
(function () {
/* EVENT HANDLING */
function areHostMethods(object) {
var methodNames = Array.prototype.slice.call(arguments, 1),
t, i, len = methodNames.length;
for (i = 0; i < len; i++) {
t = typeof object[methodNames[i]];
if (!(/^(?:function|object|unknown)$/).test(t)) return false;
}
return true;
}
var getUniqueId = (function () {
var uid = 0;
return function (element) {
return element.__uniqueID || (element.__uniqueID = 'uniqueID__' + uid++);
};
})();
/** @ignore */
var getElement, setElement;
(function () {
var elements = { };
/** @ignore */
getElement = function (uid) {
return elements[uid];
};
/** @ignore */
setElement = function (uid, element) {
elements[uid] = element;
};
})();
function createListener(uid, handler) {
return {
handler: handler,
wrappedHandler: createWrappedHandler(uid, handler)
};
}
function createWrappedHandler(uid, handler) {
return function (e) {
handler.call(getElement(uid), e || fabric.window.event);
};
}
function createDispatcher(uid, eventName) {
return function (e) {
if (handlers[uid] && handlers[uid][eventName]) {
var handlersForEvent = handlers[uid][eventName];
for (var i = 0, len = handlersForEvent.length; i < len; i++) {
handlersForEvent[i].call(this, e || fabric.window.event);
}
}
};
}
var shouldUseAddListenerRemoveListener = (
areHostMethods(fabric.document.documentElement, 'addEventListener', 'removeEventListener') &&
areHostMethods(fabric.window, 'addEventListener', 'removeEventListener')),
shouldUseAttachEventDetachEvent = (
areHostMethods(fabric.document.documentElement, 'attachEvent', 'detachEvent') &&
areHostMethods(fabric.window, 'attachEvent', 'detachEvent')),
// IE branch
listeners = { },
// DOM L0 branch
handlers = { },
addListener, removeListener;
if (shouldUseAddListenerRemoveListener) {
/** @ignore */
addListener = function (element, eventName, handler) {
element.addEventListener(eventName, handler, false);
};
/** @ignore */
removeListener = function (element, eventName, handler) {
element.removeEventListener(eventName, handler, false);
};
}
else if (shouldUseAttachEventDetachEvent) {
/** @ignore */
addListener = function (element, eventName, handler) {
var uid = getUniqueId(element);
setElement(uid, element);
if (!listeners[uid]) {
listeners[uid] = { };
}
if (!listeners[uid][eventName]) {
listeners[uid][eventName] = [ ];
}
var listener = createListener(uid, handler);
listeners[uid][eventName].push(listener);
element.attachEvent('on' + eventName, listener.wrappedHandler);
};
/** @ignore */
removeListener = function (element, eventName, handler) {
var uid = getUniqueId(element), listener;
if (listeners[uid] && listeners[uid][eventName]) {
for (var i = 0, len = listeners[uid][eventName].length; i < len; i++) {
listener = listeners[uid][eventName][i];
if (listener && listener.handler === handler) {
element.detachEvent('on' + eventName, listener.wrappedHandler);
listeners[uid][eventName][i] = null;
}
}
}
};
}
else {
/** @ignore */
addListener = function (element, eventName, handler) {
var uid = getUniqueId(element);
if (!handlers[uid]) {
handlers[uid] = { };
}
if (!handlers[uid][eventName]) {
handlers[uid][eventName] = [ ];
var existingHandler = element['on' + eventName];
if (existingHandler) {
handlers[uid][eventName].push(existingHandler);
}
element['on' + eventName] = createDispatcher(uid, eventName);
}
handlers[uid][eventName].push(handler);
};
/** @ignore */
removeListener = function (element, eventName, handler) {
var uid = getUniqueId(element);
if (handlers[uid] && handlers[uid][eventName]) {
var handlersForEvent = handlers[uid][eventName];
for (var i = 0, len = handlersForEvent.length; i < len; i++) {
if (handlersForEvent[i] === handler) {
handlersForEvent.splice(i, 1);
}
}
}
};
}
/**
* Adds an event listener to an element
* @function
* @memberOf fabric.util
* @param {HTMLElement} element
* @param {String} eventName
* @param {Function} handler
*/
fabric.util.addListener = addListener;
/**
* Removes an event listener from an element
* @function
* @memberOf fabric.util
* @param {HTMLElement} element
* @param {String} eventName
* @param {Function} handler
*/
fabric.util.removeListener = removeListener;
/**
* Cross-browser wrapper for getting event's coordinates
* @memberOf fabric.util
* @param {Event} event Event object
* @param {HTMLCanvasElement} upperCanvasEl <canvas> element on which object selection is drawn
*/
function getPointer(event, upperCanvasEl) {
event || (event = fabric.window.event);
var element = event.target || (typeof event.srcElement !== 'unknown' ? event.srcElement : null),
body = fabric.document.body || {scrollLeft: 0, scrollTop: 0},
docElement = fabric.document.documentElement,
orgElement = element,
scrollLeft = 0,
scrollTop = 0,
firstFixedAncestor;
while (element && element.parentNode && !firstFixedAncestor) {
element = element.parentNode;
if (element !== fabric.document &&
fabric.util.getElementStyle(element, 'position') === 'fixed') {
firstFixedAncestor = element;
}
if (element !== fabric.document &&
orgElement !== upperCanvasEl &&
fabric.util.getElementStyle(element, 'position') === 'absolute') {
scrollLeft = 0;
scrollTop = 0;
}
else if (element === fabric.document) {
scrollLeft = body.scrollLeft || docElement.scrollLeft || 0;
scrollTop = body.scrollTop || docElement.scrollTop || 0;
}
else {
scrollLeft += element.scrollLeft || 0;
scrollTop += element.scrollTop || 0;
}
}
return {
x: pointerX(event) + scrollLeft,
y: pointerY(event) + scrollTop
};
}
var pointerX = function(event) {
// looks like in IE (<9) clientX at certain point (apparently when mouseup fires on VML element)
// is represented as COM object, with all the consequences, like "unknown" type and error on [[Get]]
// need to investigate later
return (typeof event.clientX !== 'unknown' ? event.clientX : 0);
};
var pointerY = function(event) {
return (typeof event.clientY !== 'unknown' ? event.clientY : 0);
};
if (fabric.isTouchSupported) {
pointerX = function(event) {
if (event.type !== 'touchend') {
return (event.touches && event.touches[0] ?
(event.touches[0].pageX - (event.touches[0].pageX - event.touches[0].clientX)) || event.clientX : event.clientX);
}
return (event.changedTouches && event.changedTouches[0]
? (event.changedTouches[0].pageX - (event.changedTouches[0].pageX - event.changedTouches[0].clientX)) || event.clientX : event.clientX);
};
pointerY = function(event) {
if (event.type !== 'touchend') {
return (event.touches && event.touches[0]
? (event.touches[0].pageY - (event.touches[0].pageY - event.touches[0].clientY)) || event.clientY : event.clientY);
}
return (event.changedTouches && event.changedTouches[0]
? (event.changedTouches[0].pageY - (event.changedTouches[0].pageY - event.changedTouches[0].clientY)) || event.clientY : event.clientY);
};
}
fabric.util.getPointer = getPointer;
fabric.util.object.extend(fabric.util, fabric.Observable);
})();
(function () {
/**
* Cross-browser wrapper for setting element's style
* @memberOf fabric.util
* @param {HTMLElement} element
* @param {Object} styles
* @return {HTMLElement} Element that was passed as a first argument
*/
function setStyle(element, styles) {
var elementStyle = element.style;
if (!elementStyle) {
return element;
}
if (typeof styles === 'string') {
element.style.cssText += ';' + styles;
return styles.indexOf('opacity') > -1
? setOpacity(element, styles.match(/opacity:\s*(\d?\.?\d*)/)[1])
: element;
}
for (var property in styles) {
if (property === 'opacity') {
setOpacity(element, styles[property]);
}
else {
var normalizedProperty = (property === 'float' || property === 'cssFloat')
? (typeof elementStyle.styleFloat === 'undefined' ? 'cssFloat' : 'styleFloat')
: property;
elementStyle[normalizedProperty] = styles[property];
}
}
return element;
}
var parseEl = fabric.document.createElement('div'),
supportsOpacity = typeof parseEl.style.opacity === 'string',
supportsFilters = typeof parseEl.style.filter === 'string',
reOpacity = /alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,
/** @ignore */
setOpacity = function (element) { return element; };
if (supportsOpacity) {
/** @ignore */
setOpacity = function(element, value) {
element.style.opacity = value;
return element;
};
}
else if (supportsFilters) {
/** @ignore */
setOpacity = function(element, value) {
var es = element.style;
if (element.currentStyle && !element.currentStyle.hasLayout) {
es.zoom = 1;
}
if (reOpacity.test(es.filter)) {
value = value >= 0.9999 ? '' : ('alpha(opacity=' + (value * 100) + ')');
es.filter = es.filter.replace(reOpacity, value);
}
else {
es.filter += ' alpha(opacity=' + (value * 100) + ')';
}
return element;
};
}
fabric.util.setStyle = setStyle;
})();
(function() {
var _slice = Array.prototype.slice;
/**
* Takes id and returns an element with that id (if one exists in a document)
* @memberOf fabric.util
* @param {String|HTMLElement} id
* @return {HTMLElement|null}
*/
function getById(id) {
return typeof id === 'string' ? fabric.document.getElementById(id) : id;
}
/**
* Converts an array-like object (e.g. arguments or NodeList) to an array
* @memberOf fabric.util
* @param {Object} arrayLike
* @return {Array}
*/
var toArray = function(arrayLike) {
return _slice.call(arrayLike, 0);
};
var sliceCanConvertNodelists;
try {
sliceCanConvertNodelists = toArray(fabric.document.childNodes) instanceof Array;
}
catch(err) { }
if (!sliceCanConvertNodelists) {
toArray = function(arrayLike) {
var arr = new Array(arrayLike.length), i = arrayLike.length;
while (i--) {
arr[i] = arrayLike[i];
}
return arr;
};
}
/**
* Creates specified element with specified attributes
* @memberOf fabric.util
* @param {String} tagName Type of an element to create
* @param {Object} [attributes] Attributes to set on an element
* @return {HTMLElement} Newly created element
*/
function makeElement(tagName, attributes) {
var el = fabric.document.createElement(tagName);
for (var prop in attributes) {
if (prop === 'class') {
el.className = attributes[prop];
}
else if (prop === 'for') {
el.htmlFor = attributes[prop];
}
else {
el.setAttribute(prop, attributes[prop]);
}
}
return el;
}
/**
* Adds class to an element
* @memberOf fabric.util
* @param {HTMLElement} element Element to add class to
* @param {String} className Class to add to an element
*/
function addClass(element, className) {
if ((' ' + element.className + ' ').indexOf(' ' + className + ' ') === -1) {
element.className += (element.className ? ' ' : '') + className;
}
}
/**
* Wraps element with another element
* @memberOf fabric.util
* @param {HTMLElement} element Element to wrap
* @param {HTMLElement|String} wrapper Element to wrap with
* @param {Object} [attributes] Attributes to set on a wrapper
* @return {HTMLElement} wrapper
*/
function wrapElement(element, wrapper, attributes) {
if (typeof wrapper === 'string') {
wrapper = makeElement(wrapper, attributes);
}
if (element.parentNode) {
element.parentNode.replaceChild(wrapper, element);
}
wrapper.appendChild(element);
return wrapper;
}
/**
* Returns offset for a given element
* @function
* @memberOf fabric.util
* @param {HTMLElement} element Element to get offset for
* @return {Object} Object with "left" and "top" properties
*/
function getElementOffset(element) {
var docElem, win,
box = {left: 0, top: 0},
doc = element && element.ownerDocument,
offset = {left: 0, top: 0},
offsetAttributes = {
'borderLeftWidth': 'left',
'borderTopWidth': 'top',
'paddingLeft': 'left',
'paddingTop': 'top'
};
if (!doc){
return {left: 0, top: 0};
}
for (var attr in offsetAttributes) {
offset[offsetAttributes[attr]] += parseInt(getElementStyle(element, attr), 10) || 0;
}
docElem = doc.documentElement;
if ( typeof element.getBoundingClientRect !== "undefined" ) {
box = element.getBoundingClientRect();
}
if(doc != null && doc === doc.window){
win = doc;
} else {
win = doc.nodeType === 9 && (doc.defaultView || doc.parentWindow);
}
return {
left: box.left + (win.pageXOffset || docElem.scrollLeft) - (docElem.clientLeft || 0) + offset.left,
top: box.top + (win.pageYOffset || docElem.scrollTop) - (docElem.clientTop || 0) + offset.top
};
}
/**
* Returns style attribute value of a given element
* @memberOf fabric.util
* @param {HTMLElement} element Element to get style attribute for
* @param {String} attr Style attribute to get for element
* @return {String} Style attribute value of the given element.
*/
function getElementStyle(element, attr) {
if (!element.style) {
element.style = { };
}
if (fabric.document.defaultView && fabric.document.defaultView.getComputedStyle) {
return fabric.document.defaultView.getComputedStyle(element, null)[attr];
}
else {
var value = element.style[attr];
if (!value && element.currentStyle) value = element.currentStyle[attr];
return value;
}
}
(function () {
var style = fabric.document.documentElement.style;
var selectProp = 'userSelect' in style
? 'userSelect'
: 'MozUserSelect' in style
? 'MozUserSelect'
: 'WebkitUserSelect' in style
? 'WebkitUserSelect'
: 'KhtmlUserSelect' in style
? 'KhtmlUserSelect'
: '';
/**
* Makes element unselectable
* @memberOf fabric.util
* @param {HTMLElement} element Element to make unselectable
* @return {HTMLElement} Element that was passed in
*/
function makeElementUnselectable(element) {
if (typeof element.onselectstart !== 'undefined') {
element.onselectstart = fabric.util.falseFunction;
}
if (selectProp) {
element.style[selectProp] = 'none';
}
else if (typeof element.unselectable === 'string') {
element.unselectable = 'on';
}
return element;
}
/**
* Makes element selectable
* @memberOf fabric.util
* @param {HTMLElement} element Element to make selectable
* @return {HTMLElement} Element that was passed in
*/
function makeElementSelectable(element) {
if (typeof element.onselectstart !== 'undefined') {
element.onselectstart = null;
}
if (selectProp) {
element.style[selectProp] = '';
}
else if (typeof element.unselectable === 'string') {
element.unselectable = '';
}
return element;
}
fabric.util.makeElementUnselectable = makeElementUnselectable;
fabric.util.makeElementSelectable = makeElementSelectable;
})();
(function() {
/**
* Inserts a script element with a given url into a document; invokes callback, when that script is finished loading
* @memberOf fabric.util
* @param {String} url URL of a script to load
* @param {Function} callback Callback to execute when script is finished loading
*/
function getScript(url, callback) {
var headEl = fabric.document.getElementsByTagName("head")[0],
scriptEl = fabric.document.createElement('script'),
loading = true;
/** @ignore */
scriptEl.onload = /** @ignore */ scriptEl.onreadystatechange = function(e) {
if (loading) {
if (typeof this.readyState === 'string' &&
this.readyState !== 'loaded' &&
this.readyState !== 'complete') return;
loading = false;
callback(e || fabric.window.event);
scriptEl = scriptEl.onload = scriptEl.onreadystatechange = null;
}
};
scriptEl.src = url;
headEl.appendChild(scriptEl);
// causes issue in Opera
// headEl.removeChild(scriptEl);
}
fabric.util.getScript = getScript;
})();
fabric.util.getById = getById;
fabric.util.toArray = toArray;
fabric.util.makeElement = makeElement;
fabric.util.addClass = addClass;
fabric.util.wrapElement = wrapElement;
fabric.util.getElementOffset = getElementOffset;
fabric.util.getElementStyle = getElementStyle;
})();
(function(){
function addParamToUrl(url, param) {
return url + (/\?/.test(url) ? '&' : '?') + param;
}
var makeXHR = (function() {
var factories = [
function() { return new ActiveXObject("Microsoft.XMLHTTP"); },
function() { return new ActiveXObject("Msxml2.XMLHTTP"); },
function() { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); },
function() { return new XMLHttpRequest(); }
];
for (var i = factories.length; i--; ) {
try {
var req = factories[i]();
if (req) {
return factories[i];
}
}
catch (err) { }
}
})();
function emptyFn() { }
/**
* Cross-browser abstraction for sending XMLHttpRequest
* @memberOf fabric.util
* @param {String} url URL to send XMLHttpRequest to
* @param {Object} [options] Options object
* @param {String} [options.method="GET"]
* @param {Function} options.onComplete Callback to invoke when request is completed
* @return {XMLHttpRequest} request
*/
function request(url, options) {
options || (options = { });
var method = options.method ? options.method.toUpperCase() : 'GET',
onComplete = options.onComplete || function() { },
xhr = makeXHR(),
body;
/** @ignore */
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
onComplete(xhr);
xhr.onreadystatechange = emptyFn;
}
};
if (method === 'GET') {
body = null;
if (typeof options.parameters === 'string') {
url = addParamToUrl(url, options.parameters);
}
}
xhr.open(method, url, true);
if (method === 'POST' || method === 'PUT') {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
xhr.send(body);
return xhr;
}
fabric.util.request = request;
})();
(function() {
/**
* Changes value from one to another within certain period of time, invoking callbacks as value is being changed.
* @memberOf fabric.util
* @param {Object} [options] Animation options
* @param {Function} [options.onChange] Callback; invoked on every value change
* @param {Function} [options.onComplete] Callback; invoked when value change is completed
* @param {Number} [options.startValue=0] Starting value
* @param {Number} [options.endValue=100] Ending value
* @param {Number} [options.byValue=100] Value to modify the property by
* @param {Function} [options.easing] Easing function
* @param {Number} [options.duration=500] Duration of change
*/
function animate(options) {
options || (options = { });
var start = +new Date(),
duration = options.duration || 500,
finish = start + duration, time,
onChange = options.onChange || function() { },
abort = options.abort || function() { return false; },
easing = options.easing || function(t, b, c, d) {return -c * Math.cos(t/d * (Math.PI/2)) + c + b;},
startValue = 'startValue' in options ? options.startValue : 0,
endValue = 'endValue' in options ? options.endValue : 100,
byValue = options.byValue || endValue - startValue;
options.onStart && options.onStart();
(function tick() {
time = +new Date();
var currentTime = time > finish ? duration : (time - start);
if (abort()) {
options.onComplete && options.onComplete();
return;
}
onChange(easing(currentTime, startValue, byValue, duration));
if (time > finish) {
options.onComplete && options.onComplete();
return;
}
requestAnimFrame(tick);
})();
}
var _requestAnimFrame = fabric.window.requestAnimationFrame ||
fabric.window.webkitRequestAnimationFrame ||
fabric.window.mozRequestAnimationFrame ||
fabric.window.oRequestAnimationFrame ||
fabric.window.msRequestAnimationFrame ||
function(callback) {
fabric.window.setTimeout(callback, 1000 / 60);
};
/**
* requestAnimationFrame polyfill based on http://paulirish.com/2011/requestanimationframe-for-smart-animating/
* @memberOf fabric.util
* @param {Function} callback Callback to invoke
* @param {DOMElement} element optional Element to associate with animation
*/
var requestAnimFrame = function() {
return _requestAnimFrame.apply(fabric.window, arguments);
};
fabric.util.animate = animate;
fabric.util.requestAnimFrame = requestAnimFrame;
})();
(function() {
/**
* Quadratic easing in
* @memberOf fabric.util.ease
*/
function easeInQuad(t, b, c, d) {
return c*(t/=d)*t + b;
}
/**
* Quadratic easing out
* @memberOf fabric.util.ease
*/
function easeOutQuad(t, b, c, d) {
return -c *(t/=d)*(t-2) + b;
}
/**
* Quadratic easing in and out
* @memberOf fabric.util.ease
*/
function easeInOutQuad(t, b, c, d) {
t /= (d/2);
if (t < 1) return c/2*t*t + b;
return -c/2 * ((--t)*(t-2) - 1) + b;
}
/**
* Cubic easing in
* @memberOf fabric.util.ease
*/
function easeInCubic(t, b, c, d) {
return c*(t/=d)*t*t + b;
}
/**
* Cubic easing out
* @memberOf fabric.util.ease
*/
function easeOutCubic(t, b, c, d) {
return c*((t=t/d-1)*t*t + 1) + b;
}
/**
* Cubic easing in and out
* @memberOf fabric.util.ease
*/
function easeInOutCubic(t, b, c, d) {
t /= d/2;
if (t < 1) return c/2*t*t*t + b;
return c/2*((t-=2)*t*t + 2) + b;
}
/**
* Quartic easing in
* @memberOf fabric.util.ease
*/
function easeInQuart(t, b, c, d) {
return c*(t/=d)*t*t*t + b;
}
/**
* Quartic easing out
* @memberOf fabric.util.ease
*/
function easeOutQuart(t, b, c, d) {
return -c * ((t=t/d-1)*t*t*t - 1) + b;
}
/**
* Quartic easing in and out
* @memberOf fabric.util.ease
*/
function easeInOutQuart(t, b, c, d) {
t /= d/2;
if (t < 1) return c/2*t*t*t*t + b;
return -c/2 * ((t-=2)*t*t*t - 2) + b;
}
/**
* Quintic easing in
* @memberOf fabric.util.ease
*/
function easeInQuint(t, b, c, d) {
return c*(t/=d)*t*t*t*t + b;
}
/**
* Quintic easing out
* @memberOf fabric.util.ease
*/
function easeOutQuint(t, b, c, d) {
return c*((t=t/d-1)*t*t*t*t + 1) + b;
}
/**
* Quintic easing in and out
* @memberOf fabric.util.ease
*/
function easeInOutQuint(t, b, c, d) {
t /= d/2;
if (t < 1) return c/2*t*t*t*t*t + b;
return c/2*((t-=2)*t*t*t*t + 2) + b;
}
/**
* Sinusoidal easing in
* @memberOf fabric.util.ease
*/
function easeInSine(t, b, c, d) {
return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
}
/**
* Sinusoidal easing out
* @memberOf fabric.util.ease
*/
function easeOutSine(t, b, c, d) {
return c * Math.sin(t/d * (Math.PI/2)) + b;
}
/**
* Sinusoidal easing in and out
* @memberOf fabric.util.ease
*/
function easeInOutSine(t, b, c, d) {
return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
}
/**
* Exponential easing in
* @memberOf fabric.util.ease
*/
function easeInExpo(t, b, c, d) {
return (t===0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
}
/**
* Exponential easing out
* @memberOf fabric.util.ease
*/
function easeOutExpo(t, b, c, d) {
return (t===d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
}
/**
* Exponential easing in and out
* @memberOf fabric.util.ease
*/
function easeInOutExpo(t, b, c, d) {
if (t===0) return b;
if (t===d) return b+c;
t /= d/2;
if (t < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
}
/**
* Circular easing in
* @memberOf fabric.util.ease
*/
function easeInCirc(t, b, c, d) {
return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
}
/**
* Circular easing out
* @memberOf fabric.util.ease
*/
function easeOutCirc(t, b, c, d) {
return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
}
/**
* Circular easing in and out
* @memberOf fabric.util.ease
*/
function easeInOutCirc(t, b, c, d) {
t /= d/2;
if (t < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
}
/**
* Elastic easing in
* @memberOf fabric.util.ease
*/
function easeInElastic(t, b, c, d) {
var s=1.70158;var p=0;var a=c;
if (t===0) return b;
t /= d;
if (t===1) return b+c;
if (!p) p=d*0.3;
if (a < Math.abs(c)) { a=c; s=p/4; }
else s = p/(2*Math.PI) * Math.asin (c/a);
return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
}
/**
* Elastic easing out
* @memberOf fabric.util.ease
*/
function easeOutElastic(t, b, c, d) {
var s=1.70158;var p=0;var a=c;
if (t===0) return b;
t /= d;
if (t===1) return b+c;
if (!p) p=d*0.3;
if (a < Math.abs(c)) { a=c; s=p/4; }
else s = p/(2*Math.PI) * Math.asin (c/a);
return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
}
/**
* Elastic easing in and out
* @memberOf fabric.util.ease
*/
function easeInOutElastic(t, b, c, d) {
var s=1.70158;var p=0;var a=c;
if (t===0) return b;
t /= d/2;
if (t===2) return b+c;
if (!p) p=d*(0.3*1.5);
if (a < Math.abs(c)) { a=c; s=p/4; }
else s = p/(2*Math.PI) * Math.asin (c/a);
if (t < 1) return -0.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*0.5 + c + b;
}
/**
* Backwards easing in
* @memberOf fabric.util.ease
*/
function easeInBack(t, b, c, d, s) {
if (s === undefined) s = 1.70158;
return c*(t/=d)*t*((s+1)*t - s) + b;
}
/**
* Backwards easing out
* @memberOf fabric.util.ease
*/
function easeOutBack(t, b, c, d, s) {
if (s === undefined) s = 1.70158;
return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
}
/**
* Backwards easing in and out
* @memberOf fabric.util.ease
*/
function easeInOutBack(t, b, c, d, s) {
if (s === undefined) s = 1.70158;
t /= d/2;
if (t < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
}
/**
* Bouncing easing in
* @memberOf fabric.util.ease
*/
function easeInBounce(t, b, c, d) {
return c - easeOutBounce (d-t, 0, c, d) + b;
}
/**
* Bouncing easing out
* @memberOf fabric.util.ease
*/
function easeOutBounce(t, b, c, d) {
if ((t/=d) < (1/2.75)) {
return c*(7.5625*t*t) + b;
} else if (t < (2/2.75)) {
return c*(7.5625*(t-=(1.5/2.75))*t + 0.75) + b;
} else if (t < (2.5/2.75)) {
return c*(7.5625*(t-=(2.25/2.75))*t + 0.9375) + b;
} else {
return c*(7.5625*(t-=(2.625/2.75))*t + 0.984375) + b;
}
}
/**
* Bouncing easing in and out
* @memberOf fabric.util.ease
*/
function easeInOutBounce(t, b, c, d) {
if (t < d/2) return easeInBounce (t*2, 0, c, d) * 0.5 + b;
return easeOutBounce (t*2-d, 0, c, d) * 0.5 + c*0.5 + b;
}
/**
* Easing functions
* See Easing Equations by Robert Penner
* @namespace fabric.util.ease
*/
fabric.util.ease = {
easeInQuad: easeInQuad,
easeOutQuad: easeOutQuad,
easeInOutQuad: easeInOutQuad,
easeInCubic: easeInCubic,
easeOutCubic: easeOutCubic,
easeInOutCubic: easeInOutCubic,
easeInQuart: easeInQuart,
easeOutQuart: easeOutQuart,
easeInOutQuart: easeInOutQuart,
easeInQuint: easeInQuint,
easeOutQuint: easeOutQuint,
easeInOutQuint: easeInOutQuint,
easeInSine: easeInSine,
easeOutSine: easeOutSine,
easeInOutSine: easeInOutSine,
easeInExpo: easeInExpo,
easeOutExpo: easeOutExpo,
easeInOutExpo: easeInOutExpo,
easeInCirc: easeInCirc,
easeOutCirc: easeOutCirc,
easeInOutCirc: easeInOutCirc,
easeInElastic: easeInElastic,
easeOutElastic: easeOutElastic,
easeInOutElastic: easeInOutElastic,
easeInBack: easeInBack,
easeOutBack: easeOutBack,
easeInOutBack: easeInOutBack,
easeInBounce: easeInBounce,
easeOutBounce: easeOutBounce,
easeInOutBounce: easeInOutBounce
};
}());
(function(global) {
"use strict";
/**
* @name fabric
* @namespace
*/
var fabric = global.fabric || (global.fabric = { }),
extend = fabric.util.object.extend,
capitalize = fabric.util.string.capitalize,
clone = fabric.util.object.clone,
toFixed = fabric.util.toFixed,
multiplyTransformMatrices = fabric.util.multiplyTransformMatrices;
fabric.SHARED_ATTRIBUTES = [
"transform",
"fill", "fill-opacity", "fill-rule",
"opacity",
"stroke", "stroke-dasharray", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width"
];
var attributesMap = {
'fill-opacity': 'fillOpacity',
'fill-rule': 'fillRule',
'font-family': 'fontFamily',
'font-size': 'fontSize',
'font-style': 'fontStyle',
'font-weight': 'fontWeight',
'cx': 'left',
'x': 'left',
'r': 'radius',
'stroke-dasharray': 'strokeDashArray',
'stroke-linecap': 'strokeLineCap',
'stroke-linejoin': 'strokeLineJoin',
'stroke-miterlimit':'strokeMiterLimit',
'stroke-opacity': 'strokeOpacity',
'stroke-width': 'strokeWidth',
'text-decoration': 'textDecoration',
'cy': 'top',
'y': 'top',
'transform': 'transformMatrix'
};
var colorAttributes = {
'stroke': 'strokeOpacity',
'fill': 'fillOpacity'
};
function normalizeAttr(attr) {
// transform attribute names
if (attr in attributesMap) {
return attributesMap[attr];
}
return attr;
}
function normalizeValue(attr, value, parentAttributes) {
var isArray;
if ((attr === 'fill' || attr === 'stroke') && value === 'none') {
value = '';
}
else if (attr === 'fillRule') {
value = (value === 'evenodd') ? 'destination-over' : value;
}
else if (attr === 'strokeDashArray') {
value = value.replace(/,/g, ' ').split(/\s+/);
}
else if (attr === 'transformMatrix') {
if (parentAttributes && parentAttributes.transformMatrix) {
value = multiplyTransformMatrices(
parentAttributes.transformMatrix, fabric.parseTransformAttribute(value));
}
else {
value = fabric.parseTransformAttribute(value);
}
}
isArray = Object.prototype.toString.call(value) === '[object Array]';
// TODO: need to normalize em, %, pt, etc. to px (!)
var parsed = isArray ? value.map(parseFloat) : parseFloat(value);
return (!isArray && isNaN(parsed) ? value : parsed);
}
/**
* @private
* @param {Object} attributes Array of attributes to parse
*/
function _setStrokeFillOpacity(attributes) {
for (var attr in colorAttributes) {
if (!attributes[attr] || typeof attributes[colorAttributes[attr]] === 'undefined') continue;
if (attributes[attr].indexOf('url(') === 0) continue;
var color = new fabric.Color(attributes[attr]);
attributes[attr] = color.setAlpha(toFixed(color.getAlpha() * attributes[colorAttributes[attr]], 2)).toRgba();
delete attributes[colorAttributes[attr]];
}
return attributes;
}
/**
* Returns an object of attributes' name/value, given element and an array of attribute names;
* Parses parent "g" nodes recursively upwards.
* @static
* @memberOf fabric
* @param {DOMElement} element Element to parse
* @param {Array} attributes Array of attributes to parse
* @return {Object} object containing parsed attributes' names/values
*/
function parseAttributes(element, attributes) {
if (!element) {
return;
}
var value,
parentAttributes = { };
// if there's a parent container (`g` node), parse its attributes recursively upwards
if (element.parentNode && /^g$/i.test(element.parentNode.nodeName)) {
parentAttributes = fabric.parseAttributes(element.parentNode, attributes);
}
var ownAttributes = attributes.reduce(function(memo, attr) {
value = element.getAttribute(attr);
if (value) {
attr = normalizeAttr(attr);
value = normalizeValue(attr, value, parentAttributes);
memo[attr] = value;
}
return memo;
}, { });
// add values parsed from style, which take precedence over attributes
// (see: http://www.w3.org/TR/SVG/styling.html#UsingPresentationAttributes)
ownAttributes = extend(ownAttributes,
extend(getGlobalStylesForElement(element), fabric.parseStyleAttribute(element)));
return _setStrokeFillOpacity(extend(parentAttributes, ownAttributes));
}
/**
* Parses "transform" attribute, returning an array of values
* @static
* @function
* @memberOf fabric
* @param attributeValue {String} string containing attribute value
* @return {Array} array of 6 elements representing transformation matrix
*/
fabric.parseTransformAttribute = (function() {
function rotateMatrix(matrix, args) {
var angle = args[0];
matrix[0] = Math.cos(angle);
matrix[1] = Math.sin(angle);
matrix[2] = -Math.sin(angle);
matrix[3] = Math.cos(angle);
}
function scaleMatrix(matrix, args) {
var multiplierX = args[0],
multiplierY = (args.length === 2) ? args[1] : args[0];
matrix[0] = multiplierX;
matrix[3] = multiplierY;
}
function skewXMatrix(matrix, args) {
matrix[2] = args[0];
}
function skewYMatrix(matrix, args) {
matrix[1] = args[0];
}
function translateMatrix(matrix, args) {
matrix[4] = args[0];
if (args.length === 2) {
matrix[5] = args[1];
}
}
// identity matrix
var iMatrix = [
1, // a
0, // b
0, // c
1, // d
0, // e
0 // f
],
// == begin transform regexp
number = '(?:[-+]?\\d+(?:\\.\\d+)?(?:e[-+]?\\d+)?)',
comma_wsp = '(?:\\s+,?\\s*|,\\s*)',
skewX = '(?:(skewX)\\s*\\(\\s*(' + number + ')\\s*\\))',
skewY = '(?:(skewY)\\s*\\(\\s*(' + number + ')\\s*\\))',
rotate = '(?:(rotate)\\s*\\(\\s*(' + number + ')(?:' + comma_wsp + '(' + number + ')' + comma_wsp + '(' + number + '))?\\s*\\))',
scale = '(?:(scale)\\s*\\(\\s*(' + number + ')(?:' + comma_wsp + '(' + number + '))?\\s*\\))',
translate = '(?:(translate)\\s*\\(\\s*(' + number + ')(?:' + comma_wsp + '(' + number + '))?\\s*\\))',
matrix = '(?:(matrix)\\s*\\(\\s*' +
'(' + number + ')' + comma_wsp +
'(' + number + ')' + comma_wsp +
'(' + number + ')' + comma_wsp +
'(' + number + ')' + comma_wsp +
'(' + number + ')' + comma_wsp +
'(' + number + ')' +
'\\s*\\))',
transform = '(?:' +
matrix + '|' +
translate + '|' +
scale + '|' +
rotate + '|' +
skewX + '|' +
skewY +
')',
transforms = '(?:' + transform + '(?:' + comma_wsp + transform + ')*' + ')',
transform_list = '^\\s*(?:' + transforms + '?)\\s*$',
// http://www.w3.org/TR/SVG/coords.html#TransformAttribute
reTransformList = new RegExp(transform_list),
// == end transform regexp
reTransform = new RegExp(transform, 'g');
return function(attributeValue) {
// start with identity matrix
var matrix = iMatrix.concat();
var matrices = [ ];
// return if no argument was given or
// an argument does not match transform attribute regexp
if (!attributeValue || (attributeValue && !reTransformList.test(attributeValue))) {
return matrix;
}
attributeValue.replace(reTransform, function(match) {
var m = new RegExp(transform).exec(match).filter(function (match) {
return (match !== '' && match != null);
}),
operation = m[1],
args = m.slice(2).map(parseFloat);
switch(operation) {
case 'translate':
translateMatrix(matrix, args);
break;
case 'rotate':
rotateMatrix(matrix, args);
break;
case 'scale':
scaleMatrix(matrix, args);
break;
case 'skewX':
skewXMatrix(matrix, args);
break;
case 'skewY':
skewYMatrix(matrix, args);
break;
case 'matrix':
matrix = args;
break;
}
// snapshot current matrix into matrices array
matrices.push(matrix.concat());
// reset
matrix = iMatrix.concat();
});
var combinedMatrix = matrices[0];
while (matrices.length > 1) {
matrices.shift();
combinedMatrix = fabric.util.multiplyTransformMatrices(combinedMatrix, matrices[0]);
}
return combinedMatrix;
};
})();
/**
* Parses "points" attribute, returning an array of values
* @static
* @memberOf fabric
* @param points {String} points attribute string
* @return {Array} array of points
*/
function parsePointsAttribute(points) {
// points attribute is required and must not be empty
if (!points) return null;
points = points.trim();
var asPairs = points.indexOf(',') > -1;
points = points.split(/\s+/);
var parsedPoints = [ ], i, len;
// points could look like "10,20 30,40" or "10 20 30 40"
if (asPairs) {
i = 0;
len = points.length;
for (; i < len; i++) {
var pair = points[i].split(',');
parsedPoints.push({ x: parseFloat(pair[0]), y: parseFloat(pair[1]) });
}
}
else {
i = 0;
len = points.length;
for (; i < len; i+=2) {
parsedPoints.push({ x: parseFloat(points[i]), y: parseFloat(points[i+1]) });
}
}
// odd number of points is an error
if (parsedPoints.length % 2 !== 0) {
// return null;
}
return parsedPoints;
}
function parseFontDeclaration(value, oStyle) {
// TODO: support non-px font size
var match = value.match(/(normal|italic)?\s*(normal|small-caps)?\s*(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\s*(\d+)px(?:\/(normal|[\d\.]+))?\s+(.*)/);
if (!match) return;
var fontStyle = match[1];
// Font variant is not used
// var fontVariant = match[2];
var fontWeight = match[3];
var fontSize = match[4];
var lineHeight = match[5];
var fontFamily = match[6];
if (fontStyle) {
oStyle.fontStyle = fontStyle;
}
if (fontWeight) {
oStyle.fontSize = isNaN(parseFloat(fontWeight)) ? fontWeight : parseFloat(fontWeight);
}
if (fontSize) {
oStyle.fontSize = parseFloat(fontSize);
}
if (fontFamily) {
oStyle.fontFamily = fontFamily;
}
if (lineHeight) {
oStyle.lineHeight = lineHeight === 'normal' ? 1 : lineHeight;
}
}
/**
* Parses "style" attribute, retuning an object with values
* @static
* @memberOf fabric
* @param {SVGElement} element Element to parse
* @return {Object} Objects with values parsed from style attribute of an element
*/
function parseStyleAttribute(element) {
var oStyle = { },
style = element.getAttribute('style'),
attr, value;
if (!style) return oStyle;
if (typeof style === 'string') {
style.replace(/;$/, '').split(';').forEach(function (chunk) {
var pair = chunk.split(':');
attr = normalizeAttr(pair[0].trim().toLowerCase());
value = normalizeValue(attr, pair[1].trim());
if (attr === 'font') {
parseFontDeclaration(value, oStyle);
}
else {
oStyle[attr] = value;
}
});
}
else {
for (var prop in style) {
if (typeof style[prop] === 'undefined') continue;
attr = normalizeAttr(prop.toLowerCase());
value = normalizeValue(attr, style[prop]);
if (attr === 'font') {
parseFontDeclaration(value, oStyle);
}
else {
oStyle[attr] = value;
}
}
}
return oStyle;
}
function resolveGradients(instances) {
for (var i = instances.length; i--; ) {
var instanceFillValue = instances[i].get('fill');
if (/^url\(/.test(instanceFillValue)) {
var gradientId = instanceFillValue.slice(5, instanceFillValue.length - 1);
if (fabric.gradientDefs[gradientId]) {
instances[i].set('fill',
fabric.Gradient.fromElement(fabric.gradientDefs[gradientId], instances[i]));
}
}
}
}
/**
* Transforms an array of svg elements to corresponding fabric.* instances
* @static
* @memberOf fabric
* @param {Array} elements Array of elements to parse
* @param {Function} callback Being passed an array of fabric instances (transformed from SVG elements)
* @param {Object} [options] Options object
* @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
*/
function parseElements(elements, callback, options, reviver) {
var instances = new Array(elements.length), i = elements.length;
function checkIfDone() {
if (--i === 0) {
instances = instances.filter(function(el) {
return el != null;
});
resolveGradients(instances);
callback(instances);
}
}
for (var index = 0, el, len = elements.length; index < len; index++) {
el = elements[index];
var klass = fabric[capitalize(el.tagName)];
if (klass && klass.fromElement) {
try {
if (klass.async) {
klass.fromElement(el, (function(index, el) {
return function(obj) {
reviver && reviver(el, obj);
instances.splice(index, 0, obj);
checkIfDone();
};
})(index, el), options);
}
else {
var obj = klass.fromElement(el, options);
reviver && reviver(el, obj);
instances.splice(index, 0, obj);
checkIfDone();
}
}
catch(err) {
fabric.log(err);
}
}
else {
checkIfDone();
}
}
}
/**
* Returns CSS rules for a given SVG document
* @static
* @function
* @memberOf fabric
* @param {SVGDocument} doc SVG document to parse
* @return {Object} CSS rules of this document
*/
function getCSSRules(doc) {
var styles = doc.getElementsByTagName('style'),
allRules = { },
rules;
// very crude parsing of style contents
for (var i = 0, len = styles.length; i < len; i++) {
var styleContents = styles[0].textContent;
// remove comments
styleContents = styleContents.replace(/\/\*[\s\S]*?\*\//g, '');
rules = styleContents.match(/[^{]*\{[\s\S]*?\}/g);
rules = rules.map(function(rule) { return rule.trim(); });
rules.forEach(function(rule) {
var match = rule.match(/([\s\S]*?)\s*\{([^}]*)\}/);
rule = match[1];
var declaration = match[2].trim(),
propertyValuePairs = declaration.replace(/;$/, '').split(/\s*;\s*/);
if (!allRules[rule]) {
allRules[rule] = { };
}
for (var i = 0, len = propertyValuePairs.length; i < len; i++) {
var pair = propertyValuePairs[i].split(/\s*:\s*/),
property = pair[0],
value = pair[1];
allRules[rule][property] = value;
}
});
}
return allRules;
}
/**
* @private
*/
function getGlobalStylesForElement(element) {
var nodeName = element.nodeName,
className = element.getAttribute('class'),
id = element.getAttribute('id'),
styles = { };
for (var rule in fabric.cssRules) {
var ruleMatchesElement = (className && new RegExp('^\\.' + className).test(rule)) ||
(id && new RegExp('^#' + id).test(rule)) ||
(new RegExp('^' + nodeName).test(rule));
if (ruleMatchesElement) {
for (var property in fabric.cssRules[rule]) {
styles[property] = fabric.cssRules[rule][property];
}
}
}
return styles;
}
/**
* Parses an SVG document, converts it to an array of corresponding fabric.* instances and passes them to a callback
* @static
* @function
* @memberOf fabric
* @param {SVGDocument} doc SVG document to parse
* @param {Function} callback Callback to call when parsing is finished; It's being passed an array of elements (parsed from a document).
* @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
*/
fabric.parseSVGDocument = (function() {
var reAllowedSVGTagNames = /^(path|circle|polygon|polyline|ellipse|rect|line|image|text)$/;
// http://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute
// \d doesn't quite cut it (as we need to match an actual float number)
// matches, e.g.: +14.56e-12, etc.
var reNum = '(?:[-+]?\\d+(?:\\.\\d+)?(?:e[-+]?\\d+)?)';
var reViewBoxAttrValue = new RegExp(
'^' +
'\\s*(' + reNum + '+)\\s*,?' +
'\\s*(' + reNum + '+)\\s*,?' +
'\\s*(' + reNum + '+)\\s*,?' +
'\\s*(' + reNum + '+)\\s*' +
'$'
);
function hasAncestorWithNodeName(element, nodeName) {
while (element && (element = element.parentNode)) {
if (nodeName.test(element.nodeName)) {
return true;
}
}
return false;
}
return function(doc, callback, reviver) {
if (!doc) return;
var startTime = new Date(),
descendants = fabric.util.toArray(doc.getElementsByTagName('*'));
if (descendants.length === 0) {
// we're likely in node, where "o3-xml" library fails to gEBTN("*")
// https://github.com/ajaxorg/node-o3-xml/issues/21
descendants = doc.selectNodes("//*[name(.)!='svg']");
var arr = [ ];
for (var i = 0, len = descendants.length; i < len; i++) {
arr[i] = descendants[i];
}
descendants = arr;
}
var elements = descendants.filter(function(el) {
return reAllowedSVGTagNames.test(el.tagName) &&
!hasAncestorWithNodeName(el, /^(?:pattern|defs)$/); // http://www.w3.org/TR/SVG/struct.html#DefsElement
});
if (!elements || (elements && !elements.length)) return;
var viewBoxAttr = doc.getAttribute('viewBox'),
widthAttr = doc.getAttribute('width'),
heightAttr = doc.getAttribute('height'),
width = null,
height = null,
minX,
minY;
if (viewBoxAttr && (viewBoxAttr = viewBoxAttr.match(reViewBoxAttrValue))) {
minX = parseInt(viewBoxAttr[1], 10);
minY = parseInt(viewBoxAttr[2], 10);
width = parseInt(viewBoxAttr[3], 10);
height = parseInt(viewBoxAttr[4], 10);
}
// values of width/height attributes overwrite those extracted from viewbox attribute
width = widthAttr ? parseFloat(widthAttr) : width;
height = heightAttr ? parseFloat(heightAttr) : height;
var options = {
width: width,
height: height
};
fabric.gradientDefs = fabric.getGradientDefs(doc);
fabric.cssRules = getCSSRules(doc);
// Precedence of rules: style > class > attribute
fabric.parseElements(elements, function(instances) {
fabric.documentParsingTime = new Date() - startTime;
if (callback) {
callback(instances, options);
}
}, clone(options), reviver);
};
})();
/**
* Used for caching SVG documents (loaded via `fabric.Canvas#loadSVGFromURL`)
* @namespace
*/
var svgCache = {
/**
* @param {String} name
* @param {Function} callback
*/
has: function (name, callback) {
callback(false);
},
/**
* @param {String} url
* @param {Function} callback
*/
get: function () {
/* NOOP */
},
/**
* @param {String} url
* @param {Object} object
*/
set: function () {
/* NOOP */
}
};
/**
* Takes url corresponding to an SVG document, and parses it into a set of fabric objects. Note that SVG is fetched via XMLHttpRequest, so it needs to conform to SOP (Same Origin Policy)
* @memberof fabric
* @param {String} url
* @param {Function} callback
* @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
*/
function loadSVGFromURL(url, callback, reviver) {
url = url.replace(/^\n\s*/, '').trim();
svgCache.has(url, function (hasUrl) {
if (hasUrl) {
svgCache.get(url, function (value) {
var enlivedRecord = _enlivenCachedObject(value);
callback(enlivedRecord.objects, enlivedRecord.options);
});
}
else {
new fabric.util.request(url, {
method: 'get',
onComplete: onComplete
});
}
});
function onComplete(r) {
var xml = r.responseXML;
if (!xml.documentElement && fabric.window.ActiveXObject && r.responseText) {
xml = new ActiveXObject('Microsoft.XMLDOM');
xml.async = 'false';
//IE chokes on DOCTYPE
xml.loadXML(r.responseText.replace(//i,''));
}
if (!xml.documentElement) return;
fabric.parseSVGDocument(xml.documentElement, function (results, options) {
svgCache.set(url, {
objects: fabric.util.array.invoke(results, 'toObject'),
options: options
});
callback(results, options);
}, reviver);
}
}
/**
* @private
*/
function _enlivenCachedObject(cachedObject) {
var objects = cachedObject.objects,
options = cachedObject.options;
objects = objects.map(function (o) {
return fabric[capitalize(o.type)].fromObject(o);
});
return ({ objects: objects, options: options });
}
/**
* Takes string corresponding to an SVG document, and parses it into a set of fabric objects
* @memberof fabric
* @param {String} string
* @param {Function} callback
* @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
*/
function loadSVGFromString(string, callback, reviver) {
string = string.trim();
var doc;
if (typeof DOMParser !== 'undefined') {
var parser = new DOMParser();
if (parser && parser.parseFromString) {
doc = parser.parseFromString(string, 'text/xml');
}
}
else if (fabric.window.ActiveXObject) {
doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = 'false';
//IE chokes on DOCTYPE
doc.loadXML(string.replace(//i,''));
}
fabric.parseSVGDocument(doc.documentElement, function (results, options) {
callback(results, options);
}, reviver);
}
/**
* Creates markup containing SVG font faces
* @param {Array} objects Array of fabric objects
* @return {String}
*/
function createSVGFontFacesMarkup(objects) {
var markup = '';
for (var i = 0, len = objects.length; i < len; i++) {
if (objects[i].type !== 'text' || !objects[i].path) continue;
markup += [
'@font-face {',
'font-family: ', objects[i].fontFamily, '; ',
'src: url(\'', objects[i].path, '\')',
'}'
].join('');
}
if (markup) {
markup = [
''
].join('');
}
return markup;
}
/**
* Creates markup containing SVG referenced elements like patterns, gradients etc.
* @param {fabric.Canvas} canvas instance of fabric.Canvas
* @return {String}
*/
function createSVGRefElementsMarkup(canvas) {
var markup = '';
if (canvas.backgroundColor && canvas.backgroundColor.source) {
markup = [
'',
''
].join('');
}
return markup;
}
/**
* Parses an SVG document, returning all of the gradient declarations found in it
* @static
* @function
* @memberOf fabric
* @param {SVGDocument} doc SVG document to parse
* @return {Object} Gradient definitions; key corresponds to element id, value -- to gradient definition element
*/
function getGradientDefs(doc) {
var linearGradientEls = doc.getElementsByTagName('linearGradient'),
radialGradientEls = doc.getElementsByTagName('radialGradient'),
el, i,
gradientDefs = { };
i = linearGradientEls.length;
for (; i--; ) {
el = linearGradientEls[i];
gradientDefs[el.getAttribute('id')] = el;
}
i = radialGradientEls.length;
for (; i--; ) {
el = radialGradientEls[i];
gradientDefs[el.getAttribute('id')] = el;
}
return gradientDefs;
}
extend(fabric, {
parseAttributes: parseAttributes,
parseElements: parseElements,
parseStyleAttribute: parseStyleAttribute,
parsePointsAttribute: parsePointsAttribute,
getCSSRules: getCSSRules,
loadSVGFromURL: loadSVGFromURL,
loadSVGFromString: loadSVGFromString,
createSVGFontFacesMarkup: createSVGFontFacesMarkup,
createSVGRefElementsMarkup: createSVGRefElementsMarkup,
getGradientDefs: getGradientDefs
});
})(typeof exports !== 'undefined' ? exports : this);
(function(global) {
"use strict";
/* Adaptation of work of Kevin Lindsey (kevin@kevlindev.com) */
var fabric = global.fabric || (global.fabric = { });
if (fabric.Point) {
fabric.warn('fabric.Point is already defined');
return;
}
fabric.Point = Point;
/**
* Point class
* @class fabric.Point
* @memberOf fabric
* @constructor
* @param {Number} x
* @param {Number} y
* @return {fabric.Point} thisArg
*/
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype = /** @lends fabric.Point.prototype */ {
constructor: Point,
/**
* Adds another point to this one and returns another one
* @param {fabric.Point} that
* @return {fabric.Point} new Point instance with added values
*/
add: function (that) {
return new Point(this.x + that.x, this.y + that.y);
},
/**
* Adds another point to this one
* @param {fabric.Point} that
* @return {fabric.Point} thisArg
*/
addEquals: function (that) {
this.x += that.x;
this.y += that.y;
return this;
},
/**
* Adds value to this point and returns a new one
* @param {Number} scalar
* @return {fabric.Point} new Point with added value
*/
scalarAdd: function (scalar) {
return new Point(this.x + scalar, this.y + scalar);
},
/**
* Adds value to this point
* @param {Number} scalar
* @param {fabric.Point} thisArg
*/
scalarAddEquals: function (scalar) {
this.x += scalar;
this.y += scalar;
return this;
},
/**
* Subtracts another point from this point and returns a new one
* @param {fabric.Point} that
* @return {fabric.Point} new Point object with subtracted values
*/
subtract: function (that) {
return new Point(this.x - that.x, this.y - that.y);
},
/**
* Subtracts another point from this point
* @param {fabric.Point} that
* @return {fabric.Point} thisArg
*/
subtractEquals: function (that) {
this.x -= that.x;
this.y -= that.y;
return this;
},
/**
* Subtracts value from this point and returns a new one
* @param {Number} scalar
* @return {fabric.Point}
*/
scalarSubtract: function (scalar) {
return new Point(this.x - scalar, this.y - scalar);
},
/**
* Subtracts value from this point
* @param {Number} scalar
* @return {fabric.Point} thisArg
*/
scalarSubtractEquals: function (scalar) {
this.x -= scalar;
this.y -= scalar;
return this;
},
/**
* Miltiplies this point by a value and returns a new one
* @param {Number} scalar
* @return {fabric.Point}
*/
multiply: function (scalar) {
return new Point(this.x * scalar, this.y * scalar);
},
/**
* Miltiplies this point by a value
* @param {Number} scalar
* @return {fabric.Point} thisArg
*/
multiplyEquals: function (scalar) {
this.x *= scalar;
this.y *= scalar;
return this;
},
/**
* Divides this point by a value and returns a new one
* @param {Number} scalar
* @return {fabric.Point}
*/
divide: function (scalar) {
return new Point(this.x / scalar, this.y / scalar);
},
/**
* Divides this point by a value
* @param {Number} scalar
* @return {fabric.Point} thisArg
*/
divideEquals: function (scalar) {
this.x /= scalar;
this.y /= scalar;
return this;
},
/**
* Returns true if this point is equal to another one
* @param {fabric.Point} that
* @return {Boolean}
*/
eq: function (that) {
return (this.x === that.x && this.y === that.y);
},
/**
* Returns true if this point is less than another one
* @param {fabric.Point} that
* @return {Boolean}
*/
lt: function (that) {
return (this.x < that.x && this.y < that.y);
},
/**
* Returns true if this point is less than or equal to another one
* @param {fabric.Point} that
* @return {Boolean}
*/
lte: function (that) {
return (this.x <= that.x && this.y <= that.y);
},
/**
* Returns true if this point is greater another one
* @param {fabric.Point} that
* @return {Boolean}
*/
gt: function (that) {
return (this.x > that.x && this.y > that.y);
},
/**
* Returns true if this point is greater than or equal to another one
* @param {fabric.Point} that
* @return {Boolean}
*/
gte: function (that) {
return (this.x >= that.x && this.y >= that.y);
},
/**
* Returns new point which is the result of linear interpolation with this one and another one
* @param {fabric.Point} that
* @param {Number} t
* @return {fabric.Point}
*/
lerp: function (that, t) {
return new Point(this.x + (that.x - this.x) * t, this.y + (that.y - this.y) * t);
},
/**
* Returns distance from this point and another one
* @param {fabric.Point} that
* @return {Number}
*/
distanceFrom: function (that) {
var dx = this.x - that.x,
dy = this.y - that.y;
return Math.sqrt(dx * dx + dy * dy);
},
/**
* Returns the point between this point and another one
* @param {fabric.Point} that
* @return {fabric.Point}
*/
midPointFrom: function (that) {
return new Point(this.x + (that.x - this.x)/2, this.y + (that.y - this.y)/2);
},
/**
* Returns a new point which is the min of this and another one
* @param {fabric.Point} that
* @return {fabric.Point}
*/
min: function (that) {
return new Point(Math.min(this.x, that.x), Math.min(this.y, that.y));
},
/**
* Returns a new point which is the max of this and another one
* @param {fabric.Point} that
* @return {fabric.Point}
*/
max: function (that) {
return new Point(Math.max(this.x, that.x), Math.max(this.y, that.y));
},
/**
* Returns string representation of this point
* @return {String}
*/
toString: function () {
return this.x + "," + this.y;
},
/**
* Sets x/y of this point
* @param {Number} x
* @return {Number} y
*/
setXY: function (x, y) {
this.x = x;
this.y = y;
},
/**
* Sets x/y of this point from another point
* @param {fabric.Point} that
*/
setFromPoint: function (that) {
this.x = that.x;
this.y = that.y;
},
/**
* Swaps x/y of this point and another point
* @param {fabric.Point} that
*/
swap: function (that) {
var x = this.x,
y = this.y;
this.x = that.x;
this.y = that.y;
that.x = x;
that.y = y;
}
};
})(typeof exports !== 'undefined' ? exports : this);
(function(global) {
"use strict";
/* Adaptation of work of Kevin Lindsey (kevin@kevlindev.com) */
var fabric = global.fabric || (global.fabric = { });
if (fabric.Intersection) {
fabric.warn('fabric.Intersection is already defined');
return;
}
/**
* Intersection class
* @class fabric.Intersection
* @memberOf fabric
* @constructor
*/
function Intersection(status) {
this.status = status;
this.points = [];
}
fabric.Intersection = Intersection;
fabric.Intersection.prototype = /** @lends fabric.Intersection.prototype */ {
/**
* Appends a point to intersection
* @param {fabric.Point} point
*/
appendPoint: function (point) {
this.points.push(point);
},
/**
* Appends points to intersection
* @param {Array} points
*/
appendPoints: function (points) {
this.points = this.points.concat(points);
}
};
/**
* Checks if one line intersects another
* @static
* @param {fabric.Point} a1
* @param {fabric.Point} a2
* @param {fabric.Point} b1
* @param {fabric.Point} b2
* @return {fabric.Intersection}
*/
fabric.Intersection.intersectLineLine = function (a1, a2, b1, b2) {
var result,
ua_t = (b2.x - b1.x) * (a1.y - b1.y) - (b2.y - b1.y) * (a1.x - b1.x),
ub_t = (a2.x - a1.x) * (a1.y - b1.y) - (a2.y - a1.y) * (a1.x - b1.x),
u_b = (b2.y - b1.y) * (a2.x - a1.x) - (b2.x - b1.x) * (a2.y - a1.y);
if (u_b !== 0) {
var ua = ua_t / u_b,
ub = ub_t / u_b;
if (0 <= ua && ua <= 1 && 0 <= ub && ub <= 1) {
result = new Intersection("Intersection");
result.points.push(new fabric.Point(a1.x + ua * (a2.x - a1.x), a1.y + ua * (a2.y - a1.y)));
}
else {
result = new Intersection();
}
}
else {
if (ua_t === 0 || ub_t === 0) {
result = new Intersection("Coincident");
}
else {
result = new Intersection("Parallel");
}
}
return result;
};
/**
* Checks if line intersects polygon
* @static
* @param {fabric.Point} a1
* @param {fabric.Point} a2
* @param {Array} points
* @return {fabric.Intersection}
*/
fabric.Intersection.intersectLinePolygon = function(a1,a2,points){
var result = new Intersection(),
length = points.length;
for (var i = 0; i < length; i++) {
var b1 = points[i],
b2 = points[(i+1) % length],
inter = Intersection.intersectLineLine(a1, a2, b1, b2);
result.appendPoints(inter.points);
}
if (result.points.length > 0) {
result.status = "Intersection";
}
return result;
};
/**
* Checks if polygon intersects another polygon
* @static
* @param {Array} points1
* @param {Array} points2
* @return {fabric.Intersection}
*/
fabric.Intersection.intersectPolygonPolygon = function (points1, points2) {
var result = new Intersection(),
length = points1.length;
for (var i = 0; i < length; i++) {
var a1 = points1[i],
a2 = points1[(i+1) % length],
inter = Intersection.intersectLinePolygon(a1, a2, points2);
result.appendPoints(inter.points);
}
if (result.points.length > 0) {
result.status = "Intersection";
}
return result;
};
/**
* Checks if polygon intersects rectangle
* @static
* @param {Array} points
* @param {Number} r1
* @param {Number} r2
* @return {fabric.Intersection}
*/
fabric.Intersection.intersectPolygonRectangle = function (points, r1, r2) {
var min = r1.min(r2),
max = r1.max(r2),
topRight = new fabric.Point(max.x, min.y),
bottomLeft = new fabric.Point(min.x, max.y),
inter1 = Intersection.intersectLinePolygon(min, topRight, points),
inter2 = Intersection.intersectLinePolygon(topRight, max, points),
inter3 = Intersection.intersectLinePolygon(max, bottomLeft, points),
inter4 = Intersection.intersectLinePolygon(bottomLeft, min, points),
result = new Intersection();
result.appendPoints(inter1.points);
result.appendPoints(inter2.points);
result.appendPoints(inter3.points);
result.appendPoints(inter4.points);
if (result.points.length > 0) {
result.status = "Intersection";
}
return result;
};
})(typeof exports !== 'undefined' ? exports : this);
(function(global) {
"use strict";
var fabric = global.fabric || (global.fabric = { });
if (fabric.Color) {
fabric.warn('fabric.Color is already defined.');
return;
}
/**
* Color class
* The purpose of {@link fabric.Color} is to abstract and encapsulate common color operations;
* {@link fabric.Color} is a constructor and creates instances of {@link fabric.Color} objects.
*
* @class fabric.Color
* @param {String} color optional in hex or rgb(a) format
* @return {fabric.Color} thisArg
* @tutorial {@link http://fabricjs.com/fabric-intro-part-2/#colors}
*/
function Color(color) {
if (!color) {
this.setSource([0, 0, 0, 1]);
}
else {
this._tryParsingColor(color);
}
}
fabric.Color = Color;
fabric.Color.prototype = /** @lends fabric.Color.prototype */ {
/**
* @private
* @param {String|Array} color Color value to parse
*/
_tryParsingColor: function(color) {
var source;
if (color in Color.colorNameMap) {
color = Color.colorNameMap[color];
}
source = Color.sourceFromHex(color);
if (!source) {
source = Color.sourceFromRgb(color);
}
if (!source) {
source = Color.sourceFromHsl(color);
}
if (source) {
this.setSource(source);
}
},
/**
* Adapted from https://github.com/mjijackson
* @private
* @param {Number} r Red color value
* @param {Number} g Green color value
* @param {Number} b Blue color value
* @return {Array} Hsl color
*/
_rgbToHsl: function(r, g, b) {
r /= 255, g /= 255, b /= 255;
var h, s, l,
max = fabric.util.array.max([r, g, b]),
min = fabric.util.array.min([r, g, b]);
l = (max + min) / 2;
if (max === min) {
h = s = 0; // achromatic
}
else {
var d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
break;
}
h /= 6;
}
return [
Math.round(h * 360),
Math.round(s * 100),
Math.round(l * 100)
];
},
/**
* Returns source of this color (where source is an array representation; ex: [200, 200, 100, 1])
* @return {Array}
*/
getSource: function() {
return this._source;
},
/**
* Sets source of this color (where source is an array representation; ex: [200, 200, 100, 1])
* @param {Array} source
*/
setSource: function(source) {
this._source = source;
},
/**
* Returns color represenation in RGB format
* @return {String} ex: rgb(0-255,0-255,0-255)
*/
toRgb: function() {
var source = this.getSource();
return 'rgb(' + source[0] + ',' + source[1] + ',' + source[2] + ')';
},
/**
* Returns color represenation in RGBA format
* @return {String} ex: rgba(0-255,0-255,0-255,0-1)
*/
toRgba: function() {
var source = this.getSource();
return 'rgba(' + source[0] + ',' + source[1] + ',' + source[2] + ',' + source[3] + ')';
},
/**
* Returns color represenation in HSL format
* @return {String} ex: hsl(0-360,0%-100%,0%-100%)
*/
toHsl: function() {
var source = this.getSource(),
hsl = this._rgbToHsl(source[0], source[1], source[2]);
return 'hsl(' + hsl[0] + ',' + hsl[1] + '%,' + hsl[2] + '%)';
},
/**
* Returns color represenation in HSLA format
* @return {String} ex: hsla(0-360,0%-100%,0%-100%,0-1)
*/
toHsla: function() {
var source = this.getSource(),
hsl = this._rgbToHsl(source[0], source[1], source[2]);
return 'hsla(' + hsl[0] + ',' + hsl[1] + '%,' + hsl[2] + '%,' + source[3] + ')';
},
/**
* Returns color represenation in HEX format
* @return {String} ex: FF5555
*/
toHex: function() {
var source = this.getSource();
var r = source[0].toString(16);
r = (r.length === 1) ? ('0' + r) : r;
var g = source[1].toString(16);
g = (g.length === 1) ? ('0' + g) : g;
var b = source[2].toString(16);
b = (b.length === 1) ? ('0' + b) : b;
return r.toUpperCase() + g.toUpperCase() + b.toUpperCase();
},
/**
* Gets value of alpha channel for this color
* @return {Number} 0-1
*/
getAlpha: function() {
return this.getSource()[3];
},
/**
* Sets value of alpha channel for this color
* @param {Number} alpha Alpha value 0-1
* @return {fabric.Color} thisArg
*/
setAlpha: function(alpha) {
var source = this.getSource();
source[3] = alpha;
this.setSource(source);
return this;
},
/**
* Transforms color to its grayscale representation
* @return {fabric.Color} thisArg
*/
toGrayscale: function() {
var source = this.getSource(),
average = parseInt((source[0] * 0.3 + source[1] * 0.59 + source[2] * 0.11).toFixed(0), 10),
currentAlpha = source[3];
this.setSource([average, average, average, currentAlpha]);
return this;
},
/**
* Transforms color to its black and white representation
* @param {Number} threshold
* @return {fabric.Color} thisArg
*/
toBlackWhite: function(threshold) {
var source = this.getSource(),
average = (source[0] * 0.3 + source[1] * 0.59 + source[2] * 0.11).toFixed(0),
currentAlpha = source[3];
threshold = threshold || 127;
average = (Number(average) < Number(threshold)) ? 0 : 255;
this.setSource([average, average, average, currentAlpha]);
return this;
},
/**
* Overlays color with another color
* @param {String|fabric.Color} otherColor
* @return {fabric.Color} thisArg
*/
overlayWith: function(otherColor) {
if (!(otherColor instanceof Color)) {
otherColor = new Color(otherColor);
}
var result = [],
alpha = this.getAlpha(),
otherAlpha = 0.5,
source = this.getSource(),
otherSource = otherColor.getSource();
for (var i = 0; i < 3; i++) {
result.push(Math.round((source[i] * (1 - otherAlpha)) + (otherSource[i] * otherAlpha)));
}
result[3] = alpha;
this.setSource(result);
return this;
}
};
/**
* Regex matching color in RGB or RGBA formats (ex: rgb(0, 0, 0), rgba(255, 100, 10, 0.5), rgba( 255 , 100 , 10 , 0.5 ), rgb(1,1,1), rgba(100%, 60%, 10%, 0.5))
* @static
* @field
* @memberOf fabric.Color
*/
fabric.Color.reRGBa = /^rgba?\(\s*(\d{1,3}\%?)\s*,\s*(\d{1,3}\%?)\s*,\s*(\d{1,3}\%?)\s*(?:\s*,\s*(\d+(?:\.\d+)?)\s*)?\)$/;
/**
* Regex matching color in HSL or HSLA formats (ex: hsl(200, 80%, 10%), hsla(300, 50%, 80%, 0.5), hsla( 300 , 50% , 80% , 0.5 ))
* @static
* @field
* @memberOf fabric.Color
*/
fabric.Color.reHSLa = /^hsla?\(\s*(\d{1,3})\s*,\s*(\d{1,3}\%)\s*,\s*(\d{1,3}\%)\s*(?:\s*,\s*(\d+(?:\.\d+)?)\s*)?\)$/;
/**
* Regex matching color in HEX format (ex: #FF5555, 010155, aff)
* @static
* @field
* @memberOf fabric.Color
*/
fabric.Color.reHex = /^#?([0-9a-f]{6}|[0-9a-f]{3})$/i;
/**
* Map of the 17 basic color names with HEX code
* @static
* @field
* @memberOf fabric.Color
* @see: http://www.w3.org/TR/CSS2/syndata.html#color-units
*/
fabric.Color.colorNameMap = {
'aqua': '#00FFFF',
'black': '#000000',
'blue': '#0000FF',
'fuchsia': '#FF00FF',
'gray': '#808080',
'green': '#008000',
'lime': '#00FF00',
'maroon': '#800000',
'navy': '#000080',
'olive': '#808000',
'orange': '#FFA500',
'purple': '#800080',
'red': '#FF0000',
'silver': '#C0C0C0',
'teal': '#008080',
'white': '#FFFFFF',
'yellow': '#FFFF00'
};
/**
* @private
* @param {Number} p
* @param {Number} q
* @param {Number} t
* @return {Number}
*/
function hue2rgb(p, q, t){
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1/6) return p + (q - p) * 6 * t;
if (t < 1/2) return q;
if (t < 2/3) return p + (q - p) * (2/3 - t) * 6;
return p;
}
/**
* Returns new color object, when given a color in RGB format
* @memberOf fabric.Color
* @param {String} color Color value ex: rgb(0-255,0-255,0-255)
* @return {fabric.Color}
*/
fabric.Color.fromRgb = function(color) {
return Color.fromSource(Color.sourceFromRgb(color));
};
/**
* Returns array represenatation (ex: [100, 100, 200, 1]) of a color that's in RGB or RGBA format
* @memberOf fabric.Color
* @param {String} color Color value ex: rgb(0-255,0-255,0-255), rgb(0%-100%,0%-100%,0%-100%)
* @return {Array} source
*/
fabric.Color.sourceFromRgb = function(color) {
var match = color.match(Color.reRGBa);
if (match) {
var r = parseInt(match[1], 10) / (/%$/.test(match[1]) ? 100 : 1) * (/%$/.test(match[1]) ? 255 : 1),
g = parseInt(match[2], 10) / (/%$/.test(match[2]) ? 100 : 1) * (/%$/.test(match[2]) ? 255 : 1),
b = parseInt(match[3], 10) / (/%$/.test(match[3]) ? 100 : 1) * (/%$/.test(match[3]) ? 255 : 1);
return [
parseInt(r, 10),
parseInt(g, 10),
parseInt(b, 10),
match[4] ? parseFloat(match[4]) : 1
];
}
};
/**
* Returns new color object, when given a color in RGBA format
* @static
* @function
* @memberOf fabric.Color
* @param {String} color
* @return {fabric.Color}
*/
fabric.Color.fromRgba = Color.fromRgb;
/**
* Returns new color object, when given a color in HSL format
* @param {String} color Color value ex: hsl(0-260,0%-100%,0%-100%)
* @memberOf fabric.Color
* @return {fabric.Color}
*/
fabric.Color.fromHsl = function(color) {
return Color.fromSource(Color.sourceFromHsl(color));
};
/**
* Returns array represenatation (ex: [100, 100, 200, 1]) of a color that's in HSL or HSLA format.
* Adapted from https://github.com/mjijackson
* @memberOf fabric.Color
* @param {String} color Color value ex: hsl(0-360,0%-100%,0%-100%) or hsla(0-360,0%-100%,0%-100%, 0-1)
* @return {Array} source
* @see http://http://www.w3.org/TR/css3-color/#hsl-color
*/
fabric.Color.sourceFromHsl = function(color) {
var match = color.match(Color.reHSLa);
if (!match) return;
var h = (((parseFloat(match[1]) % 360) + 360) % 360) / 360,
s = parseFloat(match[2]) / (/%$/.test(match[2]) ? 100 : 1),
l = parseFloat(match[3]) / (/%$/.test(match[3]) ? 100 : 1),
r, g, b;
if (s === 0) {
r = g = b = l;
}
else {
var q = l <= 0.5 ? l * (s + 1) : l + s - l * s;
var p = l * 2 - q;
r = hue2rgb(p, q, h + 1/3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1/3);
}
return [
Math.round(r * 255),
Math.round(g * 255),
Math.round(b * 255),
match[4] ? parseFloat(match[4]) : 1
];
};
/**
* Returns new color object, when given a color in HSLA format
* @static
* @function
* @memberOf fabric.Color
* @param {String} color
* @return {fabric.Color}
*/
fabric.Color.fromHsla = Color.fromHsl;
/**
* Returns new color object, when given a color in HEX format
* @static
* @memberOf fabric.Color
* @param {String} color Color value ex: FF5555
* @return {fabric.Color}
*/
fabric.Color.fromHex = function(color) {
return Color.fromSource(Color.sourceFromHex(color));
};
/**
* Returns array represenatation (ex: [100, 100, 200, 1]) of a color that's in HEX format
* @static
* @memberOf fabric.Color
* @param {String} color ex: FF5555
* @return {Array} source
*/
fabric.Color.sourceFromHex = function(color) {
if (color.match(Color.reHex)) {
var value = color.slice(color.indexOf('#') + 1),
isShortNotation = (value.length === 3),
r = isShortNotation ? (value.charAt(0) + value.charAt(0)) : value.substring(0, 2),
g = isShortNotation ? (value.charAt(1) + value.charAt(1)) : value.substring(2, 4),
b = isShortNotation ? (value.charAt(2) + value.charAt(2)) : value.substring(4, 6);
return [
parseInt(r, 16),
parseInt(g, 16),
parseInt(b, 16),
1
];
}
};
/**
* Returns new color object, when given color in array representation (ex: [200, 100, 100, 0.5])
* @static
* @memberOf fabric.Color
* @param {Array} source
* @return {fabric.Color}
*/
fabric.Color.fromSource = function(source) {
var oColor = new Color();
oColor.setSource(source);
return oColor;
};
})(typeof exports !== 'undefined' ? exports : this);
(function() {
/* _FROM_SVG_START_ */
function getColorStop(el) {
var style = el.getAttribute('style'),
offset = el.getAttribute('offset'),
color, opacity;
// convert percents to absolute values
offset = parseFloat(offset) / (/%$/.test(offset) ? 100 : 1);
if (style) {
var keyValuePairs = style.split(/\s*;\s*/);
if (keyValuePairs[keyValuePairs.length-1] === '') {
keyValuePairs.pop();
}
for (var i = keyValuePairs.length; i--; ) {
var split = keyValuePairs[i].split(/\s*:\s*/),
key = split[0].trim(),
value = split[1].trim();
if (key === 'stop-color') {
color = value;
}
else if (key === 'stop-opacity') {
opacity = value;
}
}
}
if (!color) {
color = el.getAttribute('stop-color') || 'rgb(0,0,0)';
}
if (!opacity) {
opacity = el.getAttribute('stop-opacity');
}
// convert rgba color to rgb color - alpha value has no affect in svg
color = new fabric.Color(color).toRgb();
return {
offset: offset,
color: color,
opacity: isNaN(parseFloat(opacity)) ? 1 : parseFloat(opacity)
};
}
/* _FROM_SVG_END_ */
/**
* Gradient class
* @class fabric.Gradient
* @tutorial {@link http://fabricjs.com/fabric-intro-part-2/#gradients}
*/
fabric.Gradient = fabric.util.createClass(/** @lends fabric.Gradient.prototype */ {
/**
* Constructor
* @param {Object} [options] Options object with type, coords, gradientUnits and colorStops
* @return {fabric.Gradient} thisArg
*/
initialize: function(options) {
options || (options = { });
var coords = { };
this.id = fabric.Object.__uid++;
this.type = options.type || 'linear';
coords = {
x1: options.coords.x1 || 0,
y1: options.coords.y1 || 0,
x2: options.coords.x2 || 0,
y2: options.coords.y2 || 0
};
if (this.type === 'radial') {
coords.r1 = options.coords.r1 || 0;
coords.r2 = options.coords.r2 || 0;
}
this.coords = coords;
this.gradientUnits = options.gradientUnits || 'objectBoundingBox';
this.colorStops = options.colorStops.slice();
},
/**
* Adds another colorStop
* @param {Object} colorStop Object with offset and color
* @return {fabric.Gradient} thisArg
*/
addColorStop: function(colorStop) {
for (var position in colorStop) {
var color = new fabric.Color(colorStop[position]);
this.colorStops.push({offset: position, color: color.toRgb(), opacity: color.getAlpha()});
}
return this;
},
/**
* Returns object representation of a gradient
* @return {Object}
*/
toObject: function() {
return {
type: this.type,
coords: this.coords,
gradientUnits: this.gradientUnits,
colorStops: this.colorStops
};
},
/* _TO_SVG_START_ */
/**
* Returns SVG representation of an gradient
* @param {Object} object Object to create a gradient for
* @param {Boolean} normalize Whether coords should be normalized
* @return {String} SVG representation of an gradient (linear/radial)
*/
toSVG: function(object, normalize) {
var coords = fabric.util.object.clone(this.coords),
markup;
// colorStops must be sorted ascending
this.colorStops.sort(function(a, b) {
return a.offset - b.offset;
});
if (normalize && this.gradientUnits === 'userSpaceOnUse') {
coords.x1 += object.width / 2;
coords.y1 += object.height / 2;
coords.x2 += object.width / 2;
coords.y2 += object.height / 2;
}
else if (this.gradientUnits === 'objectBoundingBox') {
_convertValuesToPercentUnits(object, coords);
}
if (this.type === 'linear') {
markup = [
''
];
}
else if (this.type === 'radial') {
markup = [
''
];
}
for (var i = 0; i < this.colorStops.length; i++) {
markup.push(
''
);
}
markup.push((this.type === 'linear' ? '' : ''));
return markup.join('');
},
/* _TO_SVG_END_ */
/**
* Returns an instance of CanvasGradient
* @param {CanvasRenderingContext2D} ctx Context to render on
* @return {CanvasGradient}
*/
toLive: function(ctx) {
var gradient;
if (!this.type) return;
if (this.type === 'linear') {
gradient = ctx.createLinearGradient(
this.coords.x1, this.coords.y1, this.coords.x2, this.coords.y2);
}
else if (this.type === 'radial') {
gradient = ctx.createRadialGradient(
this.coords.x1, this.coords.y1, this.coords.r1, this.coords.x2, this.coords.y2, this.coords.r2);
}
for (var i = 0, len = this.colorStops.length; i < len; i++) {
var color = this.colorStops[i].color,
opacity = this.colorStops[i].opacity,
offset = this.colorStops[i].offset;
if (typeof opacity !== 'undefined') {
color = new fabric.Color(color).setAlpha(opacity).toRgba();
}
gradient.addColorStop(parseFloat(offset), color);
}
return gradient;
}
});
fabric.util.object.extend(fabric.Gradient, {
/* _FROM_SVG_START_ */
/**
* Returns {@link fabric.Gradient} instance from an SVG element
* @static
* @memberof fabric.Gradient
* @param {SVGGradientElement} el SVG gradient element
* @param {fabric.Object} instance
* @return {fabric.Gradient} Gradient instance
* @see http://www.w3.org/TR/SVG/pservers.html#LinearGradientElement
* @see http://www.w3.org/TR/SVG/pservers.html#RadialGradientElement
*/
fromElement: function(el, instance) {
/**
* @example:
*
*
*
*
*
*
* OR
*
*
*
*
*
*
* OR
*
*
*
*
*
*
*
* OR
*
*
*
*
*
*
*
*/
var colorStopEls = el.getElementsByTagName('stop'),
type = (el.nodeName === 'linearGradient' ? 'linear' : 'radial'),
gradientUnits = el.getAttribute('gradientUnits') || 'objectBoundingBox',
colorStops = [],
coords = { };
if (type === 'linear') {
coords = {
x1: el.getAttribute('x1') || 0,
y1: el.getAttribute('y1') || 0,
x2: el.getAttribute('x2') || '100%',
y2: el.getAttribute('y2') || 0
};
}
else if (type === 'radial') {
coords = {
x1: el.getAttribute('fx') || el.getAttribute('cx') || '50%',
y1: el.getAttribute('fy') || el.getAttribute('cy') || '50%',
r1: 0,
x2: el.getAttribute('cx') || '50%',
y2: el.getAttribute('cy') || '50%',
r2: el.getAttribute('r') || '50%'
};
}
for (var i = colorStopEls.length; i--; ) {
colorStops.push(getColorStop(colorStopEls[i]));
}
_convertPercentUnitsToValues(instance, coords);
return new fabric.Gradient({
type: type,
coords: coords,
gradientUnits: gradientUnits,
colorStops: colorStops
});
},
/* _FROM_SVG_END_ */
/**
* Returns {@link fabric.Gradient} instance from its object representation
* @static
* @memberof fabric.Gradient
* @param {Object} obj
* @param {Object} [options] Options object
*/
forObject: function(obj, options) {
options || (options = { });
_convertPercentUnitsToValues(obj, options);
return new fabric.Gradient(options);
}
});
/**
* @private
*/
function _convertPercentUnitsToValues(object, options) {
for (var prop in options) {
if (typeof options[prop] === 'string' && /^\d+%$/.test(options[prop])) {
var percents = parseFloat(options[prop], 10);
if (prop === 'x1' || prop === 'x2' || prop === 'r2') {
options[prop] = fabric.util.toFixed(object.width * percents / 100, 2);
}
else if (prop === 'y1' || prop === 'y2') {
options[prop] = fabric.util.toFixed(object.height * percents / 100, 2);
}
}
// normalize rendering point (should be from top/left corner rather than center of the shape)
if (prop === 'x1' || prop === 'x2') {
options[prop] -= fabric.util.toFixed(object.width / 2, 2);
}
else if (prop === 'y1' || prop === 'y2') {
options[prop] -= fabric.util.toFixed(object.height / 2, 2);
}
}
}
/* _TO_SVG_START_ */
/**
* @private
*/
function _convertValuesToPercentUnits(object, options) {
for (var prop in options) {
// normalize rendering point (should be from center rather than top/left corner of the shape)
if (prop === 'x1' || prop === 'x2') {
options[prop] += fabric.util.toFixed(object.width / 2, 2);
}
else if (prop === 'y1' || prop === 'y2') {
options[prop] += fabric.util.toFixed(object.height / 2, 2);
}
// convert to percent units
if (prop === 'x1' || prop === 'x2' || prop === 'r2') {
options[prop] = fabric.util.toFixed(options[prop] / object.width * 100, 2) + '%';
}
else if (prop === 'y1' || prop === 'y2') {
options[prop] = fabric.util.toFixed(options[prop] / object.height * 100, 2) + '%';
}
}
}
/* _TO_SVG_END_ */
})();
/**
* Pattern class
* @class fabric.Pattern
* @see {@link http://fabricjs.com/patterns/|Pattern demo}
* @see {@link http://fabricjs.com/dynamic-patterns/|DynamicPattern demo}
*/
fabric.Pattern = fabric.util.createClass(/** @lends fabric.Pattern.prototype */ {
/**
* Repeat property of a pattern (one of repeat, repeat-x, repeat-y or no-repeat)
* @type String
* @default
*/
repeat: 'repeat',
/**
* Pattern horizontal offset from object's left/top corner
* @type Number
* @default
*/
offsetX: 0,
/**
* Pattern vertical offset from object's left/top corner
* @type Number
* @default
*/
offsetY: 0,
/**
* Constructor
* @param {Object} [options] Options object
* @return {fabric.Pattern} thisArg
*/
initialize: function(options) {
options || (options = { });
this.id = fabric.Object.__uid++;
if (options.source) {
if (typeof options.source === 'string') {
// function string
if (typeof fabric.util.getFunctionBody(options.source) !== 'undefined') {
this.source = new Function(fabric.util.getFunctionBody(options.source));
}
else {
// img src string
var _this = this;
this.source = fabric.util.createImage();
fabric.util.loadImage(options.source, function(img) {
_this.source = img;
});
}
}
else {
// img element
this.source = options.source;
}
}
if (options.repeat) {
this.repeat = options.repeat;
}
if (options.offsetX) {
this.offsetX = options.offsetX;
}
if (options.offsetY) {
this.offsetY = options.offsetY;
}
},
/**
* Returns object representation of a pattern
* @return {Object} Object representation of a pattern instance
*/
toObject: function() {
var source;
// callback
if (typeof this.source === 'function') {
source = String(this.source);
}
// element
else if (typeof this.source.src === 'string') {
source = this.source.src;
}
return {
source: source,
repeat: this.repeat,
offsetX: this.offsetX,
offsetY: this.offsetY
};
},
/* _TO_SVG_START_ */
/**
* Returns SVG representation of a pattern
* @param {fabric.Object} object
* @return {String} SVG representation of a pattern
*/
toSVG: function(object) {
var patternSource = typeof this.source === 'function' ? this.source() : this.source;
var patternWidth = patternSource.width / object.getWidth();
var patternHeight = patternSource.height / object.getHeight();
var patternImgSrc = '';
if (patternSource.src) {
patternImgSrc = patternSource.src;
}
else if (patternSource.toDataURL) {
patternImgSrc = patternSource.toDataURL();
}
return '' +
'' +
'';
},
/* _TO_SVG_END_ */
/**
* Returns an instance of CanvasPattern
* @param {CanvasRenderingContext2D} ctx Context to create pattern
* @return {CanvasPattern}
*/
toLive: function(ctx) {
var source = typeof this.source === 'function' ? this.source() : this.source;
return ctx.createPattern(source, this.repeat);
}
});
(function(global) {
"use strict";
var fabric = global.fabric || (global.fabric = { });
if (fabric.Shadow) {
fabric.warn('fabric.Shadow is already defined.');
return;
}
/**
* Shadow class
* @class fabric.Shadow
* @see {@link http://fabricjs.com/shadows/|Shadow demo}
*/
fabric.Shadow = fabric.util.createClass(/** @lends fabric.Shadow.prototype */ {
/**
* Shadow color
* @type String
* @default
*/
color: 'rgb(0,0,0)',
/**
* Shadow blur
* @type Number
*/
blur: 0,
/**
* Shadow horizontal offset
* @type Number
* @default
*/
offsetX: 0,
/**
* Shadow vertical offset
* @type Number
* @default
*/
offsetY: 0,
/**
* Whether the shadow should affect stroke operations
* @type Boolean
* @default
*/
affectStroke: false,
/**
* Constructor
* @param {Object|String} [options] Options object with any of color, blur, offsetX, offsetX properties or string (e.g. "rgba(0,0,0,0.2) 2px 2px 10px, "2px 2px 10px rgba(0,0,0,0.2)")
* @return {fabric.Shadow} thisArg
*/
initialize: function(options) {
if (typeof options === 'string') {
options = this._parseShadow(options);
}
for (var prop in options) {
this[prop] = options[prop];
}
this.id = fabric.Object.__uid++;
},
/**
* @private
* @param {String} shadow Shadow value to parse
* @return {Object} Shadow object with color, offsetX, offsetY and blur
*/
_parseShadow: function(shadow) {
var shadowStr = shadow.trim();
var offsetsAndBlur = fabric.Shadow.reOffsetsAndBlur.exec(shadowStr) || [ ],
color = shadowStr.replace(fabric.Shadow.reOffsetsAndBlur, '') || 'rgb(0,0,0)';
return {
color: color.trim(),
offsetX: parseInt(offsetsAndBlur[1], 10) || 0,
offsetY: parseInt(offsetsAndBlur[2], 10) || 0,
blur: parseInt(offsetsAndBlur[3], 10) || 0
};
},
/**
* Returns a string representation of an instance
* @see http://www.w3.org/TR/css-text-decor-3/#text-shadow
* @return {String} Returns CSS3 text-shadow declaration
*/
toString: function() {
return [this.offsetX, this.offsetY, this.blur, this.color].join('px ');
},
/* _TO_SVG_START_ */
/**
* Returns SVG representation of a shadow
* @param {fabric.Object} object
* @return {String} SVG representation of a shadow
*/
toSVG: function(object) {
var mode = 'SourceAlpha';
if (object && (object.fill === this.color || object.stroke === this.color)) {
mode = 'SourceGraphic';
}
return (
'' +
'' +
'' +
'' +
'' +
'' +
'' +
'');
},
/* _TO_SVG_END_ */
/**
* Returns object representation of a shadow
* @return {Object} Object representation of a shadow instance
*/
toObject: function() {
return {
color: this.color,
blur: this.blur,
offsetX: this.offsetX,
offsetY: this.offsetY
};
}
});
/**
* Regex matching shadow offsetX, offsetY and blur (ex: "2px 2px 10px rgba(0,0,0,0.2)", "rgb(0,255,0) 2px 2px")
* @static
* @field
* @memberOf fabric.Shadow
*/
fabric.Shadow.reOffsetsAndBlur = /(?:\s|^)(-?\d+(?:px)?(?:\s?|$))?(-?\d+(?:px)?(?:\s?|$))?(\d+(?:px)?)?(?:\s?|$)(?:$|\s)/;
})(typeof exports !== 'undefined' ? exports : this);
(function () {
"use strict";
if (fabric.StaticCanvas) {
fabric.warn('fabric.StaticCanvas is already defined.');
return;
}
// aliases for faster resolution
var extend = fabric.util.object.extend,
getElementOffset = fabric.util.getElementOffset,
removeFromArray = fabric.util.removeFromArray,
removeListener = fabric.util.removeListener,
CANVAS_INIT_ERROR = new Error('Could not initialize `canvas` element');
/**
* Static canvas class
* @class fabric.StaticCanvas
* @mixes fabric.Collection
* @mixes fabric.Observable
* @see {@link http://fabricjs.com/static_canvas/|StaticCanvas demo}
* @fires before:render
* @fires after:render
* @fires canvas:cleared
* @fires object:added
* @fires object:removed
*/
fabric.StaticCanvas = fabric.util.createClass(/** @lends fabric.StaticCanvas.prototype */ {
/**
* Constructor
* @param {HTMLElement | String} el <canvas> element to initialize instance on
* @param {Object} [options] Options object
* @return {Object} thisArg
*/
initialize: function(el, options) {
options || (options = { });
this._initStatic(el, options);
fabric.StaticCanvas.activeInstance = this;
},
/**
* Background color of canvas instance
* @type String
* @default
*/
backgroundColor: '',
/**
* Background image of canvas instance
* Should be set via {@link fabric.StaticCanvas#setBackgroundImage}
* @type String
* @default
*/
backgroundImage: '',
/**
* Opacity of the background image of the canvas instance
* @type Float
* @default
*/
backgroundImageOpacity: 1,
/**
* Indicates whether the background image should be stretched to fit the
* dimensions of the canvas instance.
* @type Boolean
* @default
*/
backgroundImageStretch: true,
/**
* Overlay image of canvas instance
* Should be set via {@link fabric.StaticCanvas#setOverlayImage}
* @type String
* @default
*/
overlayImage: '',
/**
* Left offset of overlay image (if present)
* @type Number
* @default
*/
overlayImageLeft: 0,
/**
* Top offset of overlay image (if present)
* @type Number
* @default
*/
overlayImageTop: 0,
/**
* Indicates whether toObject/toDatalessObject should include default values
* @type Boolean
* @default
*/
includeDefaultValues: true,
/**
* Indicates whether objects' state should be saved
* @type Boolean
* @default
*/
stateful: true,
/**
* Indicates whether {@link fabric.Collection.add}, {@link fabric.Collection.insertAt} and {@link fabric.Collection.remove} should also re-render canvas.
* Disabling this option could give a great performance boost when adding/removing a lot of objects to/from canvas at once
* (followed by a manual rendering after addition/deletion)
* @type Boolean
* @default
*/
renderOnAddRemove: true,
/**
* Function that determines clipping of entire canvas area
* Being passed context as first argument. See clipping canvas area in {@link https://github.com/kangax/fabric.js/wiki/FAQ}
* @type Function
* @default
*/
clipTo: null,
/**
* Indicates whether object controls (borders/controls) are rendered above overlay image
* @type Boolean
* @default
*/
controlsAboveOverlay: false,
/**
* Indicates whether the browser can be scrolled when using a touchscreen and dragging on the canvas
* @type Boolean
* @default
*/
allowTouchScrolling: false,
/**
* Callback; invoked right before object is about to be scaled/rotated
* @param {fabric.Object} target Object that's about to be scaled/rotated
*/
onBeforeScaleRotate: function () {
/* NOOP */
},
/**
* @private
* @param {HTMLElement | String} el <canvas> element to initialize instance on
* @param {Object} [options] Options object
*/
_initStatic: function(el, options) {
this._objects = [];
this._createLowerCanvas(el);
this._initOptions(options);
if (options.overlayImage) {
this.setOverlayImage(options.overlayImage, this.renderAll.bind(this));
}
if (options.backgroundImage) {
this.setBackgroundImage(options.backgroundImage, this.renderAll.bind(this));
}
if (options.backgroundColor) {
this.setBackgroundColor(options.backgroundColor, this.renderAll.bind(this));
}
this.calcOffset();
},
/**
* Calculates canvas element offset relative to the document
* This method is also attached as "resize" event handler of window
* @return {fabric.Canvas} instance
* @chainable
*/
calcOffset: function () {
this._offset = getElementOffset(this.lowerCanvasEl);
return this;
},
/**
* Sets {@link fabric.StaticCanvas#overlayImage|overlay image} for this canvas
* @param {String} url url of an image to set overlay to
* @param {Function} callback callback to invoke when image is loaded and set as an overlay
* @param {Object} [options] Optional options to set for the overlay image
* @param {Number} [options.overlayImageLeft] {@link fabric.StaticCanvas#overlayImageLeft|Left offset} of overlay image
* @param {Number} [options.overlayImageTop] {@link fabric.StaticCanvas#overlayImageTop|Top offset} of overlay image
* @return {fabric.Canvas} thisArg
* @chainable
* @see {@link http://jsfiddle.net/fabricjs/MnzHT/|jsFiddle demo}
* @example
* canvas.setOverlayImage('http://fabricjs.com/assets/jail_cell_bars.png', canvas.renderAll.bind(canvas), {
* overlayImageLeft: 100,
* overlayImageTop: 100
* });
*/
setOverlayImage: function (url, callback, options) { // TODO (kangax): test callback
fabric.util.loadImage(url, function(img) {
this.overlayImage = img;
if (options && ('overlayImageLeft' in options)) {
this.overlayImageLeft = options.overlayImageLeft;
}
if (options && ('overlayImageTop' in options)) {
this.overlayImageTop = options.overlayImageTop;
}
callback && callback();
}, this);
return this;
},
/**
* Sets {@link fabric.StaticCanvas#backgroundImage|background image} for this canvas
* @param {String} url URL of an image to set background to
* @param {Function} callback callback to invoke when image is loaded and set as background
* @param {Object} [options] Optional options to set for the background image
* @param {Float} [options.backgroundImageOpacity] {@link fabric.StaticCanvas#backgroundImageOpacity|Opacity} of the background image of the canvas instance
* @param {Boolean} [options.backgroundImageStretch] Indicates whether the background image should be {@link fabric.StaticCanvas#backgroundImageStretch|strechted} to fit the canvas
* @return {fabric.Canvas} thisArg
* @chainable
* @see {@link http://jsfiddle.net/fabricjs/YH9yD/|jsFiddle demo}
* @example
SVG output with different encoding (default: UTF-8)
* var svg = canvas.toSVG({encoding: 'ISO-8859-1'});
* @example
Modify SVG output with reviver function
* var svg = canvas.toSVG(null, function(svg) {
* return svg.replace('stroke-dasharray: ; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; ', '');
* });
*/
toSVG: function(options, reviver) {
options || (options = { });
var markup = [];
if (!options.suppressPreamble) {
markup.push(
'',
'\n'
);
}
markup.push(
'');
return markup.join('');
},
/* _TO_SVG_END_ */
/**
* Removes an object from canvas and returns it
* @param {fabric.Object} object Object to remove
* @return {fabric.Object} removed object
*/
remove: function (object) {
// removing active object should fire "selection:cleared" events
if (this.getActiveObject() === object) {
this.fire('before:selection:cleared', { target: object });
this.discardActiveObject();
this.fire('selection:cleared');
}
return fabric.Collection.remove.call(this, object);
},
/**
* Moves an object to the bottom of the stack of drawn objects
* @param {fabric.Object} object Object to send to back
* @return {fabric.Canvas} thisArg
* @chainable
*/
sendToBack: function (object) {
removeFromArray(this._objects, object);
this._objects.unshift(object);
return this.renderAll && this.renderAll();
},
/**
* Moves an object to the top of the stack of drawn objects
* @param {fabric.Object} object Object to send
* @return {fabric.Canvas} thisArg
* @chainable
*/
bringToFront: function (object) {
removeFromArray(this._objects, object);
this._objects.push(object);
return this.renderAll && this.renderAll();
},
/**
* Moves an object down in stack of drawn objects
* @param {fabric.Object} object Object to send
* @param {Boolean} [intersecting] If `true`, send object behind next lower intersecting object
* @return {fabric.Canvas} thisArg
* @chainable
*/
sendBackwards: function (object, intersecting) {
var idx = this._objects.indexOf(object);
// if object is not on the bottom of stack
if (idx !== 0) {
var newIdx;
if (intersecting) {
newIdx = idx;
// traverse down the stack looking for the nearest intersecting object
for (var i=idx-1; i>=0; --i) {
var isIntersecting = object.intersectsWithObject(this._objects[i]) ||
object.isContainedWithinObject(this._objects[i]) ||
this._objects[i].isContainedWithinObject(object);
if (isIntersecting) {
newIdx = i;
break;
}
}
}
else {
newIdx = idx-1;
}
removeFromArray(this._objects, object);
this._objects.splice(newIdx, 0, object);
this.renderAll && this.renderAll();
}
return this;
},
/**
* Moves an object up in stack of drawn objects
* @param {fabric.Object} object Object to send
* @param {Boolean} [intersecting] If `true`, send object in front of next upper intersecting object
* @return {fabric.Canvas} thisArg
* @chainable
*/
bringForward: function (object, intersecting) {
var idx = this._objects.indexOf(object);
// if object is not on top of stack (last item in an array)
if (idx !== this._objects.length-1) {
var newIdx;
if (intersecting) {
newIdx = idx;
// traverse up the stack looking for the nearest intersecting object
for (var i = idx + 1; i < this._objects.length; ++i) {
var isIntersecting = object.intersectsWithObject(this._objects[i]) ||
object.isContainedWithinObject(this._objects[i]) ||
this._objects[i].isContainedWithinObject(object);
if (isIntersecting) {
newIdx = i;
break;
}
}
}
else {
newIdx = idx+1;
}
removeFromArray(this._objects, object);
this._objects.splice(newIdx, 0, object);
this.renderAll && this.renderAll();
}
return this;
},
/**
* Moves an object to specified level in stack of drawn objects
* @param {fabric.Object} object Object to send
* @param {Number} index Position to move to
* @return {fabric.Canvas} thisArg
* @chainable
*/
moveTo: function (object, index) {
removeFromArray(this._objects, object);
this._objects.splice(index, 0, object);
return this.renderAll && this.renderAll();
},
/**
* Clears a canvas element and removes all event handlers.
* @return {fabric.Canvas} thisArg
* @chainable
*/
dispose: function () {
this.clear();
if (!this.interactive) return this;
if (fabric.isTouchSupported) {
removeListener(this.upperCanvasEl, 'touchstart', this._onMouseDown);
removeListener(this.upperCanvasEl, 'touchmove', this._onMouseMove);
if (typeof Event !== 'undefined' && 'remove' in Event) {
Event.remove(this.upperCanvasEl, 'gesture', this._onGesture);
}
}
else {
removeListener(this.upperCanvasEl, 'mousedown', this._onMouseDown);
removeListener(this.upperCanvasEl, 'mousemove', this._onMouseMove);
removeListener(fabric.window, 'resize', this._onResize);
}
return this;
},
/**
* Returns a string representation of an instance
* @return {String} string representation of an instance
*/
toString: function () {
return '#';
}
});
extend(fabric.StaticCanvas.prototype, fabric.Observable);
extend(fabric.StaticCanvas.prototype, fabric.Collection);
extend(fabric.StaticCanvas.prototype, fabric.DataURLExporter);
extend(fabric.StaticCanvas, /** @lends fabric.StaticCanvas */ {
/**
* @static
* @type String
* @default
*/
EMPTY_JSON: '{"objects": [], "background": "white"}',
/**
* Provides a way to check support of some of the canvas methods
* (either those of HTMLCanvasElement itself, or rendering context)
*
* @param methodName {String} Method to check support for;
* Could be one of "getImageData", "toDataURL", "toDataURLWithQuality" or "setLineDash"
* @return {Boolean | null} `true` if method is supported (or at least exists),
* `null` if canvas element or context can not be initialized
*/
supports: function (methodName) {
var el = fabric.util.createCanvasElement();
if (!el || !el.getContext) {
return null;
}
var ctx = el.getContext('2d');
if (!ctx) {
return null;
}
switch (methodName) {
case 'getImageData':
return typeof ctx.getImageData !== 'undefined';
case 'setLineDash':
return typeof ctx.setLineDash !== 'undefined';
case 'toDataURL':
return typeof el.toDataURL !== 'undefined';
case 'toDataURLWithQuality':
try {
el.toDataURL('image/jpeg', 0);
return true;
}
catch (e) { }
return false;
default:
return null;
}
}
});
/**
* Returns JSON representation of canvas
* @function
* @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
* @return {String} JSON string
* @tutorial {@link http://fabricjs.com/fabric-intro-part-3/#serialization}
* @see {@link http://jsfiddle.net/fabricjs/pec86/|jsFiddle demo}
* @example