APIs

Show:
  1. /* build: `node build.js modules=ALL exclude=gestures,cufon,json minifier=uglifyjs` */
  2. /*! Fabric.js Copyright 2008-2014, Printio (Juriy Zaytsev, Maxim Chernyak) */
  3.  
  4. var fabric = fabric || { version: "1.4.12" };
  5. if (typeof exports !== 'undefined') {
  6. exports.fabric = fabric;
  7. }
  8.  
  9. if (typeof document !== 'undefined' && typeof window !== 'undefined') {
  10. fabric.document = document;
  11. fabric.window = window;
  12. }
  13. else {
  14. // assume we're running under node.js when document/window are not present
  15. fabric.document = require("jsdom")
  16. .jsdom("<!DOCTYPE html><html><head></head><body></body></html>");
  17.  
  18. fabric.window = fabric.document.createWindow();
  19. }
  20.  
  21. /**
  22. * True when in environment that supports touch events
  23. * @type boolean
  24. */
  25. fabric.isTouchSupported = "ontouchstart" in fabric.document.documentElement;
  26.  
  27. /**
  28. * True when in environment that's probably Node.js
  29. * @type boolean
  30. */
  31. fabric.isLikelyNode = typeof Buffer !== 'undefined' &&
  32. typeof window === 'undefined';
  33.  
  34.  
  35. /**
  36. * Attributes parsed from all SVG elements
  37. * @type array
  38. */
  39. fabric.SHARED_ATTRIBUTES = [
  40. "display",
  41. "transform",
  42. "fill", "fill-opacity", "fill-rule",
  43. "opacity",
  44. "stroke", "stroke-dasharray", "stroke-linecap",
  45. "stroke-linejoin", "stroke-miterlimit",
  46. "stroke-opacity", "stroke-width"
  47. ];
  48.  
  49. /**
  50. * Pixel per Inch as a default value set to 96. Can be changed for more realistic conversion.
  51. */
  52. fabric.DPI = 96;
  53.  
  54.  
  55. (function() {
  56.  
  57. /**
  58. * @private
  59. * @param {String} eventName
  60. * @param {Function} handler
  61. */
  62. function _removeEventListener(eventName, handler) {
  63. if (!this.__eventListeners[eventName]) {
  64. return;
  65. }
  66.  
  67. if (handler) {
  68. fabric.util.removeFromArray(this.__eventListeners[eventName], handler);
  69. }
  70. else {
  71. this.__eventListeners[eventName].length = 0;
  72. }
  73. }
  74.  
  75. /**
  76. * Observes specified event
  77. * @deprecated `observe` deprecated since 0.8.34 (use `on` instead)
  78. * @memberOf fabric.Observable
  79. * @alias on
  80. * @param {String|Object} eventName Event name (eg. 'after:render') or object with key/value pairs (eg. {'after:render': handler, 'selection:cleared': handler})
  81. * @param {Function} handler Function that receives a notification when an event of the specified type occurs
  82. * @return {Self} thisArg
  83. * @chainable
  84. */
  85. function observe(eventName, handler) {
  86. if (!this.__eventListeners) {
  87. this.__eventListeners = { };
  88. }
  89. // one object with key/value pairs was passed
  90. if (arguments.length === 1) {
  91. for (var prop in eventName) {
  92. this.on(prop, eventName[prop]);
  93. }
  94. }
  95. else {
  96. if (!this.__eventListeners[eventName]) {
  97. this.__eventListeners[eventName] = [ ];
  98. }
  99. this.__eventListeners[eventName].push(handler);
  100. }
  101. return this;
  102. }
  103.  
  104. /**
  105. * Stops event observing for a particular event handler. Calling this method
  106. * without arguments removes all handlers for all events
  107. * @deprecated `stopObserving` deprecated since 0.8.34 (use `off` instead)
  108. * @memberOf fabric.Observable
  109. * @alias off
  110. * @param {String|Object} eventName Event name (eg. 'after:render') or object with key/value pairs (eg. {'after:render': handler, 'selection:cleared': handler})
  111. * @param {Function} handler Function to be deleted from EventListeners
  112. * @return {Self} thisArg
  113. * @chainable
  114. */
  115. function stopObserving(eventName, handler) {
  116. if (!this.__eventListeners) {
  117. return;
  118. }
  119.  
  120. // remove all key/value pairs (event name -> event handler)
  121. if (arguments.length === 0) {
  122. this.__eventListeners = { };
  123. }
  124. // one object with key/value pairs was passed
  125. else if (arguments.length === 1 && typeof arguments[0] === 'object') {
  126. for (var prop in eventName) {
  127. _removeEventListener.call(this, prop, eventName[prop]);
  128. }
  129. }
  130. else {
  131. _removeEventListener.call(this, eventName, handler);
  132. }
  133. return this;
  134. }
  135.  
  136. /**
  137. * Fires event with an optional options object
  138. * @deprecated `fire` deprecated since 1.0.7 (use `trigger` instead)
  139. * @memberOf fabric.Observable
  140. * @alias trigger
  141. * @param {String} eventName Event name to fire
  142. * @param {Object} [options] Options object
  143. * @return {Self} thisArg
  144. * @chainable
  145. */
  146. function fire(eventName, options) {
  147. if (!this.__eventListeners) {
  148. return;
  149. }
  150.  
  151. var listenersForEvent = this.__eventListeners[eventName];
  152. if (!listenersForEvent) {
  153. return;
  154. }
  155.  
  156. for (var i = 0, len = listenersForEvent.length; i < len; i++) {
  157. // avoiding try/catch for perf. reasons
  158. listenersForEvent[i].call(this, options || { });
  159. }
  160. return this;
  161. }
  162.  
  163. /**
  164. * @namespace fabric.Observable
  165. * @tutorial {@link http://fabricjs.com/fabric-intro-part-2/#events}
  166. * @see {@link http://fabricjs.com/events/|Events demo}
  167. */
  168. fabric.Observable = {
  169. observe: observe,
  170. stopObserving: stopObserving,
  171. fire: fire,
  172.  
  173. on: observe,
  174. off: stopObserving,
  175. trigger: fire
  176. };
  177. })();
  178.  
  179.  
  180. /**
  181. * @namespace fabric.Collection
  182. */
  183. fabric.Collection = {
  184.  
  185. /**
  186. * Adds objects to collection, then renders canvas (if `renderOnAddRemove` is not `false`)
  187. * Objects should be instances of (or inherit from) fabric.Object
  188. * @param {...fabric.Object} object Zero or more fabric instances
  189. * @return {Self} thisArg
  190. */
  191. add: function () {
  192. this._objects.push.apply(this._objects, arguments);
  193. for (var i = 0, length = arguments.length; i < length; i++) {
  194. this._onObjectAdded(arguments[i]);
  195. }
  196. this.renderOnAddRemove && this.renderAll();
  197. return this;
  198. },
  199.  
  200. /**
  201. * Inserts an object into collection at specified index, then renders canvas (if `renderOnAddRemove` is not `false`)
  202. * An object should be an instance of (or inherit from) fabric.Object
  203. * @param {Object} object Object to insert
  204. * @param {Number} index Index to insert object at
  205. * @param {Boolean} nonSplicing When `true`, no splicing (shifting) of objects occurs
  206. * @return {Self} thisArg
  207. * @chainable
  208. */
  209. insertAt: function (object, index, nonSplicing) {
  210. var objects = this.getObjects();
  211. if (nonSplicing) {
  212. objects[index] = object;
  213. }
  214. else {
  215. objects.splice(index, 0, object);
  216. }
  217. this._onObjectAdded(object);
  218. this.renderOnAddRemove && this.renderAll();
  219. return this;
  220. },
  221.  
  222. /**
  223. * Removes objects from a collection, then renders canvas (if `renderOnAddRemove` is not `false`)
  224. * @param {...fabric.Object} object Zero or more fabric instances
  225. * @return {Self} thisArg
  226. * @chainable
  227. */
  228. remove: function() {
  229. var objects = this.getObjects(),
  230. index;
  231.  
  232. for (var i = 0, length = arguments.length; i < length; i++) {
  233. index = objects.indexOf(arguments[i]);
  234.  
  235. // only call onObjectRemoved if an object was actually removed
  236. if (index !== -1) {
  237. objects.splice(index, 1);
  238. this._onObjectRemoved(arguments[i]);
  239. }
  240. }
  241.  
  242. this.renderOnAddRemove && this.renderAll();
  243. return this;
  244. },
  245.  
  246. /**
  247. * Executes given function for each object in this group
  248. * @param {Function} callback
  249. * Callback invoked with current object as first argument,
  250. * index - as second and an array of all objects - as third.
  251. * Iteration happens in reverse order (for performance reasons).
  252. * Callback is invoked in a context of Global Object (e.g. `window`)
  253. * when no `context` argument is given
  254. *
  255. * @param {Object} context Context (aka thisObject)
  256. * @return {Self} thisArg
  257. */
  258. forEachObject: function(callback, context) {
  259. var objects = this.getObjects(),
  260. i = objects.length;
  261. while (i--) {
  262. callback.call(context, objects[i], i, objects);
  263. }
  264. return this;
  265. },
  266.  
  267. /**
  268. * Returns an array of children objects of this instance
  269. * Type parameter introduced in 1.3.10
  270. * @param {String} [type] When specified, only objects of this type are returned
  271. * @return {Array}
  272. */
  273. getObjects: function(type) {
  274. if (typeof type === 'undefined') {
  275. return this._objects;
  276. }
  277. return this._objects.filter(function(o) {
  278. return o.type === type;
  279. });
  280. },
  281.  
  282. /**
  283. * Returns object at specified index
  284. * @param {Number} index
  285. * @return {Self} thisArg
  286. */
  287. item: function (index) {
  288. return this.getObjects()[index];
  289. },
  290.  
  291. /**
  292. * Returns true if collection contains no objects
  293. * @return {Boolean} true if collection is empty
  294. */
  295. isEmpty: function () {
  296. return this.getObjects().length === 0;
  297. },
  298.  
  299. /**
  300. * Returns a size of a collection (i.e: length of an array containing its objects)
  301. * @return {Number} Collection size
  302. */
  303. size: function() {
  304. return this.getObjects().length;
  305. },
  306.  
  307. /**
  308. * Returns true if collection contains an object
  309. * @param {Object} object Object to check against
  310. * @return {Boolean} `true` if collection contains an object
  311. */
  312. contains: function(object) {
  313. return this.getObjects().indexOf(object) > -1;
  314. },
  315.  
  316. /**
  317. * Returns number representation of a collection complexity
  318. * @return {Number} complexity
  319. */
  320. complexity: function () {
  321. return this.getObjects().reduce(function (memo, current) {
  322. memo += current.complexity ? current.complexity() : 0;
  323. return memo;
  324. }, 0);
  325. }
  326. };
  327.  
  328.  
  329. (function(global) {
  330.  
  331. var sqrt = Math.sqrt,
  332. atan2 = Math.atan2,
  333. PiBy180 = Math.PI / 180;
  334.  
  335. /**
  336. * @namespace fabric.util
  337. */
  338. fabric.util = {
  339.  
  340. /**
  341. * Removes value from an array.
  342. * Presence of value (and its position in an array) is determined via `Array.prototype.indexOf`
  343. * @static
  344. * @memberOf fabric.util
  345. * @param {Array} array
  346. * @param {Any} value
  347. * @return {Array} original array
  348. */
  349. removeFromArray: function(array, value) {
  350. var idx = array.indexOf(value);
  351. if (idx !== -1) {
  352. array.splice(idx, 1);
  353. }
  354. return array;
  355. },
  356.  
  357. /**
  358. * Returns random number between 2 specified ones.
  359. * @static
  360. * @memberOf fabric.util
  361. * @param {Number} min lower limit
  362. * @param {Number} max upper limit
  363. * @return {Number} random value (between min and max)
  364. */
  365. getRandomInt: function(min, max) {
  366. return Math.floor(Math.random() * (max - min + 1)) + min;
  367. },
  368.  
  369. /**
  370. * Transforms degrees to radians.
  371. * @static
  372. * @memberOf fabric.util
  373. * @param {Number} degrees value in degrees
  374. * @return {Number} value in radians
  375. */
  376. degreesToRadians: function(degrees) {
  377. return degrees * PiBy180;
  378. },
  379.  
  380. /**
  381. * Transforms radians to degrees.
  382. * @static
  383. * @memberOf fabric.util
  384. * @param {Number} radians value in radians
  385. * @return {Number} value in degrees
  386. */
  387. radiansToDegrees: function(radians) {
  388. return radians / PiBy180;
  389. },
  390.  
  391. /**
  392. * Rotates `point` around `origin` with `radians`
  393. * @static
  394. * @memberOf fabric.util
  395. * @param {fabric.Point} point The point to rotate
  396. * @param {fabric.Point} origin The origin of the rotation
  397. * @param {Number} radians The radians of the angle for the rotation
  398. * @return {fabric.Point} The new rotated point
  399. */
  400. rotatePoint: function(point, origin, radians) {
  401. var sin = Math.sin(radians),
  402. cos = Math.cos(radians);
  403.  
  404. point.subtractEquals(origin);
  405.  
  406. var rx = point.x * cos - point.y * sin,
  407. ry = point.x * sin + point.y * cos;
  408.  
  409. return new fabric.Point(rx, ry).addEquals(origin);
  410. },
  411.  
  412. /**
  413. * Apply transform t to point p
  414. * @static
  415. * @memberOf fabric.util
  416. * @param {fabric.Point} p The point to transform
  417. * @param {Array} t The transform
  418. * @param {Boolean} [ignoreOffset] Indicates that the offset should not be applied
  419. * @return {fabric.Point} The transformed point
  420. */
  421. transformPoint: function(p, t, ignoreOffset) {
  422. if (ignoreOffset) {
  423. return new fabric.Point(
  424. t[0] * p.x + t[1] * p.y,
  425. t[2] * p.x + t[3] * p.y
  426. );
  427. }
  428. return new fabric.Point(
  429. t[0] * p.x + t[1] * p.y + t[4],
  430. t[2] * p.x + t[3] * p.y + t[5]
  431. );
  432. },
  433.  
  434. /**
  435. * Invert transformation t
  436. * @static
  437. * @memberOf fabric.util
  438. * @param {Array} t The transform
  439. * @return {Array} The inverted transform
  440. */
  441. invertTransform: function(t) {
  442. var r = t.slice(),
  443. a = 1 / (t[0] * t[3] - t[1] * t[2]);
  444. r = [a * t[3], -a * t[1], -a * t[2], a * t[0], 0, 0];
  445. var o = fabric.util.transformPoint({ x: t[4], y: t[5] }, r);
  446. r[4] = -o.x;
  447. r[5] = -o.y;
  448. return r;
  449. },
  450.  
  451. /**
  452. * A wrapper around Number#toFixed, which contrary to native method returns number, not string.
  453. * @static
  454. * @memberOf fabric.util
  455. * @param {Number|String} number number to operate on
  456. * @param {Number} fractionDigits number of fraction digits to "leave"
  457. * @return {Number}
  458. */
  459. toFixed: function(number, fractionDigits) {
  460. return parseFloat(Number(number).toFixed(fractionDigits));
  461. },
  462.  
  463. /**
  464. * Converts from attribute value to pixel value if applicable.
  465. * Returns converted pixels or original value not converted.
  466. * @param {Number|String} value number to operate on
  467. * @return {Number|String}
  468. */
  469. parseUnit: function(value) {
  470. var unit = /\D{0,2}$/.exec(value),
  471. number = parseFloat(value);
  472.  
  473. switch (unit[0]) {
  474. case 'mm':
  475. return number * fabric.DPI / 25.4;
  476.  
  477. case 'cm':
  478. return number * fabric.DPI / 2.54;
  479.  
  480. case 'in':
  481. return number * fabric.DPI;
  482.  
  483. case 'pt':
  484. return number * fabric.DPI / 72; // or * 4 / 3
  485.  
  486. case 'pc':
  487. return number * fabric.DPI / 72 * 12; // or * 16
  488.  
  489. default:
  490. return number;
  491. }
  492. },
  493.  
  494. /**
  495. * Function which always returns `false`.
  496. * @static
  497. * @memberOf fabric.util
  498. * @return {Boolean}
  499. */
  500. falseFunction: function() {
  501. return false;
  502. },
  503.  
  504. /**
  505. * Returns klass "Class" object of given namespace
  506. * @memberOf fabric.util
  507. * @param {String} type Type of object (eg. 'circle')
  508. * @param {String} namespace Namespace to get klass "Class" object from
  509. * @return {Object} klass "Class"
  510. */
  511. getKlass: function(type, namespace) {
  512. // capitalize first letter only
  513. type = fabric.util.string.camelize(type.charAt(0).toUpperCase() + type.slice(1));
  514. return fabric.util.resolveNamespace(namespace)[type];
  515. },
  516.  
  517. /**
  518. * Returns object of given namespace
  519. * @memberOf fabric.util
  520. * @param {String} namespace Namespace string e.g. 'fabric.Image.filter' or 'fabric'
  521. * @return {Object} Object for given namespace (default fabric)
  522. */
  523. resolveNamespace: function(namespace) {
  524. if (!namespace) {
  525. return fabric;
  526. }
  527.  
  528. var parts = namespace.split('.'),
  529. len = parts.length,
  530. obj = global || fabric.window;
  531.  
  532. for (var i = 0; i < len; ++i) {
  533. obj = obj[parts[i]];
  534. }
  535.  
  536. return obj;
  537. },
  538.  
  539. /**
  540. * Loads image element from given url and passes it to a callback
  541. * @memberOf fabric.util
  542. * @param {String} url URL representing an image
  543. * @param {Function} callback Callback; invoked with loaded image
  544. * @param {Any} [context] Context to invoke callback in
  545. * @param {Object} [crossOrigin] crossOrigin value to set image element to
  546. */
  547. loadImage: function(url, callback, context, crossOrigin) {
  548. if (!url) {
  549. callback && callback.call(context, url);
  550. return;
  551. }
  552.  
  553. var img = fabric.util.createImage();
  554.  
  555. /** @ignore */
  556. img.onload = function () {
  557. callback && callback.call(context, img);
  558. img = img.onload = img.onerror = null;
  559. };
  560.  
  561. /** @ignore */
  562. img.onerror = function() {
  563. fabric.log('Error loading ' + img.src);
  564. callback && callback.call(context, null, true);
  565. img = img.onload = img.onerror = null;
  566. };
  567.  
  568. // data-urls appear to be buggy with crossOrigin
  569. // https://github.com/kangax/fabric.js/commit/d0abb90f1cd5c5ef9d2a94d3fb21a22330da3e0a#commitcomment-4513767
  570. // see https://code.google.com/p/chromium/issues/detail?id=315152
  571. // https://bugzilla.mozilla.org/show_bug.cgi?id=935069
  572. if (url.indexOf('data') !== 0 && typeof crossOrigin !== 'undefined') {
  573. img.crossOrigin = crossOrigin;
  574. }
  575.  
  576. img.src = url;
  577. },
  578.  
  579. /**
  580. * Creates corresponding fabric instances from their object representations
  581. * @static
  582. * @memberOf fabric.util
  583. * @param {Array} objects Objects to enliven
  584. * @param {Function} callback Callback to invoke when all objects are created
  585. * @param {String} namespace Namespace to get klass "Class" object from
  586. * @param {Function} reviver Method for further parsing of object elements,
  587. * called after each fabric object created.
  588. */
  589. enlivenObjects: function(objects, callback, namespace, reviver) {
  590. objects = objects || [ ];
  591.  
  592. function onLoaded() {
  593. if (++numLoadedObjects === numTotalObjects) {
  594. callback && callback(enlivenedObjects);
  595. }
  596. }
  597.  
  598. var enlivenedObjects = [ ],
  599. numLoadedObjects = 0,
  600. numTotalObjects = objects.length;
  601.  
  602. if (!numTotalObjects) {
  603. callback && callback(enlivenedObjects);
  604. return;
  605. }
  606.  
  607. objects.forEach(function (o, index) {
  608. // if sparse array
  609. if (!o || !o.type) {
  610. onLoaded();
  611. return;
  612. }
  613. var klass = fabric.util.getKlass(o.type, namespace);
  614. if (klass.async) {
  615. klass.fromObject(o, function (obj, error) {
  616. if (!error) {
  617. enlivenedObjects[index] = obj;
  618. reviver && reviver(o, enlivenedObjects[index]);
  619. }
  620. onLoaded();
  621. });
  622. }
  623. else {
  624. enlivenedObjects[index] = klass.fromObject(o);
  625. reviver && reviver(o, enlivenedObjects[index]);
  626. onLoaded();
  627. }
  628. });
  629. },
  630.  
  631. /**
  632. * Groups SVG elements (usually those retrieved from SVG document)
  633. * @static
  634. * @memberOf fabric.util
  635. * @param {Array} elements SVG elements to group
  636. * @param {Object} [options] Options object
  637. * @return {fabric.Object|fabric.PathGroup}
  638. */
  639. groupSVGElements: function(elements, options, path) {
  640. var object;
  641.  
  642. object = new fabric.PathGroup(elements, options);
  643.  
  644. if (typeof path !== 'undefined') {
  645. object.setSourcePath(path);
  646. }
  647. return object;
  648. },
  649.  
  650. /**
  651. * Populates an object with properties of another object
  652. * @static
  653. * @memberOf fabric.util
  654. * @param {Object} source Source object
  655. * @param {Object} destination Destination object
  656. * @return {Array} properties Propertie names to include
  657. */
  658. populateWithProperties: function(source, destination, properties) {
  659. if (properties && Object.prototype.toString.call(properties) === '[object Array]') {
  660. for (var i = 0, len = properties.length; i < len; i++) {
  661. if (properties[i] in source) {
  662. destination[properties[i]] = source[properties[i]];
  663. }
  664. }
  665. }
  666. },
  667.  
  668. /**
  669. * Draws a dashed line between two points
  670. *
  671. * This method is used to draw dashed line around selection area.
  672. * See <a href="http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas">dotted stroke in canvas</a>
  673. *
  674. * @param {CanvasRenderingContext2D} ctx context
  675. * @param {Number} x start x coordinate
  676. * @param {Number} y start y coordinate
  677. * @param {Number} x2 end x coordinate
  678. * @param {Number} y2 end y coordinate
  679. * @param {Array} da dash array pattern
  680. */
  681. drawDashedLine: function(ctx, x, y, x2, y2, da) {
  682. var dx = x2 - x,
  683. dy = y2 - y,
  684. len = sqrt(dx * dx + dy * dy),
  685. rot = atan2(dy, dx),
  686. dc = da.length,
  687. di = 0,
  688. draw = true;
  689.  
  690. ctx.save();
  691. ctx.translate(x, y);
  692. ctx.moveTo(0, 0);
  693. ctx.rotate(rot);
  694.  
  695. x = 0;
  696. while (len > x) {
  697. x += da[di++ % dc];
  698. if (x > len) {
  699. x = len;
  700. }
  701. ctx[draw ? 'lineTo' : 'moveTo'](x, 0);
  702. draw = !draw;
  703. }
  704.  
  705. ctx.restore();
  706. },
  707.  
  708. /**
  709. * Creates canvas element and initializes it via excanvas if necessary
  710. * @static
  711. * @memberOf fabric.util
  712. * @param {CanvasElement} [canvasEl] optional canvas element to initialize;
  713. * when not given, element is created implicitly
  714. * @return {CanvasElement} initialized canvas element
  715. */
  716. createCanvasElement: function(canvasEl) {
  717. canvasEl || (canvasEl = fabric.document.createElement('canvas'));
  718. //jscs:disable requireCamelCaseOrUpperCaseIdentifiers
  719. if (!canvasEl.getContext && typeof G_vmlCanvasManager !== 'undefined') {
  720. G_vmlCanvasManager.initElement(canvasEl);
  721. }
  722. //jscs:enable requireCamelCaseOrUpperCaseIdentifiers
  723. return canvasEl;
  724. },
  725.  
  726. /**
  727. * Creates image element (works on client and node)
  728. * @static
  729. * @memberOf fabric.util
  730. * @return {HTMLImageElement} HTML image element
  731. */
  732. createImage: function() {
  733. return fabric.isLikelyNode
  734. ? new (require('canvas').Image)()
  735. : fabric.document.createElement('img');
  736. },
  737.  
  738. /**
  739. * Creates accessors (getXXX, setXXX) for a "class", based on "stateProperties" array
  740. * @static
  741. * @memberOf fabric.util
  742. * @param {Object} klass "Class" to create accessors for
  743. */
  744. createAccessors: function(klass) {
  745. var proto = klass.prototype;
  746.  
  747. for (var i = proto.stateProperties.length; i--; ) {
  748.  
  749. var propName = proto.stateProperties[i],
  750. capitalizedPropName = propName.charAt(0).toUpperCase() + propName.slice(1),
  751. setterName = 'set' + capitalizedPropName,
  752. getterName = 'get' + capitalizedPropName;
  753.  
  754. // using `new Function` for better introspection
  755. if (!proto[getterName]) {
  756. proto[getterName] = (function(property) {
  757. return new Function('return this.get("' + property + '")');
  758. })(propName);
  759. }
  760. if (!proto[setterName]) {
  761. proto[setterName] = (function(property) {
  762. return new Function('value', 'return this.set("' + property + '", value)');
  763. })(propName);
  764. }
  765. }
  766. },
  767.  
  768. /**
  769. * @static
  770. * @memberOf fabric.util
  771. * @param {fabric.Object} receiver Object implementing `clipTo` method
  772. * @param {CanvasRenderingContext2D} ctx Context to clip
  773. */
  774. clipContext: function(receiver, ctx) {
  775. ctx.save();
  776. ctx.beginPath();
  777. receiver.clipTo(ctx);
  778. ctx.clip();
  779. },
  780.  
  781. /**
  782. * Multiply matrix A by matrix B to nest transformations
  783. * @static
  784. * @memberOf fabric.util
  785. * @param {Array} matrixA First transformMatrix
  786. * @param {Array} matrixB Second transformMatrix
  787. * @return {Array} The product of the two transform matrices
  788. */
  789. multiplyTransformMatrices: function(matrixA, matrixB) {
  790. // Matrix multiply matrixA * matrixB
  791. var a = [
  792. [matrixA[0], matrixA[2], matrixA[4]],
  793. [matrixA[1], matrixA[3], matrixA[5]],
  794. [0, 0, 1 ]
  795. ],
  796.  
  797. b = [
  798. [matrixB[0], matrixB[2], matrixB[4]],
  799. [matrixB[1], matrixB[3], matrixB[5]],
  800. [0, 0, 1 ]
  801. ],
  802.  
  803. result = [];
  804.  
  805. for (var r = 0; r < 3; r++) {
  806. result[r] = [];
  807. for (var c = 0; c < 3; c++) {
  808. var sum = 0;
  809. for (var k = 0; k < 3; k++) {
  810. sum += a[r][k] * b[k][c];
  811. }
  812.  
  813. result[r][c] = sum;
  814. }
  815. }
  816.  
  817. return [
  818. result[0][0],
  819. result[1][0],
  820. result[0][1],
  821. result[1][1],
  822. result[0][2],
  823. result[1][2]
  824. ];
  825. },
  826.  
  827. /**
  828. * Returns string representation of function body
  829. * @param {Function} fn Function to get body of
  830. * @return {String} Function body
  831. */
  832. getFunctionBody: function(fn) {
  833. return (String(fn).match(/function[^{]*\{([\s\S]*)\}/) || {})[1];
  834. },
  835.  
  836. /**
  837. * Returns true if context has transparent pixel
  838. * at specified location (taking tolerance into account)
  839. * @param {CanvasRenderingContext2D} ctx context
  840. * @param {Number} x x coordinate
  841. * @param {Number} y y coordinate
  842. * @param {Number} tolerance Tolerance
  843. */
  844. isTransparent: function(ctx, x, y, tolerance) {
  845.  
  846. // If tolerance is > 0 adjust start coords to take into account.
  847. // If moves off Canvas fix to 0
  848. if (tolerance > 0) {
  849. if (x > tolerance) {
  850. x -= tolerance;
  851. }
  852. else {
  853. x = 0;
  854. }
  855. if (y > tolerance) {
  856. y -= tolerance;
  857. }
  858. else {
  859. y = 0;
  860. }
  861. }
  862.  
  863. var _isTransparent = true,
  864. imageData = ctx.getImageData(x, y, (tolerance * 2) || 1, (tolerance * 2) || 1);
  865.  
  866. // Split image data - for tolerance > 1, pixelDataSize = 4;
  867. for (var i = 3, l = imageData.data.length; i < l; i += 4) {
  868. var temp = imageData.data[i];
  869. _isTransparent = temp <= 0;
  870. if (_isTransparent === false) {
  871. break; // Stop if colour found
  872. }
  873. }
  874.  
  875. imageData = null;
  876.  
  877. return _isTransparent;
  878. }
  879. };
  880.  
  881. })(typeof exports !== 'undefined' ? exports : this);
  882.  
  883.  
  884. (function() {
  885.  
  886. var arcToSegmentsCache = { },
  887. segmentToBezierCache = { },
  888. boundsOfCurveCache = { },
  889. _join = Array.prototype.join;
  890.  
  891. /* Adapted from http://dxr.mozilla.org/mozilla-central/source/content/svg/content/src/nsSVGPathDataParser.cpp
  892. * by Andrea Bogazzi code is under MPL. if you don't have a copy of the license you can take it here
  893. * http://mozilla.org/MPL/2.0/
  894. */
  895. function arcToSegments(toX, toY, rx, ry, large, sweep, rotateX) {
  896. var argsString = _join.call(arguments);
  897. if (arcToSegmentsCache[argsString]) {
  898. return arcToSegmentsCache[argsString];
  899. }
  900.  
  901. var PI = Math.PI, th = rotateX * PI / 180,
  902. sinTh = Math.sin(th),
  903. cosTh = Math.cos(th),
  904. fromX = 0, fromY = 0;
  905.  
  906. rx = Math.abs(rx);
  907. ry = Math.abs(ry);
  908.  
  909. var px = -cosTh * toX * 0.5 - sinTh * toY * 0.5,
  910. py = -cosTh * toY * 0.5 + sinTh * toX * 0.5,
  911. rx2 = rx * rx, ry2 = ry * ry, py2 = py * py, px2 = px * px,
  912. pl = rx2 * ry2 - rx2 * py2 - ry2 * px2,
  913. root = 0;
  914.  
  915. if (pl < 0) {
  916. var s = Math.sqrt(1 - pl/(rx2 * ry2));
  917. rx *= s;
  918. ry *= s;
  919. }
  920. else {
  921. root = (large === sweep ? -1.0 : 1.0) *
  922. Math.sqrt( pl /(rx2 * py2 + ry2 * px2));
  923. }
  924.  
  925. var cx = root * rx * py / ry,
  926. cy = -root * ry * px / rx,
  927. cx1 = cosTh * cx - sinTh * cy + toX * 0.5,
  928. cy1 = sinTh * cx + cosTh * cy + toY * 0.5,
  929. mTheta = calcVectorAngle(1, 0, (px - cx) / rx, (py - cy) / ry),
  930. dtheta = calcVectorAngle((px - cx) / rx, (py - cy) / ry, (-px - cx) / rx, (-py - cy) / ry);
  931.  
  932. if (sweep === 0 && dtheta > 0) {
  933. dtheta -= 2 * PI;
  934. }
  935. else if (sweep === 1 && dtheta < 0) {
  936. dtheta += 2 * PI;
  937. }
  938.  
  939. // Convert into cubic bezier segments <= 90deg
  940. var segments = Math.ceil(Math.abs(dtheta / PI * 2)),
  941. result = [], mDelta = dtheta / segments,
  942. mT = 8 / 3 * Math.sin(mDelta / 4) * Math.sin(mDelta / 4) / Math.sin(mDelta / 2),
  943. th3 = mTheta + mDelta;
  944.  
  945. for (var i = 0; i < segments; i++) {
  946. result[i] = segmentToBezier(mTheta, th3, cosTh, sinTh, rx, ry, cx1, cy1, mT, fromX, fromY);
  947. fromX = result[i][4];
  948. fromY = result[i][5];
  949. mTheta = th3;
  950. th3 += mDelta;
  951. }
  952. arcToSegmentsCache[argsString] = result;
  953. return result;
  954. }
  955.  
  956. function segmentToBezier(th2, th3, cosTh, sinTh, rx, ry, cx1, cy1, mT, fromX, fromY) {
  957. var argsString2 = _join.call(arguments);
  958. if (segmentToBezierCache[argsString2]) {
  959. return segmentToBezierCache[argsString2];
  960. }
  961.  
  962. var costh2 = Math.cos(th2),
  963. sinth2 = Math.sin(th2),
  964. costh3 = Math.cos(th3),
  965. sinth3 = Math.sin(th3),
  966. toX = cosTh * rx * costh3 - sinTh * ry * sinth3 + cx1,
  967. toY = sinTh * rx * costh3 + cosTh * ry * sinth3 + cy1,
  968. cp1X = fromX + mT * ( - cosTh * rx * sinth2 - sinTh * ry * costh2),
  969. cp1Y = fromY + mT * ( - sinTh * rx * sinth2 + cosTh * ry * costh2),
  970. cp2X = toX + mT * ( cosTh * rx * sinth3 + sinTh * ry * costh3),
  971. cp2Y = toY + mT * ( sinTh * rx * sinth3 - cosTh * ry * costh3);
  972.  
  973. segmentToBezierCache[argsString2] = [
  974. cp1X, cp1Y,
  975. cp2X, cp2Y,
  976. toX, toY
  977. ];
  978. return segmentToBezierCache[argsString2];
  979. }
  980.  
  981. /*
  982. * Private
  983. */
  984. function calcVectorAngle(ux, uy, vx, vy) {
  985. var ta = Math.atan2(uy, ux),
  986. tb = Math.atan2(vy, vx);
  987. if (tb >= ta) {
  988. return tb - ta;
  989. }
  990. else {
  991. return 2 * Math.PI - (ta - tb);
  992. }
  993. }
  994.  
  995. /**
  996. * Draws arc
  997. * @param {CanvasRenderingContext2D} ctx
  998. * @param {Number} fx
  999. * @param {Number} fy
  1000. * @param {Array} coords
  1001. */
  1002. fabric.util.drawArc = function(ctx, fx, fy, coords) {
  1003. var rx = coords[0],
  1004. ry = coords[1],
  1005. rot = coords[2],
  1006. large = coords[3],
  1007. sweep = coords[4],
  1008. tx = coords[5],
  1009. ty = coords[6],
  1010. segs = [[ ], [ ], [ ], [ ]],
  1011. segsNorm = arcToSegments(tx - fx, ty - fy, rx, ry, large, sweep, rot);
  1012.  
  1013. for (var i = 0, len = segsNorm.length; i < len; i++) {
  1014. segs[i][0] = segsNorm[i][0] + fx;
  1015. segs[i][1] = segsNorm[i][1] + fy;
  1016. segs[i][2] = segsNorm[i][2] + fx;
  1017. segs[i][3] = segsNorm[i][3] + fy;
  1018. segs[i][4] = segsNorm[i][4] + fx;
  1019. segs[i][5] = segsNorm[i][5] + fy;
  1020. ctx.bezierCurveTo.apply(ctx, segs[i]);
  1021. }
  1022. };
  1023.  
  1024. /**
  1025. * Calculate bounding box of a elliptic-arc
  1026. * @param {Number} fx start point of arc
  1027. * @param {Number} fy
  1028. * @param {Number} rx horizontal radius
  1029. * @param {Number} ry vertical radius
  1030. * @param {Number} rot angle of horizontal axe
  1031. * @param {Number} large 1 or 0, whatever the arc is the big or the small on the 2 points
  1032. * @param {Number} sweep 1 or 0, 1 clockwise or counterclockwise direction
  1033. * @param {Number} tx end point of arc
  1034. * @param {Number} ty
  1035. */
  1036. fabric.util.getBoundsOfArc = function(fx, fy, rx, ry, rot, large, sweep, tx, ty) {
  1037.  
  1038. var fromX = 0, fromY = 0, bound = [ ], bounds = [ ],
  1039. segs = arcToSegments(tx - fx, ty - fy, rx, ry, large, sweep, rot);
  1040.  
  1041. for (var i = 0, len = segs.length; i < len; i++) {
  1042. bound = getBoundsOfCurve(fromX, fromY, segs[i][0], segs[i][1], segs[i][2], segs[i][3], segs[i][4], segs[i][5]);
  1043. bound[0].x += fx;
  1044. bound[0].y += fy;
  1045. bound[1].x += fx;
  1046. bound[1].y += fy;
  1047. bounds.push(bound[0]);
  1048. bounds.push(bound[1]);
  1049. fromX = segs[i][4];
  1050. fromY = segs[i][5];
  1051. }
  1052. return bounds;
  1053. };
  1054.  
  1055. /**
  1056. * Calculate bounding box of a beziercurve
  1057. * @param {Number} x0 starting point
  1058. * @param {Number} y0
  1059. * @param {Number} x1 first control point
  1060. * @param {Number} y1
  1061. * @param {Number} x2 secondo control point
  1062. * @param {Number} y2
  1063. * @param {Number} x3 end of beizer
  1064. * @param {Number} y3
  1065. */
  1066. // taken from http://jsbin.com/ivomiq/56/edit no credits available for that.
  1067. function getBoundsOfCurve(x0, y0, x1, y1, x2, y2, x3, y3) {
  1068. var argsString = _join.call(arguments);
  1069. if (boundsOfCurveCache[argsString]) {
  1070. return boundsOfCurveCache[argsString];
  1071. }
  1072.  
  1073. var sqrt = Math.sqrt,
  1074. min = Math.min, max = Math.max,
  1075. abs = Math.abs, tvalues = [ ],
  1076. bounds = [[ ], [ ]],
  1077. a, b, c, t, t1, t2, b2ac, sqrtb2ac;
  1078.  
  1079. b = 6 * x0 - 12 * x1 + 6 * x2;
  1080. a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3;
  1081. c = 3 * x1 - 3 * x0;
  1082.  
  1083. for (var i = 0; i < 2; ++i) {
  1084. if (i > 0) {
  1085. b = 6 * y0 - 12 * y1 + 6 * y2;
  1086. a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3;
  1087. c = 3 * y1 - 3 * y0;
  1088. }
  1089.  
  1090. if (abs(a) < 1e-12) {
  1091. if (abs(b) < 1e-12) {
  1092. continue;
  1093. }
  1094. t = -c / b;
  1095. if (0 < t && t < 1) {
  1096. tvalues.push(t);
  1097. }
  1098. continue;
  1099. }
  1100. b2ac = b * b - 4 * c * a;
  1101. if (b2ac < 0) {
  1102. continue;
  1103. }
  1104. sqrtb2ac = sqrt(b2ac);
  1105. t1 = (-b + sqrtb2ac) / (2 * a);
  1106. if (0 < t1 && t1 < 1) {
  1107. tvalues.push(t1);
  1108. }
  1109. t2 = (-b - sqrtb2ac) / (2 * a);
  1110. if (0 < t2 && t2 < 1) {
  1111. tvalues.push(t2);
  1112. }
  1113. }
  1114.  
  1115. var x, y, j = tvalues.length, jlen = j, mt;
  1116. while (j--) {
  1117. t = tvalues[j];
  1118. mt = 1 - t;
  1119. x = (mt * mt * mt * x0) + (3 * mt * mt * t * x1) + (3 * mt * t * t * x2) + (t * t * t * x3);
  1120. bounds[0][j] = x;
  1121.  
  1122. y = (mt * mt * mt * y0) + (3 * mt * mt * t * y1) + (3 * mt * t * t * y2) + (t * t * t * y3);
  1123. bounds[1][j] = y;
  1124. }
  1125.  
  1126. bounds[0][jlen] = x0;
  1127. bounds[1][jlen] = y0;
  1128. bounds[0][jlen + 1] = x3;
  1129. bounds[1][jlen + 1] = y3;
  1130. var result = [
  1131. {
  1132. x: min.apply(null, bounds[0]),
  1133. y: min.apply(null, bounds[1])
  1134. },
  1135. {
  1136. x: max.apply(null, bounds[0]),
  1137. y: max.apply(null, bounds[1])
  1138. }
  1139. ];
  1140. boundsOfCurveCache[argsString] = result;
  1141. return result;
  1142. }
  1143.  
  1144. fabric.util.getBoundsOfCurve = getBoundsOfCurve;
  1145.  
  1146. })();
  1147.  
  1148.  
  1149. (function() {
  1150.  
  1151. var slice = Array.prototype.slice;
  1152.  
  1153. /* _ES5_COMPAT_START_ */
  1154.  
  1155. if (!Array.prototype.indexOf) {
  1156. /**
  1157. * Finds index of an element in an array
  1158. * @param {Any} searchElement
  1159. * @param {Number} [fromIndex]
  1160. * @return {Number}
  1161. */
  1162. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  1163. if (this === void 0 || this === null) {
  1164. throw new TypeError();
  1165. }
  1166. var t = Object(this), len = t.length >>> 0;
  1167. if (len === 0) {
  1168. return -1;
  1169. }
  1170. var n = 0;
  1171. if (arguments.length > 0) {
  1172. n = Number(arguments[1]);
  1173. if (n !== n) { // shortcut for verifying if it's NaN
  1174. n = 0;
  1175. }
  1176. else if (n !== 0 && n !== Number.POSITIVE_INFINITY && n !== Number.NEGATIVE_INFINITY) {
  1177. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  1178. }
  1179. }
  1180. if (n >= len) {
  1181. return -1;
  1182. }
  1183. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  1184. for (; k < len; k++) {
  1185. if (k in t && t[k] === searchElement) {
  1186. return k;
  1187. }
  1188. }
  1189. return -1;
  1190. };
  1191. }
  1192.  
  1193. if (!Array.prototype.forEach) {
  1194. /**
  1195. * Iterates an array, invoking callback for each element
  1196. * @param {Function} fn Callback to invoke for each element
  1197. * @param {Object} [context] Context to invoke callback in
  1198. * @return {Array}
  1199. */
  1200. Array.prototype.forEach = function(fn, context) {
  1201. for (var i = 0, len = this.length >>> 0; i < len; i++) {
  1202. if (i in this) {
  1203. fn.call(context, this[i], i, this);
  1204. }
  1205. }
  1206. };
  1207. }
  1208.  
  1209. if (!Array.prototype.map) {
  1210. /**
  1211. * Returns a result of iterating over an array, invoking callback for each element
  1212. * @param {Function} fn Callback to invoke for each element
  1213. * @param {Object} [context] Context to invoke callback in
  1214. * @return {Array}
  1215. */
  1216. Array.prototype.map = function(fn, context) {
  1217. var result = [ ];
  1218. for (var i = 0, len = this.length >>> 0; i < len; i++) {
  1219. if (i in this) {
  1220. result[i] = fn.call(context, this[i], i, this);
  1221. }
  1222. }
  1223. return result;
  1224. };
  1225. }
  1226.  
  1227. if (!Array.prototype.every) {
  1228. /**
  1229. * Returns true if a callback returns truthy value for all elements in an array
  1230. * @param {Function} fn Callback to invoke for each element
  1231. * @param {Object} [context] Context to invoke callback in
  1232. * @return {Boolean}
  1233. */
  1234. Array.prototype.every = function(fn, context) {
  1235. for (var i = 0, len = this.length >>> 0; i < len; i++) {
  1236. if (i in this && !fn.call(context, this[i], i, this)) {
  1237. return false;
  1238. }
  1239. }
  1240. return true;
  1241. };
  1242. }
  1243.  
  1244. if (!Array.prototype.some) {
  1245. /**
  1246. * Returns true if a callback returns truthy value for at least one element in an array
  1247. * @param {Function} fn Callback to invoke for each element
  1248. * @param {Object} [context] Context to invoke callback in
  1249. * @return {Boolean}
  1250. */
  1251. Array.prototype.some = function(fn, context) {
  1252. for (var i = 0, len = this.length >>> 0; i < len; i++) {
  1253. if (i in this && fn.call(context, this[i], i, this)) {
  1254. return true;
  1255. }
  1256. }
  1257. return false;
  1258. };
  1259. }
  1260.  
  1261. if (!Array.prototype.filter) {
  1262. /**
  1263. * Returns the result of iterating over elements in an array
  1264. * @param {Function} fn Callback to invoke for each element
  1265. * @param {Object} [context] Context to invoke callback in
  1266. * @return {Array}
  1267. */
  1268. Array.prototype.filter = function(fn, context) {
  1269. var result = [ ], val;
  1270. for (var i = 0, len = this.length >>> 0; i < len; i++) {
  1271. if (i in this) {
  1272. val = this[i]; // in case fn mutates this
  1273. if (fn.call(context, val, i, this)) {
  1274. result.push(val);
  1275. }
  1276. }
  1277. }
  1278. return result;
  1279. };
  1280. }
  1281.  
  1282. if (!Array.prototype.reduce) {
  1283. /**
  1284. * Returns "folded" (reduced) result of iterating over elements in an array
  1285. * @param {Function} fn Callback to invoke for each element
  1286. * @param {Object} [initial] Object to use as the first argument to the first call of the callback
  1287. * @return {Any}
  1288. */
  1289. Array.prototype.reduce = function(fn /*, initial*/) {
  1290. var len = this.length >>> 0,
  1291. i = 0,
  1292. rv;
  1293.  
  1294. if (arguments.length > 1) {
  1295. rv = arguments[1];
  1296. }
  1297. else {
  1298. do {
  1299. if (i in this) {
  1300. rv = this[i++];
  1301. break;
  1302. }
  1303. // if array contains no values, no initial value to return
  1304. if (++i >= len) {
  1305. throw new TypeError();
  1306. }
  1307. }
  1308. while (true);
  1309. }
  1310. for (; i < len; i++) {
  1311. if (i in this) {
  1312. rv = fn.call(null, rv, this[i], i, this);
  1313. }
  1314. }
  1315. return rv;
  1316. };
  1317. }
  1318.  
  1319. /* _ES5_COMPAT_END_ */
  1320.  
  1321. /**
  1322. * Invokes method on all items in a given array
  1323. * @memberOf fabric.util.array
  1324. * @param {Array} array Array to iterate over
  1325. * @param {String} method Name of a method to invoke
  1326. * @return {Array}
  1327. */
  1328. function invoke(array, method) {
  1329. var args = slice.call(arguments, 2), result = [ ];
  1330. for (var i = 0, len = array.length; i < len; i++) {
  1331. result[i] = args.length ? array[i][method].apply(array[i], args) : array[i][method].call(array[i]);
  1332. }
  1333. return result;
  1334. }
  1335.  
  1336. /**
  1337. * Finds maximum value in array (not necessarily "first" one)
  1338. * @memberOf fabric.util.array
  1339. * @param {Array} array Array to iterate over
  1340. * @param {String} byProperty
  1341. * @return {Any}
  1342. */
  1343. function max(array, byProperty) {
  1344. return find(array, byProperty, function(value1, value2) {
  1345. return value1 >= value2;
  1346. });
  1347. }
  1348.  
  1349. /**
  1350. * Finds minimum value in array (not necessarily "first" one)
  1351. * @memberOf fabric.util.array
  1352. * @param {Array} array Array to iterate over
  1353. * @param {String} byProperty
  1354. * @return {Any}
  1355. */
  1356. function min(array, byProperty) {
  1357. return find(array, byProperty, function(value1, value2) {
  1358. return value1 < value2;
  1359. });
  1360. }
  1361.  
  1362. /**
  1363. * @private
  1364. */
  1365. function find(array, byProperty, condition) {
  1366. if (!array || array.length === 0) {
  1367. return;
  1368. }
  1369.  
  1370. var i = array.length - 1,
  1371. result = byProperty ? array[i][byProperty] : array[i];
  1372. if (byProperty) {
  1373. while (i--) {
  1374. if (condition(array[i][byProperty], result)) {
  1375. result = array[i][byProperty];
  1376. }
  1377. }
  1378. }
  1379. else {
  1380. while (i--) {
  1381. if (condition(array[i], result)) {
  1382. result = array[i];
  1383. }
  1384. }
  1385. }
  1386. return result;
  1387. }
  1388.  
  1389. /**
  1390. * @namespace fabric.util.array
  1391. */
  1392. fabric.util.array = {
  1393. invoke: invoke,
  1394. min: min,
  1395. max: max
  1396. };
  1397.  
  1398. })();
  1399.  
  1400.  
  1401. (function() {
  1402.  
  1403. /**
  1404. * Copies all enumerable properties of one object to another
  1405. * @memberOf fabric.util.object
  1406. * @param {Object} destination Where to copy to
  1407. * @param {Object} source Where to copy from
  1408. * @return {Object}
  1409. */
  1410. function extend(destination, source) {
  1411. // JScript DontEnum bug is not taken care of
  1412. for (var property in source) {
  1413. destination[property] = source[property];
  1414. }
  1415. return destination;
  1416. }
  1417.  
  1418. /**
  1419. * Creates an empty object and copies all enumerable properties of another object to it
  1420. * @memberOf fabric.util.object
  1421. * @param {Object} object Object to clone
  1422. * @return {Object}
  1423. */
  1424. function clone(object) {
  1425. return extend({ }, object);
  1426. }
  1427.  
  1428. /** @namespace fabric.util.object */
  1429. fabric.util.object = {
  1430. extend: extend,
  1431. clone: clone
  1432. };
  1433.  
  1434. })();
  1435.  
  1436.  
  1437. (function() {
  1438.  
  1439. /* _ES5_COMPAT_START_ */
  1440. if (!String.prototype.trim) {
  1441. /**
  1442. * Trims a string (removing whitespace from the beginning and the end)
  1443. * @function external:String#trim
  1444. * @see <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/Trim">String#trim on MDN</a>
  1445. */
  1446. String.prototype.trim = function () {
  1447. // this trim is not fully ES3 or ES5 compliant, but it should cover most cases for now
  1448. return this.replace(/^[\s\xA0]+/, '').replace(/[\s\xA0]+$/, '');
  1449. };
  1450. }
  1451. /* _ES5_COMPAT_END_ */
  1452.  
  1453. /**
  1454. * Camelizes a string
  1455. * @memberOf fabric.util.string
  1456. * @param {String} string String to camelize
  1457. * @return {String} Camelized version of a string
  1458. */
  1459. function camelize(string) {
  1460. return string.replace(/-+(.)?/g, function(match, character) {
  1461. return character ? character.toUpperCase() : '';
  1462. });
  1463. }
  1464.  
  1465. /**
  1466. * Capitalizes a string
  1467. * @memberOf fabric.util.string
  1468. * @param {String} string String to capitalize
  1469. * @param {Boolean} [firstLetterOnly] If true only first letter is capitalized
  1470. * and other letters stay untouched, if false first letter is capitalized
  1471. * and other letters are converted to lowercase.
  1472. * @return {String} Capitalized version of a string
  1473. */
  1474. function capitalize(string, firstLetterOnly) {
  1475. return string.charAt(0).toUpperCase() +
  1476. (firstLetterOnly ? string.slice(1) : string.slice(1).toLowerCase());
  1477. }
  1478.  
  1479. /**
  1480. * Escapes XML in a string
  1481. * @memberOf fabric.util.string
  1482. * @param {String} string String to escape
  1483. * @return {String} Escaped version of a string
  1484. */
  1485. function escapeXml(string) {
  1486. return string.replace(/&/g, '&amp;')
  1487. .replace(/"/g, '&quot;')
  1488. .replace(/'/g, '&apos;')
  1489. .replace(/</g, '&lt;')
  1490. .replace(/>/g, '&gt;');
  1491. }
  1492.  
  1493. /**
  1494. * String utilities
  1495. * @namespace fabric.util.string
  1496. */
  1497. fabric.util.string = {
  1498. camelize: camelize,
  1499. capitalize: capitalize,
  1500. escapeXml: escapeXml
  1501. };
  1502. }());
  1503.  
  1504.  
  1505. /* _ES5_COMPAT_START_ */
  1506. (function() {
  1507.  
  1508. var slice = Array.prototype.slice,
  1509. apply = Function.prototype.apply,
  1510. Dummy = function() { };
  1511.  
  1512. if (!Function.prototype.bind) {
  1513. /**
  1514. * Cross-browser approximation of ES5 Function.prototype.bind (not fully spec conforming)
  1515. * @see <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind">Function#bind on MDN</a>
  1516. * @param {Object} thisArg Object to bind function to
  1517. * @param {Any[]} [...] Values to pass to a bound function
  1518. * @return {Function}
  1519. */
  1520. Function.prototype.bind = function(thisArg) {
  1521. var _this = this, args = slice.call(arguments, 1), bound;
  1522. if (args.length) {
  1523. bound = function() {
  1524. return apply.call(_this, this instanceof Dummy ? this : thisArg, args.concat(slice.call(arguments)));
  1525. };
  1526. }
  1527. else {
  1528. /** @ignore */
  1529. bound = function() {
  1530. return apply.call(_this, this instanceof Dummy ? this : thisArg, arguments);
  1531. };
  1532. }
  1533. Dummy.prototype = this.prototype;
  1534. bound.prototype = new Dummy();
  1535.  
  1536. return bound;
  1537. };
  1538. }
  1539.  
  1540. })();
  1541. /* _ES5_COMPAT_END_ */
  1542.  
  1543.  
  1544. (function() {
  1545.  
  1546. var slice = Array.prototype.slice, emptyFunction = function() { },
  1547.  
  1548. IS_DONTENUM_BUGGY = (function() {
  1549. for (var p in { toString: 1 }) {
  1550. if (p === 'toString') {
  1551. return false;
  1552. }
  1553. }
  1554. return true;
  1555. })(),
  1556.  
  1557. /** @ignore */
  1558. addMethods = function(klass, source, parent) {
  1559. for (var property in source) {
  1560.  
  1561. if (property in klass.prototype &&
  1562. typeof klass.prototype[property] === 'function' &&
  1563. (source[property] + '').indexOf('callSuper') > -1) {
  1564.  
  1565. klass.prototype[property] = (function(property) {
  1566. return function() {
  1567.  
  1568. var superclass = this.constructor.superclass;
  1569. this.constructor.superclass = parent;
  1570. var returnValue = source[property].apply(this, arguments);
  1571. this.constructor.superclass = superclass;
  1572.  
  1573. if (property !== 'initialize') {
  1574. return returnValue;
  1575. }
  1576. };
  1577. })(property);
  1578. }
  1579. else {
  1580. klass.prototype[property] = source[property];
  1581. }
  1582.  
  1583. if (IS_DONTENUM_BUGGY) {
  1584. if (source.toString !== Object.prototype.toString) {
  1585. klass.prototype.toString = source.toString;
  1586. }
  1587. if (source.valueOf !== Object.prototype.valueOf) {
  1588. klass.prototype.valueOf = source.valueOf;
  1589. }
  1590. }
  1591. }
  1592. };
  1593.  
  1594. function Subclass() { }
  1595.  
  1596. function callSuper(methodName) {
  1597. var fn = this.constructor.superclass.prototype[methodName];
  1598. return (arguments.length > 1)
  1599. ? fn.apply(this, slice.call(arguments, 1))
  1600. : fn.call(this);
  1601. }
  1602.  
  1603. /**
  1604. * Helper for creation of "classes".
  1605. * @memberOf fabric.util
  1606. * @param {Function} [parent] optional "Class" to inherit from
  1607. * @param {Object} [properties] Properties shared by all instances of this class
  1608. * (be careful modifying objects defined here as this would affect all instances)
  1609. */
  1610. function createClass() {
  1611. var parent = null,
  1612. properties = slice.call(arguments, 0);
  1613.  
  1614. if (typeof properties[0] === 'function') {
  1615. parent = properties.shift();
  1616. }
  1617. function klass() {
  1618. this.initialize.apply(this, arguments);
  1619. }
  1620.  
  1621. klass.superclass = parent;
  1622. klass.subclasses = [ ];
  1623.  
  1624. if (parent) {
  1625. Subclass.prototype = parent.prototype;
  1626. klass.prototype = new Subclass();
  1627. parent.subclasses.push(klass);
  1628. }
  1629. for (var i = 0, length = properties.length; i < length; i++) {
  1630. addMethods(klass, properties[i], parent);
  1631. }
  1632. if (!klass.prototype.initialize) {
  1633. klass.prototype.initialize = emptyFunction;
  1634. }
  1635. klass.prototype.constructor = klass;
  1636. klass.prototype.callSuper = callSuper;
  1637. return klass;
  1638. }
  1639.  
  1640. fabric.util.createClass = createClass;
  1641. })();
  1642.  
  1643.  
  1644. (function () {
  1645.  
  1646. var unknown = 'unknown';
  1647.  
  1648. /* EVENT HANDLING */
  1649.  
  1650. function areHostMethods(object) {
  1651. var methodNames = Array.prototype.slice.call(arguments, 1),
  1652. t, i, len = methodNames.length;
  1653. for (i = 0; i < len; i++) {
  1654. t = typeof object[methodNames[i]];
  1655. if (!(/^(?:function|object|unknown)$/).test(t)) {
  1656. return false;
  1657. }
  1658. }
  1659. return true;
  1660. }
  1661.  
  1662. /** @ignore */
  1663. var getElement,
  1664. setElement,
  1665. getUniqueId = (function () {
  1666. var uid = 0;
  1667. return function (element) {
  1668. return element.__uniqueID || (element.__uniqueID = 'uniqueID__' + uid++);
  1669. };
  1670. })();
  1671.  
  1672. (function () {
  1673. var elements = { };
  1674. /** @ignore */
  1675. getElement = function (uid) {
  1676. return elements[uid];
  1677. };
  1678. /** @ignore */
  1679. setElement = function (uid, element) {
  1680. elements[uid] = element;
  1681. };
  1682. })();
  1683.  
  1684. function createListener(uid, handler) {
  1685. return {
  1686. handler: handler,
  1687. wrappedHandler: createWrappedHandler(uid, handler)
  1688. };
  1689. }
  1690.  
  1691. function createWrappedHandler(uid, handler) {
  1692. return function (e) {
  1693. handler.call(getElement(uid), e || fabric.window.event);
  1694. };
  1695. }
  1696.  
  1697. function createDispatcher(uid, eventName) {
  1698. return function (e) {
  1699. if (handlers[uid] && handlers[uid][eventName]) {
  1700. var handlersForEvent = handlers[uid][eventName];
  1701. for (var i = 0, len = handlersForEvent.length; i < len; i++) {
  1702. handlersForEvent[i].call(this, e || fabric.window.event);
  1703. }
  1704. }
  1705. };
  1706. }
  1707.  
  1708. var shouldUseAddListenerRemoveListener = (
  1709. areHostMethods(fabric.document.documentElement, 'addEventListener', 'removeEventListener') &&
  1710. areHostMethods(fabric.window, 'addEventListener', 'removeEventListener')),
  1711.  
  1712. shouldUseAttachEventDetachEvent = (
  1713. areHostMethods(fabric.document.documentElement, 'attachEvent', 'detachEvent') &&
  1714. areHostMethods(fabric.window, 'attachEvent', 'detachEvent')),
  1715.  
  1716. // IE branch
  1717. listeners = { },
  1718.  
  1719. // DOM L0 branch
  1720. handlers = { },
  1721.  
  1722. addListener, removeListener;
  1723.  
  1724. if (shouldUseAddListenerRemoveListener) {
  1725. /** @ignore */
  1726. addListener = function (element, eventName, handler) {
  1727. element.addEventListener(eventName, handler, false);
  1728. };
  1729. /** @ignore */
  1730. removeListener = function (element, eventName, handler) {
  1731. element.removeEventListener(eventName, handler, false);
  1732. };
  1733. }
  1734.  
  1735. else if (shouldUseAttachEventDetachEvent) {
  1736. /** @ignore */
  1737. addListener = function (element, eventName, handler) {
  1738. var uid = getUniqueId(element);
  1739. setElement(uid, element);
  1740. if (!listeners[uid]) {
  1741. listeners[uid] = { };
  1742. }
  1743. if (!listeners[uid][eventName]) {
  1744. listeners[uid][eventName] = [ ];
  1745.  
  1746. }
  1747. var listener = createListener(uid, handler);
  1748. listeners[uid][eventName].push(listener);
  1749. element.attachEvent('on' + eventName, listener.wrappedHandler);
  1750. };
  1751. /** @ignore */
  1752. removeListener = function (element, eventName, handler) {
  1753. var uid = getUniqueId(element), listener;
  1754. if (listeners[uid] && listeners[uid][eventName]) {
  1755. for (var i = 0, len = listeners[uid][eventName].length; i < len; i++) {
  1756. listener = listeners[uid][eventName][i];
  1757. if (listener && listener.handler === handler) {
  1758. element.detachEvent('on' + eventName, listener.wrappedHandler);
  1759. listeners[uid][eventName][i] = null;
  1760. }
  1761. }
  1762. }
  1763. };
  1764. }
  1765. else {
  1766. /** @ignore */
  1767. addListener = function (element, eventName, handler) {
  1768. var uid = getUniqueId(element);
  1769. if (!handlers[uid]) {
  1770. handlers[uid] = { };
  1771. }
  1772. if (!handlers[uid][eventName]) {
  1773. handlers[uid][eventName] = [ ];
  1774. var existingHandler = element['on' + eventName];
  1775. if (existingHandler) {
  1776. handlers[uid][eventName].push(existingHandler);
  1777. }
  1778. element['on' + eventName] = createDispatcher(uid, eventName);
  1779. }
  1780. handlers[uid][eventName].push(handler);
  1781. };
  1782. /** @ignore */
  1783. removeListener = function (element, eventName, handler) {
  1784. var uid = getUniqueId(element);
  1785. if (handlers[uid] && handlers[uid][eventName]) {
  1786. var handlersForEvent = handlers[uid][eventName];
  1787. for (var i = 0, len = handlersForEvent.length; i < len; i++) {
  1788. if (handlersForEvent[i] === handler) {
  1789. handlersForEvent.splice(i, 1);
  1790. }
  1791. }
  1792. }
  1793. };
  1794. }
  1795.  
  1796. /**
  1797. * Adds an event listener to an element
  1798. * @function
  1799. * @memberOf fabric.util
  1800. * @param {HTMLElement} element
  1801. * @param {String} eventName
  1802. * @param {Function} handler
  1803. */
  1804. fabric.util.addListener = addListener;
  1805.  
  1806. /**
  1807. * Removes an event listener from an element
  1808. * @function
  1809. * @memberOf fabric.util
  1810. * @param {HTMLElement} element
  1811. * @param {String} eventName
  1812. * @param {Function} handler
  1813. */
  1814. fabric.util.removeListener = removeListener;
  1815.  
  1816. /**
  1817. * Cross-browser wrapper for getting event's coordinates
  1818. * @memberOf fabric.util
  1819. * @param {Event} event Event object
  1820. * @param {HTMLCanvasElement} upperCanvasEl &lt;canvas> element on which object selection is drawn
  1821. */
  1822. function getPointer(event, upperCanvasEl) {
  1823. event || (event = fabric.window.event);
  1824.  
  1825. var element = event.target ||
  1826. (typeof event.srcElement !== unknown ? event.srcElement : null),
  1827.  
  1828. scroll = fabric.util.getScrollLeftTop(element, upperCanvasEl);
  1829.  
  1830. return {
  1831. x: pointerX(event) + scroll.left,
  1832. y: pointerY(event) + scroll.top
  1833. };
  1834. }
  1835.  
  1836. var pointerX = function(event) {
  1837. // looks like in IE (<9) clientX at certain point (apparently when mouseup fires on VML element)
  1838. // is represented as COM object, with all the consequences, like "unknown" type and error on [[Get]]
  1839. // need to investigate later
  1840. return (typeof event.clientX !== unknown ? event.clientX : 0);
  1841. },
  1842.  
  1843. pointerY = function(event) {
  1844. return (typeof event.clientY !== unknown ? event.clientY : 0);
  1845. };
  1846.  
  1847. function _getPointer(event, pageProp, clientProp) {
  1848. var touchProp = event.type === 'touchend' ? 'changedTouches' : 'touches';
  1849.  
  1850. return (event[touchProp] && event[touchProp][0]
  1851. ? (event[touchProp][0][pageProp] - (event[touchProp][0][pageProp] - event[touchProp][0][clientProp]))
  1852. || event[clientProp]
  1853. : event[clientProp]);
  1854. }
  1855.  
  1856. if (fabric.isTouchSupported) {
  1857. pointerX = function(event) {
  1858. return _getPointer(event, 'pageX', 'clientX');
  1859. };
  1860. pointerY = function(event) {
  1861. return _getPointer(event, 'pageY', 'clientY');
  1862. };
  1863. }
  1864.  
  1865. fabric.util.getPointer = getPointer;
  1866.  
  1867. fabric.util.object.extend(fabric.util, fabric.Observable);
  1868.  
  1869. })();
  1870.  
  1871.  
  1872. (function () {
  1873.  
  1874. /**
  1875. * Cross-browser wrapper for setting element's style
  1876. * @memberOf fabric.util
  1877. * @param {HTMLElement} element
  1878. * @param {Object} styles
  1879. * @return {HTMLElement} Element that was passed as a first argument
  1880. */
  1881. function setStyle(element, styles) {
  1882. var elementStyle = element.style;
  1883. if (!elementStyle) {
  1884. return element;
  1885. }
  1886. if (typeof styles === 'string') {
  1887. element.style.cssText += ';' + styles;
  1888. return styles.indexOf('opacity') > -1
  1889. ? setOpacity(element, styles.match(/opacity:\s*(\d?\.?\d*)/)[1])
  1890. : element;
  1891. }
  1892. for (var property in styles) {
  1893. if (property === 'opacity') {
  1894. setOpacity(element, styles[property]);
  1895. }
  1896. else {
  1897. var normalizedProperty = (property === 'float' || property === 'cssFloat')
  1898. ? (typeof elementStyle.styleFloat === 'undefined' ? 'cssFloat' : 'styleFloat')
  1899. : property;
  1900. elementStyle[normalizedProperty] = styles[property];
  1901. }
  1902. }
  1903. return element;
  1904. }
  1905.  
  1906. var parseEl = fabric.document.createElement('div'),
  1907. supportsOpacity = typeof parseEl.style.opacity === 'string',
  1908. supportsFilters = typeof parseEl.style.filter === 'string',
  1909. reOpacity = /alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,
  1910.  
  1911. /** @ignore */
  1912. setOpacity = function (element) { return element; };
  1913.  
  1914. if (supportsOpacity) {
  1915. /** @ignore */
  1916. setOpacity = function(element, value) {
  1917. element.style.opacity = value;
  1918. return element;
  1919. };
  1920. }
  1921. else if (supportsFilters) {
  1922. /** @ignore */
  1923. setOpacity = function(element, value) {
  1924. var es = element.style;
  1925. if (element.currentStyle && !element.currentStyle.hasLayout) {
  1926. es.zoom = 1;
  1927. }
  1928. if (reOpacity.test(es.filter)) {
  1929. value = value >= 0.9999 ? '' : ('alpha(opacity=' + (value * 100) + ')');
  1930. es.filter = es.filter.replace(reOpacity, value);
  1931. }
  1932. else {
  1933. es.filter += ' alpha(opacity=' + (value * 100) + ')';
  1934. }
  1935. return element;
  1936. };
  1937. }
  1938.  
  1939. fabric.util.setStyle = setStyle;
  1940.  
  1941. })();
  1942.  
  1943.  
  1944. (function() {
  1945.  
  1946. var _slice = Array.prototype.slice;
  1947.  
  1948. /**
  1949. * Takes id and returns an element with that id (if one exists in a document)
  1950. * @memberOf fabric.util
  1951. * @param {String|HTMLElement} id
  1952. * @return {HTMLElement|null}
  1953. */
  1954. function getById(id) {
  1955. return typeof id === 'string' ? fabric.document.getElementById(id) : id;
  1956. }
  1957.  
  1958. var sliceCanConvertNodelists,
  1959. /**
  1960. * Converts an array-like object (e.g. arguments or NodeList) to an array
  1961. * @memberOf fabric.util
  1962. * @param {Object} arrayLike
  1963. * @return {Array}
  1964. */
  1965. toArray = function(arrayLike) {
  1966. return _slice.call(arrayLike, 0);
  1967. };
  1968.  
  1969. try {
  1970. sliceCanConvertNodelists = toArray(fabric.document.childNodes) instanceof Array;
  1971. }
  1972. catch (err) { }
  1973.  
  1974. if (!sliceCanConvertNodelists) {
  1975. toArray = function(arrayLike) {
  1976. var arr = new Array(arrayLike.length), i = arrayLike.length;
  1977. while (i--) {
  1978. arr[i] = arrayLike[i];
  1979. }
  1980. return arr;
  1981. };
  1982. }
  1983.  
  1984. /**
  1985. * Creates specified element with specified attributes
  1986. * @memberOf fabric.util
  1987. * @param {String} tagName Type of an element to create
  1988. * @param {Object} [attributes] Attributes to set on an element
  1989. * @return {HTMLElement} Newly created element
  1990. */
  1991. function makeElement(tagName, attributes) {
  1992. var el = fabric.document.createElement(tagName);
  1993. for (var prop in attributes) {
  1994. if (prop === 'class') {
  1995. el.className = attributes[prop];
  1996. }
  1997. else if (prop === 'for') {
  1998. el.htmlFor = attributes[prop];
  1999. }
  2000. else {
  2001. el.setAttribute(prop, attributes[prop]);
  2002. }
  2003. }
  2004. return el;
  2005. }
  2006.  
  2007. /**
  2008. * Adds class to an element
  2009. * @memberOf fabric.util
  2010. * @param {HTMLElement} element Element to add class to
  2011. * @param {String} className Class to add to an element
  2012. */
  2013. function addClass(element, className) {
  2014. if (element && (' ' + element.className + ' ').indexOf(' ' + className + ' ') === -1) {
  2015. element.className += (element.className ? ' ' : '') + className;
  2016. }
  2017. }
  2018.  
  2019. /**
  2020. * Wraps element with another element
  2021. * @memberOf fabric.util
  2022. * @param {HTMLElement} element Element to wrap
  2023. * @param {HTMLElement|String} wrapper Element to wrap with
  2024. * @param {Object} [attributes] Attributes to set on a wrapper
  2025. * @return {HTMLElement} wrapper
  2026. */
  2027. function wrapElement(element, wrapper, attributes) {
  2028. if (typeof wrapper === 'string') {
  2029. wrapper = makeElement(wrapper, attributes);
  2030. }
  2031. if (element.parentNode) {
  2032. element.parentNode.replaceChild(wrapper, element);
  2033. }
  2034. wrapper.appendChild(element);
  2035. return wrapper;
  2036. }
  2037.  
  2038. /**
  2039. * Returns element scroll offsets
  2040. * @memberOf fabric.util
  2041. * @param {HTMLElement} element Element to operate on
  2042. * @param {HTMLElement} upperCanvasEl Upper canvas element
  2043. * @return {Object} Object with left/top values
  2044. */
  2045. function getScrollLeftTop(element, upperCanvasEl) {
  2046.  
  2047. var firstFixedAncestor,
  2048. origElement,
  2049. left = 0,
  2050. top = 0,
  2051. docElement = fabric.document.documentElement,
  2052. body = fabric.document.body || {
  2053. scrollLeft: 0, scrollTop: 0
  2054. };
  2055.  
  2056. origElement = element;
  2057.  
  2058. while (element && element.parentNode && !firstFixedAncestor) {
  2059.  
  2060. element = element.parentNode;
  2061.  
  2062. if (element.nodeType === 1 &&
  2063. fabric.util.getElementStyle(element, 'position') === 'fixed') {
  2064. firstFixedAncestor = element;
  2065. }
  2066.  
  2067. if (element.nodeType === 1 &&
  2068. origElement !== upperCanvasEl &&
  2069. fabric.util.getElementStyle(element, 'position') === 'absolute') {
  2070. left = 0;
  2071. top = 0;
  2072. }
  2073. else if (element === fabric.document) {
  2074. left = body.scrollLeft || docElement.scrollLeft || 0;
  2075. top = body.scrollTop || docElement.scrollTop || 0;
  2076. }
  2077. else {
  2078. left += element.scrollLeft || 0;
  2079. top += element.scrollTop || 0;
  2080. }
  2081. }
  2082.  
  2083. return { left: left, top: top };
  2084. }
  2085.  
  2086. /**
  2087. * Returns offset for a given element
  2088. * @function
  2089. * @memberOf fabric.util
  2090. * @param {HTMLElement} element Element to get offset for
  2091. * @return {Object} Object with "left" and "top" properties
  2092. */
  2093. function getElementOffset(element) {
  2094. var docElem,
  2095. doc = element && element.ownerDocument,
  2096. box = { left: 0, top: 0 },
  2097. offset = { left: 0, top: 0 },
  2098. scrollLeftTop,
  2099. offsetAttributes = {
  2100. borderLeftWidth: 'left',
  2101. borderTopWidth: 'top',
  2102. paddingLeft: 'left',
  2103. paddingTop: 'top'
  2104. };
  2105.  
  2106. if (!doc) {
  2107. return { left: 0, top: 0 };
  2108. }
  2109.  
  2110. for (var attr in offsetAttributes) {
  2111. offset[offsetAttributes[attr]] += parseInt(getElementStyle(element, attr), 10) || 0;
  2112. }
  2113.  
  2114. docElem = doc.documentElement;
  2115. if ( typeof element.getBoundingClientRect !== 'undefined' ) {
  2116. box = element.getBoundingClientRect();
  2117. }
  2118.  
  2119. scrollLeftTop = fabric.util.getScrollLeftTop(element, null);
  2120.  
  2121. return {
  2122. left: box.left + scrollLeftTop.left - (docElem.clientLeft || 0) + offset.left,
  2123. top: box.top + scrollLeftTop.top - (docElem.clientTop || 0) + offset.top
  2124. };
  2125. }
  2126.  
  2127. /**
  2128. * Returns style attribute value of a given element
  2129. * @memberOf fabric.util
  2130. * @param {HTMLElement} element Element to get style attribute for
  2131. * @param {String} attr Style attribute to get for element
  2132. * @return {String} Style attribute value of the given element.
  2133. */
  2134. var getElementStyle;
  2135. if (fabric.document.defaultView && fabric.document.defaultView.getComputedStyle) {
  2136. getElementStyle = function(element, attr) {
  2137. var style = fabric.document.defaultView.getComputedStyle(element, null);
  2138. return style ? style[attr] : undefined;
  2139. };
  2140. }
  2141. else {
  2142. getElementStyle = function(element, attr) {
  2143. var value = element.style[attr];
  2144. if (!value && element.currentStyle) {
  2145. value = element.currentStyle[attr];
  2146. }
  2147. return value;
  2148. };
  2149. }
  2150.  
  2151. (function () {
  2152. var style = fabric.document.documentElement.style,
  2153. selectProp = 'userSelect' in style
  2154. ? 'userSelect'
  2155. : 'MozUserSelect' in style
  2156. ? 'MozUserSelect'
  2157. : 'WebkitUserSelect' in style
  2158. ? 'WebkitUserSelect'
  2159. : 'KhtmlUserSelect' in style
  2160. ? 'KhtmlUserSelect'
  2161. : '';
  2162.  
  2163. /**
  2164. * Makes element unselectable
  2165. * @memberOf fabric.util
  2166. * @param {HTMLElement} element Element to make unselectable
  2167. * @return {HTMLElement} Element that was passed in
  2168. */
  2169. function makeElementUnselectable(element) {
  2170. if (typeof element.onselectstart !== 'undefined') {
  2171. element.onselectstart = fabric.util.falseFunction;
  2172. }
  2173. if (selectProp) {
  2174. element.style[selectProp] = 'none';
  2175. }
  2176. else if (typeof element.unselectable === 'string') {
  2177. element.unselectable = 'on';
  2178. }
  2179. return element;
  2180. }
  2181.  
  2182. /**
  2183. * Makes element selectable
  2184. * @memberOf fabric.util
  2185. * @param {HTMLElement} element Element to make selectable
  2186. * @return {HTMLElement} Element that was passed in
  2187. */
  2188. function makeElementSelectable(element) {
  2189. if (typeof element.onselectstart !== 'undefined') {
  2190. element.onselectstart = null;
  2191. }
  2192. if (selectProp) {
  2193. element.style[selectProp] = '';
  2194. }
  2195. else if (typeof element.unselectable === 'string') {
  2196. element.unselectable = '';
  2197. }
  2198. return element;
  2199. }
  2200.  
  2201. fabric.util.makeElementUnselectable = makeElementUnselectable;
  2202. fabric.util.makeElementSelectable = makeElementSelectable;
  2203. })();
  2204.  
  2205. (function() {
  2206.  
  2207. /**
  2208. * Inserts a script element with a given url into a document; invokes callback, when that script is finished loading
  2209. * @memberOf fabric.util
  2210. * @param {String} url URL of a script to load
  2211. * @param {Function} callback Callback to execute when script is finished loading
  2212. */
  2213. function getScript(url, callback) {
  2214. var headEl = fabric.document.getElementsByTagName('head')[0],
  2215. scriptEl = fabric.document.createElement('script'),
  2216. loading = true;
  2217.  
  2218. /** @ignore */
  2219. scriptEl.onload = /** @ignore */ scriptEl.onreadystatechange = function(e) {
  2220. if (loading) {
  2221. if (typeof this.readyState === 'string' &&
  2222. this.readyState !== 'loaded' &&
  2223. this.readyState !== 'complete') {
  2224. return;
  2225. }
  2226. loading = false;
  2227. callback(e || fabric.window.event);
  2228. scriptEl = scriptEl.onload = scriptEl.onreadystatechange = null;
  2229. }
  2230. };
  2231. scriptEl.src = url;
  2232. headEl.appendChild(scriptEl);
  2233. // causes issue in Opera
  2234. // headEl.removeChild(scriptEl);
  2235. }
  2236.  
  2237. fabric.util.getScript = getScript;
  2238. })();
  2239.  
  2240. fabric.util.getById = getById;
  2241. fabric.util.toArray = toArray;
  2242. fabric.util.makeElement = makeElement;
  2243. fabric.util.addClass = addClass;
  2244. fabric.util.wrapElement = wrapElement;
  2245. fabric.util.getScrollLeftTop = getScrollLeftTop;
  2246. fabric.util.getElementOffset = getElementOffset;
  2247. fabric.util.getElementStyle = getElementStyle;
  2248.  
  2249. })();
  2250.  
  2251.  
  2252. (function() {
  2253.  
  2254. function addParamToUrl(url, param) {
  2255. return url + (/\?/.test(url) ? '&' : '?') + param;
  2256. }
  2257.  
  2258. var makeXHR = (function() {
  2259. var factories = [
  2260. function() { return new ActiveXObject('Microsoft.XMLHTTP'); },
  2261. function() { return new ActiveXObject('Msxml2.XMLHTTP'); },
  2262. function() { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); },
  2263. function() { return new XMLHttpRequest(); }
  2264. ];
  2265. for (var i = factories.length; i--; ) {
  2266. try {
  2267. var req = factories[i]();
  2268. if (req) {
  2269. return factories[i];
  2270. }
  2271. }
  2272. catch (err) { }
  2273. }
  2274. })();
  2275.  
  2276. function emptyFn() { }
  2277.  
  2278. /**
  2279. * Cross-browser abstraction for sending XMLHttpRequest
  2280. * @memberOf fabric.util
  2281. * @param {String} url URL to send XMLHttpRequest to
  2282. * @param {Object} [options] Options object
  2283. * @param {String} [options.method="GET"]
  2284. * @param {Function} options.onComplete Callback to invoke when request is completed
  2285. * @return {XMLHttpRequest} request
  2286. */
  2287. function request(url, options) {
  2288.  
  2289. options || (options = { });
  2290.  
  2291. var method = options.method ? options.method.toUpperCase() : 'GET',
  2292. onComplete = options.onComplete || function() { },
  2293. xhr = makeXHR(),
  2294. body;
  2295.  
  2296. /** @ignore */
  2297. xhr.onreadystatechange = function() {
  2298. if (xhr.readyState === 4) {
  2299. onComplete(xhr);
  2300. xhr.onreadystatechange = emptyFn;
  2301. }
  2302. };
  2303.  
  2304. if (method === 'GET') {
  2305. body = null;
  2306. if (typeof options.parameters === 'string') {
  2307. url = addParamToUrl(url, options.parameters);
  2308. }
  2309. }
  2310.  
  2311. xhr.open(method, url, true);
  2312.  
  2313. if (method === 'POST' || method === 'PUT') {
  2314. xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  2315. }
  2316.  
  2317. xhr.send(body);
  2318. return xhr;
  2319. }
  2320.  
  2321. fabric.util.request = request;
  2322. })();
  2323.  
  2324.  
  2325. /**
  2326. * Wrapper around `console.log` (when available)
  2327. * @param {Any} [values] Values to log
  2328. */
  2329. fabric.log = function() { };
  2330.  
  2331. /**
  2332. * Wrapper around `console.warn` (when available)
  2333. * @param {Any} [values] Values to log as a warning
  2334. */
  2335. fabric.warn = function() { };
  2336.  
  2337. if (typeof console !== 'undefined') {
  2338. ['log', 'warn'].forEach(function(methodName) {
  2339. if (typeof console[methodName] !== 'undefined' && console[methodName].apply) {
  2340. fabric[methodName] = function() {
  2341. return console[methodName].apply(console, arguments);
  2342. };
  2343. }
  2344. });
  2345. }
  2346.  
  2347.  
  2348. (function() {
  2349.  
  2350. /**
  2351. * Changes value from one to another within certain period of time, invoking callbacks as value is being changed.
  2352. * @memberOf fabric.util
  2353. * @param {Object} [options] Animation options
  2354. * @param {Function} [options.onChange] Callback; invoked on every value change
  2355. * @param {Function} [options.onComplete] Callback; invoked when value change is completed
  2356. * @param {Number} [options.startValue=0] Starting value
  2357. * @param {Number} [options.endValue=100] Ending value
  2358. * @param {Number} [options.byValue=100] Value to modify the property by
  2359. * @param {Function} [options.easing] Easing function
  2360. * @param {Number} [options.duration=500] Duration of change (in ms)
  2361. */
  2362. function animate(options) {
  2363.  
  2364. requestAnimFrame(function(timestamp) {
  2365. options || (options = { });
  2366.  
  2367. var start = timestamp || +new Date(),
  2368. duration = options.duration || 500,
  2369. finish = start + duration, time,
  2370. onChange = options.onChange || function() { },
  2371. abort = options.abort || function() { return false; },
  2372. easing = options.easing || function(t, b, c, d) {return -c * Math.cos(t / d * (Math.PI / 2)) + c + b;},
  2373. startValue = 'startValue' in options ? options.startValue : 0,
  2374. endValue = 'endValue' in options ? options.endValue : 100,
  2375. byValue = options.byValue || endValue - startValue;
  2376.  
  2377. options.onStart && options.onStart();
  2378.  
  2379. (function tick(ticktime) {
  2380. time = ticktime || +new Date();
  2381. var currentTime = time > finish ? duration : (time - start);
  2382. if (abort()) {
  2383. options.onComplete && options.onComplete();
  2384. return;
  2385. }
  2386. onChange(easing(currentTime, startValue, byValue, duration));
  2387. if (time > finish) {
  2388. options.onComplete && options.onComplete();
  2389. return;
  2390. }
  2391. requestAnimFrame(tick);
  2392. })(start);
  2393. });
  2394.  
  2395. }
  2396.  
  2397. var _requestAnimFrame = fabric.window.requestAnimationFrame ||
  2398. fabric.window.webkitRequestAnimationFrame ||
  2399. fabric.window.mozRequestAnimationFrame ||
  2400. fabric.window.oRequestAnimationFrame ||
  2401. fabric.window.msRequestAnimationFrame ||
  2402. function(callback) {
  2403. fabric.window.setTimeout(callback, 1000 / 60);
  2404. };
  2405. /**
  2406. * requestAnimationFrame polyfill based on http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  2407. * In order to get a precise start time, `requestAnimFrame` should be called as an entry into the method
  2408. * @memberOf fabric.util
  2409. * @param {Function} callback Callback to invoke
  2410. * @param {DOMElement} element optional Element to associate with animation
  2411. */
  2412. function requestAnimFrame() {
  2413. return _requestAnimFrame.apply(fabric.window, arguments);
  2414. }
  2415.  
  2416. fabric.util.animate = animate;
  2417. fabric.util.requestAnimFrame = requestAnimFrame;
  2418.  
  2419. })();
  2420.  
  2421.  
  2422. (function() {
  2423.  
  2424. function normalize(a, c, p, s) {
  2425. if (a < Math.abs(c)) {
  2426. a = c;
  2427. s = p / 4;
  2428. }
  2429. else {
  2430. s = p / (2 * Math.PI) * Math.asin(c / a);
  2431. }
  2432. return { a: a, c: c, p: p, s: s };
  2433. }
  2434.  
  2435. function elastic(opts, t, d) {
  2436. return opts.a *
  2437. Math.pow(2, 10 * (t -= 1)) *
  2438. Math.sin( (t * d - opts.s) * (2 * Math.PI) / opts.p );
  2439. }
  2440.  
  2441. /**
  2442. * Cubic easing out
  2443. * @memberOf fabric.util.ease
  2444. */
  2445. function easeOutCubic(t, b, c, d) {
  2446. return c * ((t = t / d - 1) * t * t + 1) + b;
  2447. }
  2448.  
  2449. /**
  2450. * Cubic easing in and out
  2451. * @memberOf fabric.util.ease
  2452. */
  2453. function easeInOutCubic(t, b, c, d) {
  2454. t /= d/2;
  2455. if (t < 1) {
  2456. return c / 2 * t * t * t + b;
  2457. }
  2458. return c / 2 * ((t -= 2) * t * t + 2) + b;
  2459. }
  2460.  
  2461. /**
  2462. * Quartic easing in
  2463. * @memberOf fabric.util.ease
  2464. */
  2465. function easeInQuart(t, b, c, d) {
  2466. return c * (t /= d) * t * t * t + b;
  2467. }
  2468.  
  2469. /**
  2470. * Quartic easing out
  2471. * @memberOf fabric.util.ease
  2472. */
  2473. function easeOutQuart(t, b, c, d) {
  2474. return -c * ((t = t / d - 1) * t * t * t - 1) + b;
  2475. }
  2476.  
  2477. /**
  2478. * Quartic easing in and out
  2479. * @memberOf fabric.util.ease
  2480. */
  2481. function easeInOutQuart(t, b, c, d) {
  2482. t /= d / 2;
  2483. if (t < 1) {
  2484. return c / 2 * t * t * t * t + b;
  2485. }
  2486. return -c / 2 * ((t -= 2) * t * t * t - 2) + b;
  2487. }
  2488.  
  2489. /**
  2490. * Quintic easing in
  2491. * @memberOf fabric.util.ease
  2492. */
  2493. function easeInQuint(t, b, c, d) {
  2494. return c * (t /= d) * t * t * t * t + b;
  2495. }
  2496.  
  2497. /**
  2498. * Quintic easing out
  2499. * @memberOf fabric.util.ease
  2500. */
  2501. function easeOutQuint(t, b, c, d) {
  2502. return c * ((t = t / d - 1) * t * t * t * t + 1) + b;
  2503. }
  2504.  
  2505. /**
  2506. * Quintic easing in and out
  2507. * @memberOf fabric.util.ease
  2508. */
  2509. function easeInOutQuint(t, b, c, d) {
  2510. t /= d / 2;
  2511. if (t < 1) {
  2512. return c / 2 * t * t * t * t * t + b;
  2513. }
  2514. return c / 2 * ((t -= 2) * t * t * t * t + 2) + b;
  2515. }
  2516.  
  2517. /**
  2518. * Sinusoidal easing in
  2519. * @memberOf fabric.util.ease
  2520. */
  2521. function easeInSine(t, b, c, d) {
  2522. return -c * Math.cos(t / d * (Math.PI / 2)) + c + b;
  2523. }
  2524.  
  2525. /**
  2526. * Sinusoidal easing out
  2527. * @memberOf fabric.util.ease
  2528. */
  2529. function easeOutSine(t, b, c, d) {
  2530. return c * Math.sin(t / d * (Math.PI / 2)) + b;
  2531. }
  2532.  
  2533. /**
  2534. * Sinusoidal easing in and out
  2535. * @memberOf fabric.util.ease
  2536. */
  2537. function easeInOutSine(t, b, c, d) {
  2538. return -c / 2 * (Math.cos(Math.PI * t / d) - 1) + b;
  2539. }
  2540.  
  2541. /**
  2542. * Exponential easing in
  2543. * @memberOf fabric.util.ease
  2544. */
  2545. function easeInExpo(t, b, c, d) {
  2546. return (t === 0) ? b : c * Math.pow(2, 10 * (t / d - 1)) + b;
  2547. }
  2548.  
  2549. /**
  2550. * Exponential easing out
  2551. * @memberOf fabric.util.ease
  2552. */
  2553. function easeOutExpo(t, b, c, d) {
  2554. return (t === d) ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b;
  2555. }
  2556.  
  2557. /**
  2558. * Exponential easing in and out
  2559. * @memberOf fabric.util.ease
  2560. */
  2561. function easeInOutExpo(t, b, c, d) {
  2562. if (t === 0) {
  2563. return b;
  2564. }
  2565. if (t === d) {
  2566. return b + c;
  2567. }
  2568. t /= d / 2;
  2569. if (t < 1) {
  2570. return c / 2 * Math.pow(2, 10 * (t - 1)) + b;
  2571. }
  2572. return c / 2 * (-Math.pow(2, -10 * --t) + 2) + b;
  2573. }
  2574.  
  2575. /**
  2576. * Circular easing in
  2577. * @memberOf fabric.util.ease
  2578. */
  2579. function easeInCirc(t, b, c, d) {
  2580. return -c * (Math.sqrt(1 - (t /= d) * t) - 1) + b;
  2581. }
  2582.  
  2583. /**
  2584. * Circular easing out
  2585. * @memberOf fabric.util.ease
  2586. */
  2587. function easeOutCirc(t, b, c, d) {
  2588. return c * Math.sqrt(1 - (t = t / d - 1) * t) + b;
  2589. }
  2590.  
  2591. /**
  2592. * Circular easing in and out
  2593. * @memberOf fabric.util.ease
  2594. */
  2595. function easeInOutCirc(t, b, c, d) {
  2596. t /= d / 2;
  2597. if (t < 1) {
  2598. return -c / 2 * (Math.sqrt(1 - t * t) - 1) + b;
  2599. }
  2600. return c / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1) + b;
  2601. }
  2602.  
  2603. /**
  2604. * Elastic easing in
  2605. * @memberOf fabric.util.ease
  2606. */
  2607. function easeInElastic(t, b, c, d) {
  2608. var s = 1.70158, p = 0, a = c;
  2609. if (t === 0) {
  2610. return b;
  2611. }
  2612. t /= d;
  2613. if (t === 1) {
  2614. return b + c;
  2615. }
  2616. if (!p) {
  2617. p = d * 0.3;
  2618. }
  2619. var opts = normalize(a, c, p, s);
  2620. return -elastic(opts, t, d) + b;
  2621. }
  2622.  
  2623. /**
  2624. * Elastic easing out
  2625. * @memberOf fabric.util.ease
  2626. */
  2627. function easeOutElastic(t, b, c, d) {
  2628. var s = 1.70158, p = 0, a = c;
  2629. if (t === 0) {
  2630. return b;
  2631. }
  2632. t /= d;
  2633. if (t === 1) {
  2634. return b + c;
  2635. }
  2636. if (!p) {
  2637. p = d * 0.3;
  2638. }
  2639. var opts = normalize(a, c, p, s);
  2640. return opts.a * Math.pow(2, -10 * t) * Math.sin((t * d - opts.s) * (2 * Math.PI) / opts.p ) + opts.c + b;
  2641. }
  2642.  
  2643. /**
  2644. * Elastic easing in and out
  2645. * @memberOf fabric.util.ease
  2646. */
  2647. function easeInOutElastic(t, b, c, d) {
  2648. var s = 1.70158, p = 0, a = c;
  2649. if (t === 0) {
  2650. return b;
  2651. }
  2652. t /= d / 2;
  2653. if (t === 2) {
  2654. return b + c;
  2655. }
  2656. if (!p) {
  2657. p = d * (0.3 * 1.5);
  2658. }
  2659. var opts = normalize(a, c, p, s);
  2660. if (t < 1) {
  2661. return -0.5 * elastic(opts, t, d) + b;
  2662. }
  2663. return opts.a * Math.pow(2, -10 * (t -= 1)) *
  2664. Math.sin((t * d - opts.s) * (2 * Math.PI) / opts.p ) * 0.5 + opts.c + b;
  2665. }
  2666.  
  2667. /**
  2668. * Backwards easing in
  2669. * @memberOf fabric.util.ease
  2670. */
  2671. function easeInBack(t, b, c, d, s) {
  2672. if (s === undefined) {
  2673. s = 1.70158;
  2674. }
  2675. return c * (t /= d) * t * ((s + 1) * t - s) + b;
  2676. }
  2677.  
  2678. /**
  2679. * Backwards easing out
  2680. * @memberOf fabric.util.ease
  2681. */
  2682. function easeOutBack(t, b, c, d, s) {
  2683. if (s === undefined) {
  2684. s = 1.70158;
  2685. }
  2686. return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
  2687. }
  2688.  
  2689. /**
  2690. * Backwards easing in and out
  2691. * @memberOf fabric.util.ease
  2692. */
  2693. function easeInOutBack(t, b, c, d, s) {
  2694. if (s === undefined) {
  2695. s = 1.70158;
  2696. }
  2697. t /= d / 2;
  2698. if (t < 1) {
  2699. return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b;
  2700. }
  2701. return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
  2702. }
  2703.  
  2704. /**
  2705. * Bouncing easing in
  2706. * @memberOf fabric.util.ease
  2707. */
  2708. function easeInBounce(t, b, c, d) {
  2709. return c - easeOutBounce (d - t, 0, c, d) + b;
  2710. }
  2711.  
  2712. /**
  2713. * Bouncing easing out
  2714. * @memberOf fabric.util.ease
  2715. */
  2716. function easeOutBounce(t, b, c, d) {
  2717. if ((t /= d) < (1 / 2.75)) {
  2718. return c * (7.5625 * t * t) + b;
  2719. }
  2720. else if (t < (2/2.75)) {
  2721. return c * (7.5625 * (t -= (1.5 / 2.75)) * t + 0.75) + b;
  2722. }
  2723. else if (t < (2.5/2.75)) {
  2724. return c * (7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375) + b;
  2725. }
  2726. else {
  2727. return c * (7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375) + b;
  2728. }
  2729. }
  2730.  
  2731. /**
  2732. * Bouncing easing in and out
  2733. * @memberOf fabric.util.ease
  2734. */
  2735. function easeInOutBounce(t, b, c, d) {
  2736. if (t < d / 2) {
  2737. return easeInBounce (t * 2, 0, c, d) * 0.5 + b;
  2738. }
  2739. return easeOutBounce(t * 2 - d, 0, c, d) * 0.5 + c * 0.5 + b;
  2740. }
  2741.  
  2742. /**
  2743. * Easing functions
  2744. * See <a href="http://gizma.com/easing/">Easing Equations by Robert Penner</a>
  2745. * @namespace fabric.util.ease
  2746. */
  2747. fabric.util.ease = {
  2748.  
  2749. /**
  2750. * Quadratic easing in
  2751. * @memberOf fabric.util.ease
  2752. */
  2753. easeInQuad: function(t, b, c, d) {
  2754. return c * (t /= d) * t + b;
  2755. },
  2756.  
  2757. /**
  2758. * Quadratic easing out
  2759. * @memberOf fabric.util.ease
  2760. */
  2761. easeOutQuad: function(t, b, c, d) {
  2762. return -c * (t /= d) * (t - 2) + b;
  2763. },
  2764.  
  2765. /**
  2766. * Quadratic easing in and out
  2767. * @memberOf fabric.util.ease
  2768. */
  2769. easeInOutQuad: function(t, b, c, d) {
  2770. t /= (d / 2);
  2771. if (t < 1) {
  2772. return c / 2 * t * t + b;
  2773. }
  2774. return -c / 2 * ((--t) * (t - 2) - 1) + b;
  2775. },
  2776.  
  2777. /**
  2778. * Cubic easing in
  2779. * @memberOf fabric.util.ease
  2780. */
  2781. easeInCubic: function(t, b, c, d) {
  2782. return c * (t /= d) * t * t + b;
  2783. },
  2784.  
  2785. easeOutCubic: easeOutCubic,
  2786. easeInOutCubic: easeInOutCubic,
  2787. easeInQuart: easeInQuart,
  2788. easeOutQuart: easeOutQuart,
  2789. easeInOutQuart: easeInOutQuart,
  2790. easeInQuint: easeInQuint,
  2791. easeOutQuint: easeOutQuint,
  2792. easeInOutQuint: easeInOutQuint,
  2793. easeInSine: easeInSine,
  2794. easeOutSine: easeOutSine,
  2795. easeInOutSine: easeInOutSine,
  2796. easeInExpo: easeInExpo,
  2797. easeOutExpo: easeOutExpo,
  2798. easeInOutExpo: easeInOutExpo,
  2799. easeInCirc: easeInCirc,
  2800. easeOutCirc: easeOutCirc,
  2801. easeInOutCirc: easeInOutCirc,
  2802. easeInElastic: easeInElastic,
  2803. easeOutElastic: easeOutElastic,
  2804. easeInOutElastic: easeInOutElastic,
  2805. easeInBack: easeInBack,
  2806. easeOutBack: easeOutBack,
  2807. easeInOutBack: easeInOutBack,
  2808. easeInBounce: easeInBounce,
  2809. easeOutBounce: easeOutBounce,
  2810. easeInOutBounce: easeInOutBounce
  2811. };
  2812.  
  2813. }());
  2814.  
  2815.  
  2816. (function(global) {
  2817.  
  2818. 'use strict';
  2819.  
  2820. /**
  2821. * @name fabric
  2822. * @namespace
  2823. */
  2824.  
  2825. var fabric = global.fabric || (global.fabric = { }),
  2826. extend = fabric.util.object.extend,
  2827. capitalize = fabric.util.string.capitalize,
  2828. clone = fabric.util.object.clone,
  2829. toFixed = fabric.util.toFixed,
  2830. parseUnit = fabric.util.parseUnit,
  2831. multiplyTransformMatrices = fabric.util.multiplyTransformMatrices,
  2832.  
  2833. attributesMap = {
  2834. cx: 'left',
  2835. x: 'left',
  2836. r: 'radius',
  2837. cy: 'top',
  2838. y: 'top',
  2839. display: 'visible',
  2840. visibility: 'visible',
  2841. transform: 'transformMatrix',
  2842. 'fill-opacity': 'fillOpacity',
  2843. 'fill-rule': 'fillRule',
  2844. 'font-family': 'fontFamily',
  2845. 'font-size': 'fontSize',
  2846. 'font-style': 'fontStyle',
  2847. 'font-weight': 'fontWeight',
  2848. 'stroke-dasharray': 'strokeDashArray',
  2849. 'stroke-linecap': 'strokeLineCap',
  2850. 'stroke-linejoin': 'strokeLineJoin',
  2851. 'stroke-miterlimit': 'strokeMiterLimit',
  2852. 'stroke-opacity': 'strokeOpacity',
  2853. 'stroke-width': 'strokeWidth',
  2854. 'text-decoration': 'textDecoration',
  2855. 'text-anchor': 'originX'
  2856. },
  2857.  
  2858. colorAttributes = {
  2859. stroke: 'strokeOpacity',
  2860. fill: 'fillOpacity'
  2861. };
  2862.  
  2863. fabric.cssRules = { };
  2864. fabric.gradientDefs = { };
  2865.  
  2866. function normalizeAttr(attr) {
  2867. // transform attribute names
  2868. if (attr in attributesMap) {
  2869. return attributesMap[attr];
  2870. }
  2871. return attr;
  2872. }
  2873.  
  2874. function normalizeValue(attr, value, parentAttributes) {
  2875. var isArray = Object.prototype.toString.call(value) === '[object Array]',
  2876. parsed;
  2877.  
  2878. if ((attr === 'fill' || attr === 'stroke') && value === 'none') {
  2879. value = '';
  2880. }
  2881. else if (attr === 'strokeDashArray') {
  2882. value = value.replace(/,/g, ' ').split(/\s+/).map(function(n) {
  2883. return parseFloat(n);
  2884. });
  2885. }
  2886. else if (attr === 'transformMatrix') {
  2887. if (parentAttributes && parentAttributes.transformMatrix) {
  2888. value = multiplyTransformMatrices(
  2889. parentAttributes.transformMatrix, fabric.parseTransformAttribute(value));
  2890. }
  2891. else {
  2892. value = fabric.parseTransformAttribute(value);
  2893. }
  2894. }
  2895. else if (attr === 'visible') {
  2896. value = (value === 'none' || value === 'hidden') ? false : true;
  2897. // display=none on parent element always takes precedence over child element
  2898. if (parentAttributes && parentAttributes.visible === false) {
  2899. value = false;
  2900. }
  2901. }
  2902. else if (attr === 'originX' /* text-anchor */) {
  2903. value = value === 'start' ? 'left' : value === 'end' ? 'right' : 'center';
  2904. }
  2905. else {
  2906. parsed = isArray ? value.map(parseUnit) : parseUnit(value);
  2907. }
  2908.  
  2909. return (!isArray && isNaN(parsed) ? value : parsed);
  2910. }
  2911.  
  2912. /**
  2913. * @private
  2914. * @param {Object} attributes Array of attributes to parse
  2915. */
  2916. function _setStrokeFillOpacity(attributes) {
  2917. for (var attr in colorAttributes) {
  2918.  
  2919. if (!attributes[attr] || typeof attributes[colorAttributes[attr]] === 'undefined') {
  2920. continue;
  2921. }
  2922.  
  2923. if (attributes[attr].indexOf('url(') === 0) {
  2924. continue;
  2925. }
  2926.  
  2927. var color = new fabric.Color(attributes[attr]);
  2928. attributes[attr] = color.setAlpha(toFixed(color.getAlpha() * attributes[colorAttributes[attr]], 2)).toRgba();
  2929. }
  2930. return attributes;
  2931. }
  2932.  
  2933. /**
  2934. * Parses "transform" attribute, returning an array of values
  2935. * @static
  2936. * @function
  2937. * @memberOf fabric
  2938. * @param {String} attributeValue String containing attribute value
  2939. * @return {Array} Array of 6 elements representing transformation matrix
  2940. */
  2941. fabric.parseTransformAttribute = (function() {
  2942. function rotateMatrix(matrix, args) {
  2943. var angle = args[0];
  2944.  
  2945. matrix[0] = Math.cos(angle);
  2946. matrix[1] = Math.sin(angle);
  2947. matrix[2] = -Math.sin(angle);
  2948. matrix[3] = Math.cos(angle);
  2949. }
  2950.  
  2951. function scaleMatrix(matrix, args) {
  2952. var multiplierX = args[0],
  2953. multiplierY = (args.length === 2) ? args[1] : args[0];
  2954.  
  2955. matrix[0] = multiplierX;
  2956. matrix[3] = multiplierY;
  2957. }
  2958.  
  2959. function skewXMatrix(matrix, args) {
  2960. matrix[2] = Math.tan(fabric.util.degreesToRadians(args[0]));
  2961. }
  2962.  
  2963. function skewYMatrix(matrix, args) {
  2964. matrix[1] = Math.tan(fabric.util.degreesToRadians(args[0]));
  2965. }
  2966.  
  2967. function translateMatrix(matrix, args) {
  2968. matrix[4] = args[0];
  2969. if (args.length === 2) {
  2970. matrix[5] = args[1];
  2971. }
  2972. }
  2973.  
  2974. // identity matrix
  2975. var iMatrix = [
  2976. 1, // a
  2977. 0, // b
  2978. 0, // c
  2979. 1, // d
  2980. 0, // e
  2981. 0 // f
  2982. ],
  2983.  
  2984. // == begin transform regexp
  2985. number = '(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:e[-+]?\\d+)?)',
  2986.  
  2987. commaWsp = '(?:\\s+,?\\s*|,\\s*)',
  2988.  
  2989. skewX = '(?:(skewX)\\s*\\(\\s*(' + number + ')\\s*\\))',
  2990.  
  2991. skewY = '(?:(skewY)\\s*\\(\\s*(' + number + ')\\s*\\))',
  2992.  
  2993. rotate = '(?:(rotate)\\s*\\(\\s*(' + number + ')(?:' +
  2994. commaWsp + '(' + number + ')' +
  2995. commaWsp + '(' + number + '))?\\s*\\))',
  2996.  
  2997. scale = '(?:(scale)\\s*\\(\\s*(' + number + ')(?:' +
  2998. commaWsp + '(' + number + '))?\\s*\\))',
  2999.  
  3000. translate = '(?:(translate)\\s*\\(\\s*(' + number + ')(?:' +
  3001. commaWsp + '(' + number + '))?\\s*\\))',
  3002.  
  3003. matrix = '(?:(matrix)\\s*\\(\\s*' +
  3004. '(' + number + ')' + commaWsp +
  3005. '(' + number + ')' + commaWsp +
  3006. '(' + number + ')' + commaWsp +
  3007. '(' + number + ')' + commaWsp +
  3008. '(' + number + ')' + commaWsp +
  3009. '(' + number + ')' +
  3010. '\\s*\\))',
  3011.  
  3012. transform = '(?:' +
  3013. matrix + '|' +
  3014. translate + '|' +
  3015. scale + '|' +
  3016. rotate + '|' +
  3017. skewX + '|' +
  3018. skewY +
  3019. ')',
  3020.  
  3021. transforms = '(?:' + transform + '(?:' + commaWsp + transform + ')*' + ')',
  3022.  
  3023. transformList = '^\\s*(?:' + transforms + '?)\\s*$',
  3024.  
  3025. // http://www.w3.org/TR/SVG/coords.html#TransformAttribute
  3026. reTransformList = new RegExp(transformList),
  3027. // == end transform regexp
  3028.  
  3029. reTransform = new RegExp(transform, 'g');
  3030.  
  3031. return function(attributeValue) {
  3032.  
  3033. // start with identity matrix
  3034. var matrix = iMatrix.concat(),
  3035. matrices = [ ];
  3036.  
  3037. // return if no argument was given or
  3038. // an argument does not match transform attribute regexp
  3039. if (!attributeValue || (attributeValue && !reTransformList.test(attributeValue))) {
  3040. return matrix;
  3041. }
  3042.  
  3043. attributeValue.replace(reTransform, function(match) {
  3044.  
  3045. var m = new RegExp(transform).exec(match).filter(function (match) {
  3046. return (match !== '' && match != null);
  3047. }),
  3048. operation = m[1],
  3049. args = m.slice(2).map(parseFloat);
  3050.  
  3051. switch (operation) {
  3052. case 'translate':
  3053. translateMatrix(matrix, args);
  3054. break;
  3055. case 'rotate':
  3056. args[0] = fabric.util.degreesToRadians(args[0]);
  3057. rotateMatrix(matrix, args);
  3058. break;
  3059. case 'scale':
  3060. scaleMatrix(matrix, args);
  3061. break;
  3062. case 'skewX':
  3063. skewXMatrix(matrix, args);
  3064. break;
  3065. case 'skewY':
  3066. skewYMatrix(matrix, args);
  3067. break;
  3068. case 'matrix':
  3069. matrix = args;
  3070. break;
  3071. }
  3072.  
  3073. // snapshot current matrix into matrices array
  3074. matrices.push(matrix.concat());
  3075. // reset
  3076. matrix = iMatrix.concat();
  3077. });
  3078.  
  3079. var combinedMatrix = matrices[0];
  3080. while (matrices.length > 1) {
  3081. matrices.shift();
  3082. combinedMatrix = fabric.util.multiplyTransformMatrices(combinedMatrix, matrices[0]);
  3083. }
  3084. return combinedMatrix;
  3085. };
  3086. })();
  3087.  
  3088. function parseFontDeclaration(value, oStyle) {
  3089.  
  3090. // TODO: support non-px font size
  3091. 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+(.*)/);
  3092.  
  3093. if (!match) {
  3094. return;
  3095. }
  3096.  
  3097. var fontStyle = match[1],
  3098. // font variant is not used
  3099. // fontVariant = match[2],
  3100. fontWeight = match[3],
  3101. fontSize = match[4],
  3102. lineHeight = match[5],
  3103. fontFamily = match[6];
  3104.  
  3105. if (fontStyle) {
  3106. oStyle.fontStyle = fontStyle;
  3107. }
  3108. if (fontWeight) {
  3109. oStyle.fontWeight = isNaN(parseFloat(fontWeight)) ? fontWeight : parseFloat(fontWeight);
  3110. }
  3111. if (fontSize) {
  3112. oStyle.fontSize = parseFloat(fontSize);
  3113. }
  3114. if (fontFamily) {
  3115. oStyle.fontFamily = fontFamily;
  3116. }
  3117. if (lineHeight) {
  3118. oStyle.lineHeight = lineHeight === 'normal' ? 1 : lineHeight;
  3119. }
  3120. }
  3121.  
  3122. /**
  3123. * @private
  3124. */
  3125. function parseStyleString(style, oStyle) {
  3126. var attr, value;
  3127. style.replace(/;$/, '').split(';').forEach(function (chunk) {
  3128. var pair = chunk.split(':');
  3129.  
  3130. attr = normalizeAttr(pair[0].trim().toLowerCase());
  3131. value = normalizeValue(attr, pair[1].trim());
  3132.  
  3133. if (attr === 'font') {
  3134. parseFontDeclaration(value, oStyle);
  3135. }
  3136. else {
  3137. oStyle[attr] = value;
  3138. }
  3139. });
  3140. }
  3141.  
  3142. /**
  3143. * @private
  3144. */
  3145. function parseStyleObject(style, oStyle) {
  3146. var attr, value;
  3147. for (var prop in style) {
  3148. if (typeof style[prop] === 'undefined') {
  3149. continue;
  3150. }
  3151.  
  3152. attr = normalizeAttr(prop.toLowerCase());
  3153. value = normalizeValue(attr, style[prop]);
  3154.  
  3155. if (attr === 'font') {
  3156. parseFontDeclaration(value, oStyle);
  3157. }
  3158. else {
  3159. oStyle[attr] = value;
  3160. }
  3161. }
  3162. }
  3163.  
  3164. /**
  3165. * @private
  3166. */
  3167. function getGlobalStylesForElement(element, svgUid) {
  3168. var styles = { };
  3169. for (var rule in fabric.cssRules[svgUid]) {
  3170. if (elementMatchesRule(element, rule.split(' '))) {
  3171. for (var property in fabric.cssRules[svgUid][rule]) {
  3172. styles[property] = fabric.cssRules[svgUid][rule][property];
  3173. }
  3174. }
  3175. }
  3176. return styles;
  3177. }
  3178.  
  3179. /**
  3180. * @private
  3181. */
  3182. function elementMatchesRule(element, selectors) {
  3183. var firstMatching, parentMatching = true;
  3184. //start from rightmost selector.
  3185. firstMatching = selectorMatches(element, selectors.pop());
  3186. if (firstMatching && selectors.length) {
  3187. parentMatching = doesSomeParentMatch(element, selectors);
  3188. }
  3189. return firstMatching && parentMatching && (selectors.length === 0);
  3190. }
  3191.  
  3192. function doesSomeParentMatch(element, selectors) {
  3193. var selector, parentMatching = true;
  3194. while (element.parentNode && element.parentNode.nodeType === 1 && selectors.length) {
  3195. if (parentMatching) {
  3196. selector = selectors.pop();
  3197. }
  3198. element = element.parentNode;
  3199. parentMatching = selectorMatches(element, selector);
  3200. }
  3201. return selectors.length === 0;
  3202. }
  3203. /**
  3204. * @private
  3205. */
  3206. function selectorMatches(element, selector) {
  3207. var nodeName = element.nodeName,
  3208. classNames = element.getAttribute('class'),
  3209. id = element.getAttribute('id'), matcher;
  3210. // i check if a selector matches slicing away part from it.
  3211. // if i get empty string i should match
  3212. matcher = new RegExp('^' + nodeName, 'i');
  3213. selector = selector.replace(matcher, '');
  3214. if (id && selector.length) {
  3215. matcher = new RegExp('#' + id + '(?![a-zA-Z\\-]+)', 'i');
  3216. selector = selector.replace(matcher, '');
  3217. }
  3218. if (classNames && selector.length) {
  3219. classNames = classNames.split(' ');
  3220. for (var i = classNames.length; i--;) {
  3221. matcher = new RegExp('\\.' + classNames[i] + '(?![a-zA-Z\\-]+)', 'i');
  3222. selector = selector.replace(matcher, '');
  3223. }
  3224. }
  3225. return selector.length === 0;
  3226. }
  3227.  
  3228. /**
  3229. * @private
  3230. */
  3231. function parseUseDirectives(doc) {
  3232. var nodelist = doc.getElementsByTagName('use');
  3233. while (nodelist.length) {
  3234. var el = nodelist[0],
  3235. xlink = el.getAttribute('xlink:href').substr(1),
  3236. x = el.getAttribute('x') || 0,
  3237. y = el.getAttribute('y') || 0,
  3238. el2 = doc.getElementById(xlink).cloneNode(true),
  3239. currentTrans = (el.getAttribute('transform') || '') + ' translate(' + x + ', ' + y + ')',
  3240. parentNode;
  3241.  
  3242. for (var j = 0, attrs = el.attributes, l = attrs.length; j < l; j++) {
  3243. var attr = attrs.item(j);
  3244. if (attr.nodeName === 'x' || attr.nodeName === 'y' || attr.nodeName === 'xlink:href') {
  3245. continue;
  3246. }
  3247.  
  3248. if (attr.nodeName === 'transform') {
  3249. currentTrans = currentTrans + ' ' + attr.nodeValue;
  3250. }
  3251. else {
  3252. el2.setAttribute(attr.nodeName, attr.nodeValue);
  3253. }
  3254. }
  3255.  
  3256. el2.setAttribute('transform', currentTrans);
  3257. el2.removeAttribute('id');
  3258. parentNode = el.parentNode;
  3259. parentNode.replaceChild(el2, el);
  3260. }
  3261. }
  3262.  
  3263. /**
  3264. * Add a <g> element that envelop all SCG elements and makes the viewbox transformMatrix descend on all elements
  3265. */
  3266. function addSvgTransform(doc, matrix) {
  3267. matrix[3] = matrix[0] = (matrix[0] > matrix[3] ? matrix[3] : matrix[0]);
  3268. if (!(matrix[0] !== 1 || matrix[3] !== 1 || matrix[4] !== 0 || matrix[5] !== 0)) {
  3269. return;
  3270. }
  3271. // default is to preserve aspect ratio
  3272. // preserveAspectRatio attribute to be implemented
  3273. var el = doc.ownerDocument.createElement('g');
  3274. while (doc.firstChild != null) {
  3275. el.appendChild(doc.firstChild);
  3276. }
  3277. el.setAttribute('transform',
  3278. 'matrix(' + matrix[0] + ' ' +
  3279. matrix[1] + ' ' +
  3280. matrix[2] + ' ' +
  3281. matrix[3] + ' ' +
  3282. matrix[4] + ' ' +
  3283. matrix[5] + ')');
  3284.  
  3285. doc.appendChild(el);
  3286. }
  3287.  
  3288. /**
  3289. * Parses an SVG document, converts it to an array of corresponding fabric.* instances and passes them to a callback
  3290. * @static
  3291. * @function
  3292. * @memberOf fabric
  3293. * @param {SVGDocument} doc SVG document to parse
  3294. * @param {Function} callback Callback to call when parsing is finished; It's being passed an array of elements (parsed from a document).
  3295. * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
  3296. */
  3297. fabric.parseSVGDocument = (function() {
  3298.  
  3299. var reAllowedSVGTagNames = /^(path|circle|polygon|polyline|ellipse|rect|line|image|text)$/,
  3300.  
  3301. // http://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute
  3302. // \d doesn't quite cut it (as we need to match an actual float number)
  3303.  
  3304. // matches, e.g.: +14.56e-12, etc.
  3305. reNum = '(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:e[-+]?\\d+)?)',
  3306.  
  3307. reViewBoxAttrValue = new RegExp(
  3308. '^' +
  3309. '\\s*(' + reNum + '+)\\s*,?' +
  3310. '\\s*(' + reNum + '+)\\s*,?' +
  3311. '\\s*(' + reNum + '+)\\s*,?' +
  3312. '\\s*(' + reNum + '+)\\s*' +
  3313. '$'
  3314. );
  3315.  
  3316. function hasAncestorWithNodeName(element, nodeName) {
  3317. while (element && (element = element.parentNode)) {
  3318. if (nodeName.test(element.nodeName)) {
  3319. return true;
  3320. }
  3321. }
  3322. return false;
  3323. }
  3324.  
  3325. return function(doc, callback, reviver) {
  3326. if (!doc) {
  3327. return;
  3328. }
  3329. var startTime = new Date(),
  3330. svgUid = fabric.Object.__uid++;
  3331.  
  3332. parseUseDirectives(doc);
  3333. /* http://www.w3.org/TR/SVG/struct.html#SVGElementWidthAttribute
  3334. * as per spec, width and height attributes are to be considered
  3335. * 100% if no value is specified.
  3336. */
  3337. var viewBoxAttr = doc.getAttribute('viewBox'),
  3338. widthAttr = parseUnit(doc.getAttribute('width') || '100%'),
  3339. heightAttr = parseUnit(doc.getAttribute('height') || '100%'),
  3340. viewBoxWidth,
  3341. viewBoxHeight;
  3342.  
  3343. if (viewBoxAttr && (viewBoxAttr = viewBoxAttr.match(reViewBoxAttrValue))) {
  3344. var minX = parseFloat(viewBoxAttr[1]),
  3345. minY = parseFloat(viewBoxAttr[2]),
  3346. scaleX = 1, scaleY = 1;
  3347. viewBoxWidth = parseFloat(viewBoxAttr[3]);
  3348. viewBoxHeight = parseFloat(viewBoxAttr[4]);
  3349. if (widthAttr && widthAttr !== viewBoxWidth ) {
  3350. scaleX = widthAttr / viewBoxWidth;
  3351. }
  3352. if (heightAttr && heightAttr !== viewBoxHeight) {
  3353. scaleY = heightAttr / viewBoxHeight;
  3354. }
  3355. addSvgTransform(doc, [scaleX, 0, 0, scaleY, scaleX * -minX, scaleY * -minY]);
  3356. }
  3357.  
  3358. var descendants = fabric.util.toArray(doc.getElementsByTagName('*'));
  3359.  
  3360. if (descendants.length === 0 && fabric.isLikelyNode) {
  3361. // we're likely in node, where "o3-xml" library fails to gEBTN("*")
  3362. // https://github.com/ajaxorg/node-o3-xml/issues/21
  3363. descendants = doc.selectNodes('//*[name(.)!="svg"]');
  3364. var arr = [ ];
  3365. for (var i = 0, len = descendants.length; i < len; i++) {
  3366. arr[i] = descendants[i];
  3367. }
  3368. descendants = arr;
  3369. }
  3370.  
  3371. var elements = descendants.filter(function(el) {
  3372. return reAllowedSVGTagNames.test(el.tagName) &&
  3373. !hasAncestorWithNodeName(el, /^(?:pattern|defs)$/); // http://www.w3.org/TR/SVG/struct.html#DefsElement
  3374. });
  3375.  
  3376. if (!elements || (elements && !elements.length)) {
  3377. callback && callback([], {});
  3378. return;
  3379. }
  3380.  
  3381. var options = {
  3382. width: widthAttr ? widthAttr : viewBoxWidth,
  3383. height: heightAttr ? heightAttr : viewBoxHeight,
  3384. widthAttr: widthAttr,
  3385. heightAttr: heightAttr,
  3386. svgUid: svgUid
  3387. };
  3388.  
  3389. fabric.gradientDefs[svgUid] = fabric.getGradientDefs(doc);
  3390. fabric.cssRules[svgUid] = fabric.getCSSRules(doc);
  3391. // Precedence of rules: style > class > attribute
  3392.  
  3393. fabric.parseElements(elements, function(instances) {
  3394. fabric.documentParsingTime = new Date() - startTime;
  3395. if (callback) {
  3396. callback(instances, options);
  3397. }
  3398. }, clone(options), reviver);
  3399. };
  3400. })();
  3401.  
  3402. /**
  3403. * Used for caching SVG documents (loaded via `fabric.Canvas#loadSVGFromURL`)
  3404. * @namespace
  3405. */
  3406. var svgCache = {
  3407.  
  3408. /**
  3409. * @param {String} name
  3410. * @param {Function} callback
  3411. */
  3412. has: function (name, callback) {
  3413. callback(false);
  3414. },
  3415.  
  3416. get: function () {
  3417. /* NOOP */
  3418. },
  3419.  
  3420. set: function () {
  3421. /* NOOP */
  3422. }
  3423. };
  3424.  
  3425. /**
  3426. * @private
  3427. */
  3428. function _enlivenCachedObject(cachedObject) {
  3429.  
  3430. var objects = cachedObject.objects,
  3431. options = cachedObject.options;
  3432.  
  3433. objects = objects.map(function (o) {
  3434. return fabric[capitalize(o.type)].fromObject(o);
  3435. });
  3436.  
  3437. return ({ objects: objects, options: options });
  3438. }
  3439.  
  3440. /**
  3441. * @private
  3442. */
  3443. function _createSVGPattern(markup, canvas, property) {
  3444. if (canvas[property] && canvas[property].toSVG) {
  3445. markup.push(
  3446. '<pattern x="0" y="0" id="', property, 'Pattern" ',
  3447. 'width="', canvas[property].source.width,
  3448. '" height="', canvas[property].source.height,
  3449. '" patternUnits="userSpaceOnUse">',
  3450. '<image x="0" y="0" ',
  3451. 'width="', canvas[property].source.width,
  3452. '" height="', canvas[property].source.height,
  3453. '" xlink:href="', canvas[property].source.src,
  3454. '"></image></pattern>'
  3455. );
  3456. }
  3457. }
  3458.  
  3459. extend(fabric, {
  3460.  
  3461. /**
  3462. * Parses an SVG document, returning all of the gradient declarations found in it
  3463. * @static
  3464. * @function
  3465. * @memberOf fabric
  3466. * @param {SVGDocument} doc SVG document to parse
  3467. * @return {Object} Gradient definitions; key corresponds to element id, value -- to gradient definition element
  3468. */
  3469. getGradientDefs: function(doc) {
  3470. var linearGradientEls = doc.getElementsByTagName('linearGradient'),
  3471. radialGradientEls = doc.getElementsByTagName('radialGradient'),
  3472. el, i, j = 0, id, xlink, elList = [ ],
  3473. gradientDefs = { }, idsToXlinkMap = { };
  3474.  
  3475. elList.length = linearGradientEls.length + radialGradientEls.length;
  3476. i = linearGradientEls.length;
  3477. while (i--) {
  3478. elList[j++] = linearGradientEls[i];
  3479. }
  3480. i = radialGradientEls.length;
  3481. while (i--) {
  3482. elList[j++] = radialGradientEls[i];
  3483. }
  3484.  
  3485. while (j--) {
  3486. el = elList[j];
  3487. xlink = el.getAttribute('xlink:href');
  3488. id = el.getAttribute('id');
  3489. if (xlink) {
  3490. idsToXlinkMap[id] = xlink.substr(1);
  3491. }
  3492. gradientDefs[id] = el;
  3493. }
  3494.  
  3495. for (id in idsToXlinkMap) {
  3496. var el2 = gradientDefs[idsToXlinkMap[id]].cloneNode(true);
  3497. el = gradientDefs[id];
  3498. while (el2.firstChild) {
  3499. el.appendChild(el2.firstChild);
  3500. }
  3501. }
  3502. return gradientDefs;
  3503. },
  3504.  
  3505. /**
  3506. * Returns an object of attributes' name/value, given element and an array of attribute names;
  3507. * Parses parent "g" nodes recursively upwards.
  3508. * @static
  3509. * @memberOf fabric
  3510. * @param {DOMElement} element Element to parse
  3511. * @param {Array} attributes Array of attributes to parse
  3512. * @return {Object} object containing parsed attributes' names/values
  3513. */
  3514. parseAttributes: function(element, attributes, svgUid) {
  3515.  
  3516. if (!element) {
  3517. return;
  3518. }
  3519.  
  3520. var value,
  3521. parentAttributes = { };
  3522.  
  3523. if (typeof svgUid === 'undefined') {
  3524. svgUid = element.getAttribute('svgUid');
  3525. }
  3526. // if there's a parent container (`g` or `a` or `symbol` node), parse its attributes recursively upwards
  3527. if (element.parentNode && /^symbol|[g|a]$/i.test(element.parentNode.nodeName)) {
  3528. parentAttributes = fabric.parseAttributes(element.parentNode, attributes, svgUid);
  3529. }
  3530.  
  3531. var ownAttributes = attributes.reduce(function(memo, attr) {
  3532. value = element.getAttribute(attr);
  3533. if (value) {
  3534. attr = normalizeAttr(attr);
  3535. value = normalizeValue(attr, value, parentAttributes);
  3536.  
  3537. memo[attr] = value;
  3538. }
  3539. return memo;
  3540. }, { });
  3541.  
  3542. // add values parsed from style, which take precedence over attributes
  3543. // (see: http://www.w3.org/TR/SVG/styling.html#UsingPresentationAttributes)
  3544. ownAttributes = extend(ownAttributes,
  3545. extend(getGlobalStylesForElement(element, svgUid), fabric.parseStyleAttribute(element)));
  3546.  
  3547. return _setStrokeFillOpacity(extend(parentAttributes, ownAttributes));
  3548. },
  3549.  
  3550. /**
  3551. * Transforms an array of svg elements to corresponding fabric.* instances
  3552. * @static
  3553. * @memberOf fabric
  3554. * @param {Array} elements Array of elements to parse
  3555. * @param {Function} callback Being passed an array of fabric instances (transformed from SVG elements)
  3556. * @param {Object} [options] Options object
  3557. * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
  3558. */
  3559. parseElements: function(elements, callback, options, reviver) {
  3560. new fabric.ElementsParser(elements, callback, options, reviver).parse();
  3561. },
  3562.  
  3563. /**
  3564. * Parses "style" attribute, retuning an object with values
  3565. * @static
  3566. * @memberOf fabric
  3567. * @param {SVGElement} element Element to parse
  3568. * @return {Object} Objects with values parsed from style attribute of an element
  3569. */
  3570. parseStyleAttribute: function(element) {
  3571. var oStyle = { },
  3572. style = element.getAttribute('style');
  3573.  
  3574. if (!style) {
  3575. return oStyle;
  3576. }
  3577.  
  3578. if (typeof style === 'string') {
  3579. parseStyleString(style, oStyle);
  3580. }
  3581. else {
  3582. parseStyleObject(style, oStyle);
  3583. }
  3584.  
  3585. return oStyle;
  3586. },
  3587.  
  3588. /**
  3589. * Parses "points" attribute, returning an array of values
  3590. * @static
  3591. * @memberOf fabric
  3592. * @param {String} points points attribute string
  3593. * @return {Array} array of points
  3594. */
  3595. parsePointsAttribute: function(points) {
  3596.  
  3597. // points attribute is required and must not be empty
  3598. if (!points) {
  3599. return null;
  3600. }
  3601.  
  3602. // replace commas with whitespace and remove bookending whitespace
  3603. points = points.replace(/,/g, ' ').trim();
  3604.  
  3605. points = points.split(/\s+/);
  3606. var parsedPoints = [ ], i, len;
  3607.  
  3608. i = 0;
  3609. len = points.length;
  3610. for (; i < len; i+=2) {
  3611. parsedPoints.push({
  3612. x: parseFloat(points[i]),
  3613. y: parseFloat(points[i + 1])
  3614. });
  3615. }
  3616.  
  3617. // odd number of points is an error
  3618. // if (parsedPoints.length % 2 !== 0) {
  3619. // return null;
  3620. // }
  3621.  
  3622. return parsedPoints;
  3623. },
  3624.  
  3625. /**
  3626. * Returns CSS rules for a given SVG document
  3627. * @static
  3628. * @function
  3629. * @memberOf fabric
  3630. * @param {SVGDocument} doc SVG document to parse
  3631. * @return {Object} CSS rules of this document
  3632. */
  3633. getCSSRules: function(doc) {
  3634. var styles = doc.getElementsByTagName('style'),
  3635. allRules = { }, rules;
  3636.  
  3637. // very crude parsing of style contents
  3638. for (var i = 0, len = styles.length; i < len; i++) {
  3639. var styleContents = styles[i].textContent;
  3640.  
  3641. // remove comments
  3642. styleContents = styleContents.replace(/\/\*[\s\S]*?\*\//g, '');
  3643. if (styleContents.trim() === '') {
  3644. continue;
  3645. }
  3646. rules = styleContents.match(/[^{]*\{[\s\S]*?\}/g);
  3647. rules = rules.map(function(rule) { return rule.trim(); });
  3648.  
  3649. rules.forEach(function(rule) {
  3650.  
  3651. var match = rule.match(/([\s\S]*?)\s*\{([^}]*)\}/),
  3652. ruleObj = { }, declaration = match[2].trim(),
  3653. propertyValuePairs = declaration.replace(/;$/, '').split(/\s*;\s*/);
  3654.  
  3655. for (var i = 0, len = propertyValuePairs.length; i < len; i++) {
  3656. var pair = propertyValuePairs[i].split(/\s*:\s*/),
  3657. property = normalizeAttr(pair[0]),
  3658. value = normalizeValue(property, pair[1], pair[0]);
  3659. ruleObj[property] = value;
  3660. }
  3661. rule = match[1];
  3662. rule.split(',').forEach(function(_rule) {
  3663. allRules[_rule.trim()] = fabric.util.object.clone(ruleObj);
  3664. });
  3665. });
  3666. }
  3667. return allRules;
  3668. },
  3669.  
  3670. /**
  3671. * 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)
  3672. * @memberof fabric
  3673. * @param {String} url
  3674. * @param {Function} callback
  3675. * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
  3676. */
  3677. loadSVGFromURL: function(url, callback, reviver) {
  3678.  
  3679. url = url.replace(/^\n\s*/, '').trim();
  3680. svgCache.has(url, function (hasUrl) {
  3681. if (hasUrl) {
  3682. svgCache.get(url, function (value) {
  3683. var enlivedRecord = _enlivenCachedObject(value);
  3684. callback(enlivedRecord.objects, enlivedRecord.options);
  3685. });
  3686. }
  3687. else {
  3688. new fabric.util.request(url, {
  3689. method: 'get',
  3690. onComplete: onComplete
  3691. });
  3692. }
  3693. });
  3694.  
  3695. function onComplete(r) {
  3696.  
  3697. var xml = r.responseXML;
  3698. if (xml && !xml.documentElement && fabric.window.ActiveXObject && r.responseText) {
  3699. xml = new ActiveXObject('Microsoft.XMLDOM');
  3700. xml.async = 'false';
  3701. //IE chokes on DOCTYPE
  3702. xml.loadXML(r.responseText.replace(/<!DOCTYPE[\s\S]*?(\[[\s\S]*\])*?>/i, ''));
  3703. }
  3704. if (!xml || !xml.documentElement) {
  3705. return;
  3706. }
  3707.  
  3708. fabric.parseSVGDocument(xml.documentElement, function (results, options) {
  3709. svgCache.set(url, {
  3710. objects: fabric.util.array.invoke(results, 'toObject'),
  3711. options: options
  3712. });
  3713. callback(results, options);
  3714. }, reviver);
  3715. }
  3716. },
  3717.  
  3718. /**
  3719. * Takes string corresponding to an SVG document, and parses it into a set of fabric objects
  3720. * @memberof fabric
  3721. * @param {String} string
  3722. * @param {Function} callback
  3723. * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
  3724. */
  3725. loadSVGFromString: function(string, callback, reviver) {
  3726. string = string.trim();
  3727. var doc;
  3728. if (typeof DOMParser !== 'undefined') {
  3729. var parser = new DOMParser();
  3730. if (parser && parser.parseFromString) {
  3731. doc = parser.parseFromString(string, 'text/xml');
  3732. }
  3733. }
  3734. else if (fabric.window.ActiveXObject) {
  3735. doc = new ActiveXObject('Microsoft.XMLDOM');
  3736. doc.async = 'false';
  3737. // IE chokes on DOCTYPE
  3738. doc.loadXML(string.replace(/<!DOCTYPE[\s\S]*?(\[[\s\S]*\])*?>/i, ''));
  3739. }
  3740.  
  3741. fabric.parseSVGDocument(doc.documentElement, function (results, options) {
  3742. callback(results, options);
  3743. }, reviver);
  3744. },
  3745.  
  3746. /**
  3747. * Creates markup containing SVG font faces
  3748. * @param {Array} objects Array of fabric objects
  3749. * @return {String}
  3750. */
  3751. createSVGFontFacesMarkup: function(objects) {
  3752. var markup = '';
  3753.  
  3754. for (var i = 0, len = objects.length; i < len; i++) {
  3755. if (objects[i].type !== 'text' || !objects[i].path) {
  3756. continue;
  3757. }
  3758.  
  3759. markup += [
  3760. //jscs:disable validateIndentation
  3761. '@font-face {',
  3762. 'font-family: ', objects[i].fontFamily, '; ',
  3763. 'src: url(\'', objects[i].path, '\')',
  3764. '}'
  3765. //jscs:enable validateIndentation
  3766. ].join('');
  3767. }
  3768.  
  3769. if (markup) {
  3770. markup = [
  3771. //jscs:disable validateIndentation
  3772. '<style type="text/css">',
  3773. '<![CDATA[',
  3774. markup,
  3775. ']]>',
  3776. '</style>'
  3777. //jscs:enable validateIndentation
  3778. ].join('');
  3779. }
  3780.  
  3781. return markup;
  3782. },
  3783.  
  3784. /**
  3785. * Creates markup containing SVG referenced elements like patterns, gradients etc.
  3786. * @param {fabric.Canvas} canvas instance of fabric.Canvas
  3787. * @return {String}
  3788. */
  3789. createSVGRefElementsMarkup: function(canvas) {
  3790. var markup = [ ];
  3791.  
  3792. _createSVGPattern(markup, canvas, 'backgroundColor');
  3793. _createSVGPattern(markup, canvas, 'overlayColor');
  3794.  
  3795. return markup.join('');
  3796. }
  3797. });
  3798.  
  3799. })(typeof exports !== 'undefined' ? exports : this);
  3800.  
  3801.  
  3802. fabric.ElementsParser = function(elements, callback, options, reviver) {
  3803. this.elements = elements;
  3804. this.callback = callback;
  3805. this.options = options;
  3806. this.reviver = reviver;
  3807. this.svgUid = (options && options.svgUid) || 0;
  3808. };
  3809.  
  3810. fabric.ElementsParser.prototype.parse = function() {
  3811. this.instances = new Array(this.elements.length);
  3812. this.numElements = this.elements.length;
  3813.  
  3814. this.createObjects();
  3815. };
  3816.  
  3817. fabric.ElementsParser.prototype.createObjects = function() {
  3818. for (var i = 0, len = this.elements.length; i < len; i++) {
  3819. this.elements[i].setAttribute('svgUid', this.svgUid);
  3820. (function(_this, i) {
  3821. setTimeout(function() {
  3822. _this.createObject(_this.elements[i], i);
  3823. }, 0);
  3824. })(this, i);
  3825. }
  3826. };
  3827.  
  3828. fabric.ElementsParser.prototype.createObject = function(el, index) {
  3829. var klass = fabric[fabric.util.string.capitalize(el.tagName)];
  3830. if (klass && klass.fromElement) {
  3831. try {
  3832. this._createObject(klass, el, index);
  3833. }
  3834. catch (err) {
  3835. fabric.log(err);
  3836. }
  3837. }
  3838. else {
  3839. this.checkIfDone();
  3840. }
  3841. };
  3842.  
  3843. fabric.ElementsParser.prototype._createObject = function(klass, el, index) {
  3844. if (klass.async) {
  3845. klass.fromElement(el, this.createCallback(index, el), this.options);
  3846. }
  3847. else {
  3848. var obj = klass.fromElement(el, this.options);
  3849. this.resolveGradient(obj, 'fill');
  3850. this.resolveGradient(obj, 'stroke');
  3851. this.reviver && this.reviver(el, obj);
  3852. this.instances[index] = obj;
  3853. this.checkIfDone();
  3854. }
  3855. };
  3856.  
  3857. fabric.ElementsParser.prototype.createCallback = function(index, el) {
  3858. var _this = this;
  3859. return function(obj) {
  3860. _this.resolveGradient(obj, 'fill');
  3861. _this.resolveGradient(obj, 'stroke');
  3862. _this.reviver && _this.reviver(el, obj);
  3863. _this.instances[index] = obj;
  3864. _this.checkIfDone();
  3865. };
  3866. };
  3867.  
  3868. fabric.ElementsParser.prototype.resolveGradient = function(obj, property) {
  3869.  
  3870. var instanceFillValue = obj.get(property);
  3871. if (!(/^url\(/).test(instanceFillValue)) {
  3872. return;
  3873. }
  3874. var gradientId = instanceFillValue.slice(5, instanceFillValue.length - 1);
  3875. if (fabric.gradientDefs[this.svgUid][gradientId]) {
  3876. obj.set(property,
  3877. fabric.Gradient.fromElement(fabric.gradientDefs[this.svgUid][gradientId], obj));
  3878. }
  3879. };
  3880.  
  3881. fabric.ElementsParser.prototype.checkIfDone = function() {
  3882. if (--this.numElements === 0) {
  3883. this.instances = this.instances.filter(function(el) {
  3884. return el != null;
  3885. });
  3886. this.callback(this.instances);
  3887. }
  3888. };
  3889.  
  3890.  
  3891. (function(global) {
  3892.  
  3893. 'use strict';
  3894.  
  3895. /* Adaptation of work of Kevin Lindsey (kevin@kevlindev.com) */
  3896.  
  3897. var fabric = global.fabric || (global.fabric = { });
  3898.  
  3899. if (fabric.Point) {
  3900. fabric.warn('fabric.Point is already defined');
  3901. return;
  3902. }
  3903.  
  3904. fabric.Point = Point;
  3905.  
  3906. /**
  3907. * Point class
  3908. * @class fabric.Point
  3909. * @memberOf fabric
  3910. * @constructor
  3911. * @param {Number} x
  3912. * @param {Number} y
  3913. * @return {fabric.Point} thisArg
  3914. */
  3915. function Point(x, y) {
  3916. this.x = x;
  3917. this.y = y;
  3918. }
  3919.  
  3920. Point.prototype = /** @lends fabric.Point.prototype */ {
  3921.  
  3922. constructor: Point,
  3923.  
  3924. /**
  3925. * Adds another point to this one and returns another one
  3926. * @param {fabric.Point} that
  3927. * @return {fabric.Point} new Point instance with added values
  3928. */
  3929. add: function (that) {
  3930. return new Point(this.x + that.x, this.y + that.y);
  3931. },
  3932.  
  3933. /**
  3934. * Adds another point to this one
  3935. * @param {fabric.Point} that
  3936. * @return {fabric.Point} thisArg
  3937. */
  3938. addEquals: function (that) {
  3939. this.x += that.x;
  3940. this.y += that.y;
  3941. return this;
  3942. },
  3943.  
  3944. /**
  3945. * Adds value to this point and returns a new one
  3946. * @param {Number} scalar
  3947. * @return {fabric.Point} new Point with added value
  3948. */
  3949. scalarAdd: function (scalar) {
  3950. return new Point(this.x + scalar, this.y + scalar);
  3951. },
  3952.  
  3953. /**
  3954. * Adds value to this point
  3955. * @param {Number} scalar
  3956. * @return {fabric.Point} thisArg
  3957. */
  3958. scalarAddEquals: function (scalar) {
  3959. this.x += scalar;
  3960. this.y += scalar;
  3961. return this;
  3962. },
  3963.  
  3964. /**
  3965. * Subtracts another point from this point and returns a new one
  3966. * @param {fabric.Point} that
  3967. * @return {fabric.Point} new Point object with subtracted values
  3968. */
  3969. subtract: function (that) {
  3970. return new Point(this.x - that.x, this.y - that.y);
  3971. },
  3972.  
  3973. /**
  3974. * Subtracts another point from this point
  3975. * @param {fabric.Point} that
  3976. * @return {fabric.Point} thisArg
  3977. */
  3978. subtractEquals: function (that) {
  3979. this.x -= that.x;
  3980. this.y -= that.y;
  3981. return this;
  3982. },
  3983.  
  3984. /**
  3985. * Subtracts value from this point and returns a new one
  3986. * @param {Number} scalar
  3987. * @return {fabric.Point}
  3988. */
  3989. scalarSubtract: function (scalar) {
  3990. return new Point(this.x - scalar, this.y - scalar);
  3991. },
  3992.  
  3993. /**
  3994. * Subtracts value from this point
  3995. * @param {Number} scalar
  3996. * @return {fabric.Point} thisArg
  3997. */
  3998. scalarSubtractEquals: function (scalar) {
  3999. this.x -= scalar;
  4000. this.y -= scalar;
  4001. return this;
  4002. },
  4003.  
  4004. /**
  4005. * Miltiplies this point by a value and returns a new one
  4006. * @param {Number} scalar
  4007. * @return {fabric.Point}
  4008. */
  4009. multiply: function (scalar) {
  4010. return new Point(this.x * scalar, this.y * scalar);
  4011. },
  4012.  
  4013. /**
  4014. * Miltiplies this point by a value
  4015. * @param {Number} scalar
  4016. * @return {fabric.Point} thisArg
  4017. */
  4018. multiplyEquals: function (scalar) {
  4019. this.x *= scalar;
  4020. this.y *= scalar;
  4021. return this;
  4022. },
  4023.  
  4024. /**
  4025. * Divides this point by a value and returns a new one
  4026. * @param {Number} scalar
  4027. * @return {fabric.Point}
  4028. */
  4029. divide: function (scalar) {
  4030. return new Point(this.x / scalar, this.y / scalar);
  4031. },
  4032.  
  4033. /**
  4034. * Divides this point by a value
  4035. * @param {Number} scalar
  4036. * @return {fabric.Point} thisArg
  4037. */
  4038. divideEquals: function (scalar) {
  4039. this.x /= scalar;
  4040. this.y /= scalar;
  4041. return this;
  4042. },
  4043.  
  4044. /**
  4045. * Returns true if this point is equal to another one
  4046. * @param {fabric.Point} that
  4047. * @return {Boolean}
  4048. */
  4049. eq: function (that) {
  4050. return (this.x === that.x && this.y === that.y);
  4051. },
  4052.  
  4053. /**
  4054. * Returns true if this point is less than another one
  4055. * @param {fabric.Point} that
  4056. * @return {Boolean}
  4057. */
  4058. lt: function (that) {
  4059. return (this.x < that.x && this.y < that.y);
  4060. },
  4061.  
  4062. /**
  4063. * Returns true if this point is less than or equal to another one
  4064. * @param {fabric.Point} that
  4065. * @return {Boolean}
  4066. */
  4067. lte: function (that) {
  4068. return (this.x <= that.x && this.y <= that.y);
  4069. },
  4070.  
  4071. /**
  4072.  
  4073. * Returns true if this point is greater another one
  4074. * @param {fabric.Point} that
  4075. * @return {Boolean}
  4076. */
  4077. gt: function (that) {
  4078. return (this.x > that.x && this.y > that.y);
  4079. },
  4080.  
  4081. /**
  4082. * Returns true if this point is greater than or equal to another one
  4083. * @param {fabric.Point} that
  4084. * @return {Boolean}
  4085. */
  4086. gte: function (that) {
  4087. return (this.x >= that.x && this.y >= that.y);
  4088. },
  4089.  
  4090. /**
  4091. * Returns new point which is the result of linear interpolation with this one and another one
  4092. * @param {fabric.Point} that
  4093. * @param {Number} t
  4094. * @return {fabric.Point}
  4095. */
  4096. lerp: function (that, t) {
  4097. return new Point(this.x + (that.x - this.x) * t, this.y + (that.y - this.y) * t);
  4098. },
  4099.  
  4100. /**
  4101. * Returns distance from this point and another one
  4102. * @param {fabric.Point} that
  4103. * @return {Number}
  4104. */
  4105. distanceFrom: function (that) {
  4106. var dx = this.x - that.x,
  4107. dy = this.y - that.y;
  4108. return Math.sqrt(dx * dx + dy * dy);
  4109. },
  4110.  
  4111. /**
  4112. * Returns the point between this point and another one
  4113. * @param {fabric.Point} that
  4114. * @return {fabric.Point}
  4115. */
  4116. midPointFrom: function (that) {
  4117. return new Point(this.x + (that.x - this.x)/2, this.y + (that.y - this.y)/2);
  4118. },
  4119.  
  4120. /**
  4121. * Returns a new point which is the min of this and another one
  4122. * @param {fabric.Point} that
  4123. * @return {fabric.Point}
  4124. */
  4125. min: function (that) {
  4126. return new Point(Math.min(this.x, that.x), Math.min(this.y, that.y));
  4127. },
  4128.  
  4129. /**
  4130. * Returns a new point which is the max of this and another one
  4131. * @param {fabric.Point} that
  4132. * @return {fabric.Point}
  4133. */
  4134. max: function (that) {
  4135. return new Point(Math.max(this.x, that.x), Math.max(this.y, that.y));
  4136. },
  4137.  
  4138. /**
  4139. * Returns string representation of this point
  4140. * @return {String}
  4141. */
  4142. toString: function () {
  4143. return this.x + ',' + this.y;
  4144. },
  4145.  
  4146. /**
  4147. * Sets x/y of this point
  4148. * @param {Number} x
  4149. * @return {Number} y
  4150. */
  4151. setXY: function (x, y) {
  4152. this.x = x;
  4153. this.y = y;
  4154. },
  4155.  
  4156. /**
  4157. * Sets x/y of this point from another point
  4158. * @param {fabric.Point} that
  4159. */
  4160. setFromPoint: function (that) {
  4161. this.x = that.x;
  4162. this.y = that.y;
  4163. },
  4164.  
  4165. /**
  4166. * Swaps x/y of this point and another point
  4167. * @param {fabric.Point} that
  4168. */
  4169. swap: function (that) {
  4170. var x = this.x,
  4171. y = this.y;
  4172. this.x = that.x;
  4173. this.y = that.y;
  4174. that.x = x;
  4175. that.y = y;
  4176. }
  4177. };
  4178.  
  4179. })(typeof exports !== 'undefined' ? exports : this);
  4180.  
  4181.  
  4182. (function(global) {
  4183.  
  4184. 'use strict';
  4185.  
  4186. /* Adaptation of work of Kevin Lindsey (kevin@kevlindev.com) */
  4187. var fabric = global.fabric || (global.fabric = { });
  4188.  
  4189. if (fabric.Intersection) {
  4190. fabric.warn('fabric.Intersection is already defined');
  4191. return;
  4192. }
  4193.  
  4194. /**
  4195. * Intersection class
  4196. * @class fabric.Intersection
  4197. * @memberOf fabric
  4198. * @constructor
  4199. */
  4200. function Intersection(status) {
  4201. this.status = status;
  4202. this.points = [];
  4203. }
  4204.  
  4205. fabric.Intersection = Intersection;
  4206.  
  4207. fabric.Intersection.prototype = /** @lends fabric.Intersection.prototype */ {
  4208.  
  4209. /**
  4210. * Appends a point to intersection
  4211. * @param {fabric.Point} point
  4212. */
  4213. appendPoint: function (point) {
  4214. this.points.push(point);
  4215. },
  4216.  
  4217. /**
  4218. * Appends points to intersection
  4219. * @param {Array} points
  4220. */
  4221. appendPoints: function (points) {
  4222. this.points = this.points.concat(points);
  4223. }
  4224. };
  4225.  
  4226. /**
  4227. * Checks if one line intersects another
  4228. * @static
  4229. * @param {fabric.Point} a1
  4230. * @param {fabric.Point} a2
  4231. * @param {fabric.Point} b1
  4232. * @param {fabric.Point} b2
  4233. * @return {fabric.Intersection}
  4234. */
  4235. fabric.Intersection.intersectLineLine = function (a1, a2, b1, b2) {
  4236. var result,
  4237. uaT = (b2.x - b1.x) * (a1.y - b1.y) - (b2.y - b1.y) * (a1.x - b1.x),
  4238. ubT = (a2.x - a1.x) * (a1.y - b1.y) - (a2.y - a1.y) * (a1.x - b1.x),
  4239. uB = (b2.y - b1.y) * (a2.x - a1.x) - (b2.x - b1.x) * (a2.y - a1.y);
  4240. if (uB !== 0) {
  4241. var ua = uaT / uB,
  4242. ub = ubT / uB;
  4243. if (0 <= ua && ua <= 1 && 0 <= ub && ub <= 1) {
  4244. result = new Intersection('Intersection');
  4245. result.points.push(new fabric.Point(a1.x + ua * (a2.x - a1.x), a1.y + ua * (a2.y - a1.y)));
  4246. }
  4247. else {
  4248. result = new Intersection();
  4249. }
  4250. }
  4251. else {
  4252. if (uaT === 0 || ubT === 0) {
  4253. result = new Intersection('Coincident');
  4254. }
  4255. else {
  4256. result = new Intersection('Parallel');
  4257. }
  4258. }
  4259. return result;
  4260. };
  4261.  
  4262. /**
  4263. * Checks if line intersects polygon
  4264. * @static
  4265. * @param {fabric.Point} a1
  4266. * @param {fabric.Point} a2
  4267. * @param {Array} points
  4268. * @return {fabric.Intersection}
  4269. */
  4270. fabric.Intersection.intersectLinePolygon = function(a1, a2, points) {
  4271. var result = new Intersection(),
  4272. length = points.length;
  4273.  
  4274. for (var i = 0; i < length; i++) {
  4275. var b1 = points[i],
  4276. b2 = points[(i + 1) % length],
  4277. inter = Intersection.intersectLineLine(a1, a2, b1, b2);
  4278.  
  4279. result.appendPoints(inter.points);
  4280. }
  4281. if (result.points.length > 0) {
  4282. result.status = 'Intersection';
  4283. }
  4284. return result;
  4285. };
  4286.  
  4287. /**
  4288. * Checks if polygon intersects another polygon
  4289. * @static
  4290. * @param {Array} points1
  4291. * @param {Array} points2
  4292. * @return {fabric.Intersection}
  4293. */
  4294. fabric.Intersection.intersectPolygonPolygon = function (points1, points2) {
  4295. var result = new Intersection(),
  4296. length = points1.length;
  4297.  
  4298. for (var i = 0; i < length; i++) {
  4299. var a1 = points1[i],
  4300. a2 = points1[(i + 1) % length],
  4301. inter = Intersection.intersectLinePolygon(a1, a2, points2);
  4302.  
  4303. result.appendPoints(inter.points);
  4304. }
  4305. if (result.points.length > 0) {
  4306. result.status = 'Intersection';
  4307. }
  4308. return result;
  4309. };
  4310.  
  4311. /**
  4312. * Checks if polygon intersects rectangle
  4313. * @static
  4314. * @param {Array} points
  4315. * @param {Number} r1
  4316. * @param {Number} r2
  4317. * @return {fabric.Intersection}
  4318. */
  4319. fabric.Intersection.intersectPolygonRectangle = function (points, r1, r2) {
  4320. var min = r1.min(r2),
  4321. max = r1.max(r2),
  4322. topRight = new fabric.Point(max.x, min.y),
  4323. bottomLeft = new fabric.Point(min.x, max.y),
  4324. inter1 = Intersection.intersectLinePolygon(min, topRight, points),
  4325. inter2 = Intersection.intersectLinePolygon(topRight, max, points),
  4326. inter3 = Intersection.intersectLinePolygon(max, bottomLeft, points),
  4327. inter4 = Intersection.intersectLinePolygon(bottomLeft, min, points),
  4328. result = new Intersection();
  4329.  
  4330. result.appendPoints(inter1.points);
  4331. result.appendPoints(inter2.points);
  4332. result.appendPoints(inter3.points);
  4333. result.appendPoints(inter4.points);
  4334.  
  4335. if (result.points.length > 0) {
  4336. result.status = 'Intersection';
  4337. }
  4338. return result;
  4339. };
  4340.  
  4341. })(typeof exports !== 'undefined' ? exports : this);
  4342.  
  4343.  
  4344. (function(global) {
  4345.  
  4346. 'use strict';
  4347.  
  4348. var fabric = global.fabric || (global.fabric = { });
  4349.  
  4350. if (fabric.Color) {
  4351. fabric.warn('fabric.Color is already defined.');
  4352. return;
  4353. }
  4354.  
  4355. /**
  4356. * Color class
  4357. * The purpose of {@link fabric.Color} is to abstract and encapsulate common color operations;
  4358. * {@link fabric.Color} is a constructor and creates instances of {@link fabric.Color} objects.
  4359. *
  4360. * @class fabric.Color
  4361. * @param {String} color optional in hex or rgb(a) format
  4362. * @return {fabric.Color} thisArg
  4363. * @tutorial {@link http://fabricjs.com/fabric-intro-part-2/#colors}
  4364. */
  4365. function Color(color) {
  4366. if (!color) {
  4367. this.setSource([0, 0, 0, 1]);
  4368. }
  4369. else {
  4370. this._tryParsingColor(color);
  4371. }
  4372. }
  4373.  
  4374. fabric.Color = Color;
  4375.  
  4376. fabric.Color.prototype = /** @lends fabric.Color.prototype */ {
  4377.  
  4378. /**
  4379. * @private
  4380. * @param {String|Array} color Color value to parse
  4381. */
  4382. _tryParsingColor: function(color) {
  4383. var source;
  4384.  
  4385. if (color in Color.colorNameMap) {
  4386. color = Color.colorNameMap[color];
  4387. }
  4388.  
  4389. if (color === 'transparent') {
  4390. this.setSource([255, 255, 255, 0]);
  4391. return;
  4392. }
  4393.  
  4394. source = Color.sourceFromHex(color);
  4395.  
  4396. if (!source) {
  4397. source = Color.sourceFromRgb(color);
  4398. }
  4399. if (!source) {
  4400. source = Color.sourceFromHsl(color);
  4401. }
  4402. if (source) {
  4403. this.setSource(source);
  4404. }
  4405. },
  4406.  
  4407. /**
  4408. * Adapted from <a href="https://rawgithub.com/mjijackson/mjijackson.github.com/master/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript.html">https://github.com/mjijackson</a>
  4409. * @private
  4410. * @param {Number} r Red color value
  4411. * @param {Number} g Green color value
  4412. * @param {Number} b Blue color value
  4413. * @return {Array} Hsl color
  4414. */
  4415. _rgbToHsl: function(r, g, b) {
  4416. r /= 255, g /= 255, b /= 255;
  4417.  
  4418. var h, s, l,
  4419. max = fabric.util.array.max([r, g, b]),
  4420. min = fabric.util.array.min([r, g, b]);
  4421.  
  4422. l = (max + min) / 2;
  4423.  
  4424. if (max === min) {
  4425. h = s = 0; // achromatic
  4426. }
  4427. else {
  4428. var d = max - min;
  4429. s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
  4430. switch (max) {
  4431. case r:
  4432. h = (g - b) / d + (g < b ? 6 : 0);
  4433. break;
  4434. case g:
  4435. h = (b - r) / d + 2;
  4436. break;
  4437. case b:
  4438. h = (r - g) / d + 4;
  4439. break;
  4440. }
  4441. h /= 6;
  4442. }
  4443.  
  4444. return [
  4445. Math.round(h * 360),
  4446. Math.round(s * 100),
  4447. Math.round(l * 100)
  4448. ];
  4449. },
  4450.  
  4451. /**
  4452. * Returns source of this color (where source is an array representation; ex: [200, 200, 100, 1])
  4453. * @return {Array}
  4454. */
  4455. getSource: function() {
  4456. return this._source;
  4457. },
  4458.  
  4459. /**
  4460. * Sets source of this color (where source is an array representation; ex: [200, 200, 100, 1])
  4461. * @param {Array} source
  4462. */
  4463. setSource: function(source) {
  4464. this._source = source;
  4465. },
  4466.  
  4467. /**
  4468. * Returns color represenation in RGB format
  4469. * @return {String} ex: rgb(0-255,0-255,0-255)
  4470. */
  4471. toRgb: function() {
  4472. var source = this.getSource();
  4473. return 'rgb(' + source[0] + ',' + source[1] + ',' + source[2] + ')';
  4474. },
  4475.  
  4476. /**
  4477. * Returns color represenation in RGBA format
  4478. * @return {String} ex: rgba(0-255,0-255,0-255,0-1)
  4479. */
  4480. toRgba: function() {
  4481. var source = this.getSource();
  4482. return 'rgba(' + source[0] + ',' + source[1] + ',' + source[2] + ',' + source[3] + ')';
  4483. },
  4484.  
  4485. /**
  4486. * Returns color represenation in HSL format
  4487. * @return {String} ex: hsl(0-360,0%-100%,0%-100%)
  4488. */
  4489. toHsl: function() {
  4490. var source = this.getSource(),
  4491. hsl = this._rgbToHsl(source[0], source[1], source[2]);
  4492.  
  4493. return 'hsl(' + hsl[0] + ',' + hsl[1] + '%,' + hsl[2] + '%)';
  4494. },
  4495.  
  4496. /**
  4497. * Returns color represenation in HSLA format
  4498. * @return {String} ex: hsla(0-360,0%-100%,0%-100%,0-1)
  4499. */
  4500. toHsla: function() {
  4501. var source = this.getSource(),
  4502. hsl = this._rgbToHsl(source[0], source[1], source[2]);
  4503.  
  4504. return 'hsla(' + hsl[0] + ',' + hsl[1] + '%,' + hsl[2] + '%,' + source[3] + ')';
  4505. },
  4506.  
  4507. /**
  4508. * Returns color represenation in HEX format
  4509. * @return {String} ex: FF5555
  4510. */
  4511. toHex: function() {
  4512. var source = this.getSource(), r, g, b;
  4513.  
  4514. r = source[0].toString(16);
  4515. r = (r.length === 1) ? ('0' + r) : r;
  4516.  
  4517. g = source[1].toString(16);
  4518. g = (g.length === 1) ? ('0' + g) : g;
  4519.  
  4520. b = source[2].toString(16);
  4521. b = (b.length === 1) ? ('0' + b) : b;
  4522.  
  4523. return r.toUpperCase() + g.toUpperCase() + b.toUpperCase();
  4524. },
  4525.  
  4526. /**
  4527. * Gets value of alpha channel for this color
  4528. * @return {Number} 0-1
  4529. */
  4530. getAlpha: function() {
  4531. return this.getSource()[3];
  4532. },
  4533.  
  4534. /**
  4535. * Sets value of alpha channel for this color
  4536. * @param {Number} alpha Alpha value 0-1
  4537. * @return {fabric.Color} thisArg
  4538. */
  4539. setAlpha: function(alpha) {
  4540. var source = this.getSource();
  4541. source[3] = alpha;
  4542. this.setSource(source);
  4543. return this;
  4544. },
  4545.  
  4546. /**
  4547. * Transforms color to its grayscale representation
  4548. * @return {fabric.Color} thisArg
  4549. */
  4550. toGrayscale: function() {
  4551. var source = this.getSource(),
  4552. average = parseInt((source[0] * 0.3 + source[1] * 0.59 + source[2] * 0.11).toFixed(0), 10),
  4553. currentAlpha = source[3];
  4554. this.setSource([average, average, average, currentAlpha]);
  4555. return this;
  4556. },
  4557.  
  4558. /**
  4559. * Transforms color to its black and white representation
  4560. * @param {Number} threshold
  4561. * @return {fabric.Color} thisArg
  4562. */
  4563. toBlackWhite: function(threshold) {
  4564. var source = this.getSource(),
  4565. average = (source[0] * 0.3 + source[1] * 0.59 + source[2] * 0.11).toFixed(0),
  4566. currentAlpha = source[3];
  4567.  
  4568. threshold = threshold || 127;
  4569.  
  4570. average = (Number(average) < Number(threshold)) ? 0 : 255;
  4571. this.setSource([average, average, average, currentAlpha]);
  4572. return this;
  4573. },
  4574.  
  4575. /**
  4576. * Overlays color with another color
  4577. * @param {String|fabric.Color} otherColor
  4578. * @return {fabric.Color} thisArg
  4579. */
  4580. overlayWith: function(otherColor) {
  4581. if (!(otherColor instanceof Color)) {
  4582. otherColor = new Color(otherColor);
  4583. }
  4584.  
  4585. var result = [],
  4586. alpha = this.getAlpha(),
  4587. otherAlpha = 0.5,
  4588. source = this.getSource(),
  4589. otherSource = otherColor.getSource();
  4590.  
  4591. for (var i = 0; i < 3; i++) {
  4592. result.push(Math.round((source[i] * (1 - otherAlpha)) + (otherSource[i] * otherAlpha)));
  4593. }
  4594.  
  4595. result[3] = alpha;
  4596. this.setSource(result);
  4597. return this;
  4598. }
  4599. };
  4600.  
  4601. /**
  4602. * 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))
  4603. * @static
  4604. * @field
  4605. * @memberOf fabric.Color
  4606. */
  4607. fabric.Color.reRGBa = /^rgba?\(\s*(\d{1,3}(?:\.\d+)?\%?)\s*,\s*(\d{1,3}(?:\.\d+)?\%?)\s*,\s*(\d{1,3}(?:\.\d+)?\%?)\s*(?:\s*,\s*(\d+(?:\.\d+)?)\s*)?\)$/;
  4608.  
  4609. /**
  4610. * 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 ))
  4611. * @static
  4612. * @field
  4613. * @memberOf fabric.Color
  4614. */
  4615. fabric.Color.reHSLa = /^hsla?\(\s*(\d{1,3})\s*,\s*(\d{1,3}\%)\s*,\s*(\d{1,3}\%)\s*(?:\s*,\s*(\d+(?:\.\d+)?)\s*)?\)$/;
  4616.  
  4617. /**
  4618. * Regex matching color in HEX format (ex: #FF5555, 010155, aff)
  4619. * @static
  4620. * @field
  4621. * @memberOf fabric.Color
  4622. */
  4623. fabric.Color.reHex = /^#?([0-9a-f]{6}|[0-9a-f]{3})$/i;
  4624.  
  4625. /**
  4626. * Map of the 17 basic color names with HEX code
  4627. * @static
  4628. * @field
  4629. * @memberOf fabric.Color
  4630. * @see: http://www.w3.org/TR/CSS2/syndata.html#color-units
  4631. */
  4632. fabric.Color.colorNameMap = {
  4633. aqua: '#00FFFF',
  4634. black: '#000000',
  4635. blue: '#0000FF',
  4636. fuchsia: '#FF00FF',
  4637. gray: '#808080',
  4638. green: '#008000',
  4639. lime: '#00FF00',
  4640. maroon: '#800000',
  4641. navy: '#000080',
  4642. olive: '#808000',
  4643. orange: '#FFA500',
  4644. purple: '#800080',
  4645. red: '#FF0000',
  4646. silver: '#C0C0C0',
  4647. teal: '#008080',
  4648. white: '#FFFFFF',
  4649. yellow: '#FFFF00'
  4650. };
  4651.  
  4652. /**
  4653. * @private
  4654. * @param {Number} p
  4655. * @param {Number} q
  4656. * @param {Number} t
  4657. * @return {Number}
  4658. */
  4659. function hue2rgb(p, q, t) {
  4660. if (t < 0) {
  4661. t += 1;
  4662. }
  4663. if (t > 1) {
  4664. t -= 1;
  4665. }
  4666. if (t < 1/6) {
  4667. return p + (q - p) * 6 * t;
  4668. }
  4669. if (t < 1/2) {
  4670. return q;
  4671. }
  4672. if (t < 2/3) {
  4673. return p + (q - p) * (2/3 - t) * 6;
  4674. }
  4675. return p;
  4676. }
  4677.  
  4678. /**
  4679. * Returns new color object, when given a color in RGB format
  4680. * @memberOf fabric.Color
  4681. * @param {String} color Color value ex: rgb(0-255,0-255,0-255)
  4682. * @return {fabric.Color}
  4683. */
  4684. fabric.Color.fromRgb = function(color) {
  4685. return Color.fromSource(Color.sourceFromRgb(color));
  4686. };
  4687.  
  4688. /**
  4689. * Returns array represenatation (ex: [100, 100, 200, 1]) of a color that's in RGB or RGBA format
  4690. * @memberOf fabric.Color
  4691. * @param {String} color Color value ex: rgb(0-255,0-255,0-255), rgb(0%-100%,0%-100%,0%-100%)
  4692. * @return {Array} source
  4693. */
  4694. fabric.Color.sourceFromRgb = function(color) {
  4695. var match = color.match(Color.reRGBa);
  4696. if (match) {
  4697. var r = parseInt(match[1], 10) / (/%$/.test(match[1]) ? 100 : 1) * (/%$/.test(match[1]) ? 255 : 1),
  4698. g = parseInt(match[2], 10) / (/%$/.test(match[2]) ? 100 : 1) * (/%$/.test(match[2]) ? 255 : 1),
  4699. b = parseInt(match[3], 10) / (/%$/.test(match[3]) ? 100 : 1) * (/%$/.test(match[3]) ? 255 : 1);
  4700.  
  4701. return [
  4702. parseInt(r, 10),
  4703. parseInt(g, 10),
  4704. parseInt(b, 10),
  4705. match[4] ? parseFloat(match[4]) : 1
  4706. ];
  4707. }
  4708. };
  4709.  
  4710. /**
  4711. * Returns new color object, when given a color in RGBA format
  4712. * @static
  4713. * @function
  4714. * @memberOf fabric.Color
  4715. * @param {String} color
  4716. * @return {fabric.Color}
  4717. */
  4718. fabric.Color.fromRgba = Color.fromRgb;
  4719.  
  4720. /**
  4721. * Returns new color object, when given a color in HSL format
  4722. * @param {String} color Color value ex: hsl(0-260,0%-100%,0%-100%)
  4723. * @memberOf fabric.Color
  4724. * @return {fabric.Color}
  4725. */
  4726. fabric.Color.fromHsl = function(color) {
  4727. return Color.fromSource(Color.sourceFromHsl(color));
  4728. };
  4729.  
  4730. /**
  4731. * Returns array represenatation (ex: [100, 100, 200, 1]) of a color that's in HSL or HSLA format.
  4732. * Adapted from <a href="https://rawgithub.com/mjijackson/mjijackson.github.com/master/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript.html">https://github.com/mjijackson</a>
  4733. * @memberOf fabric.Color
  4734. * @param {String} color Color value ex: hsl(0-360,0%-100%,0%-100%) or hsla(0-360,0%-100%,0%-100%, 0-1)
  4735. * @return {Array} source
  4736. * @see http://http://www.w3.org/TR/css3-color/#hsl-color
  4737. */
  4738. fabric.Color.sourceFromHsl = function(color) {
  4739. var match = color.match(Color.reHSLa);
  4740. if (!match) {
  4741. return;
  4742. }
  4743.  
  4744. var h = (((parseFloat(match[1]) % 360) + 360) % 360) / 360,
  4745. s = parseFloat(match[2]) / (/%$/.test(match[2]) ? 100 : 1),
  4746. l = parseFloat(match[3]) / (/%$/.test(match[3]) ? 100 : 1),
  4747. r, g, b;
  4748.  
  4749. if (s === 0) {
  4750. r = g = b = l;
  4751. }
  4752. else {
  4753. var q = l <= 0.5 ? l * (s + 1) : l + s - l * s,
  4754. p = l * 2 - q;
  4755.  
  4756. r = hue2rgb(p, q, h + 1/3);
  4757. g = hue2rgb(p, q, h);
  4758. b = hue2rgb(p, q, h - 1/3);
  4759. }
  4760.  
  4761. return [
  4762. Math.round(r * 255),
  4763. Math.round(g * 255),
  4764. Math.round(b * 255),
  4765. match[4] ? parseFloat(match[4]) : 1
  4766. ];
  4767. };
  4768.  
  4769. /**
  4770. * Returns new color object, when given a color in HSLA format
  4771. * @static
  4772. * @function
  4773. * @memberOf fabric.Color
  4774. * @param {String} color
  4775. * @return {fabric.Color}
  4776. */
  4777. fabric.Color.fromHsla = Color.fromHsl;
  4778.  
  4779. /**
  4780. * Returns new color object, when given a color in HEX format
  4781. * @static
  4782. * @memberOf fabric.Color
  4783. * @param {String} color Color value ex: FF5555
  4784. * @return {fabric.Color}
  4785. */
  4786. fabric.Color.fromHex = function(color) {
  4787. return Color.fromSource(Color.sourceFromHex(color));
  4788. };
  4789.  
  4790. /**
  4791. * Returns array represenatation (ex: [100, 100, 200, 1]) of a color that's in HEX format
  4792. * @static
  4793. * @memberOf fabric.Color
  4794. * @param {String} color ex: FF5555
  4795. * @return {Array} source
  4796. */
  4797. fabric.Color.sourceFromHex = function(color) {
  4798. if (color.match(Color.reHex)) {
  4799. var value = color.slice(color.indexOf('#') + 1),
  4800. isShortNotation = (value.length === 3),
  4801. r = isShortNotation ? (value.charAt(0) + value.charAt(0)) : value.substring(0, 2),
  4802. g = isShortNotation ? (value.charAt(1) + value.charAt(1)) : value.substring(2, 4),
  4803. b = isShortNotation ? (value.charAt(2) + value.charAt(2)) : value.substring(4, 6);
  4804.  
  4805. return [
  4806. parseInt(r, 16),
  4807. parseInt(g, 16),
  4808. parseInt(b, 16),
  4809. 1
  4810. ];
  4811. }
  4812. };
  4813.  
  4814. /**
  4815. * Returns new color object, when given color in array representation (ex: [200, 100, 100, 0.5])
  4816. * @static
  4817. * @memberOf fabric.Color
  4818. * @param {Array} source
  4819. * @return {fabric.Color}
  4820. */
  4821. fabric.Color.fromSource = function(source) {
  4822. var oColor = new Color();
  4823. oColor.setSource(source);
  4824. return oColor;
  4825. };
  4826.  
  4827. })(typeof exports !== 'undefined' ? exports : this);
  4828.  
  4829.  
  4830. (function() {
  4831.  
  4832. /* _FROM_SVG_START_ */
  4833. function getColorStop(el) {
  4834. var style = el.getAttribute('style'),
  4835. offset = el.getAttribute('offset'),
  4836. color, colorAlpha, opacity;
  4837.  
  4838. // convert percents to absolute values
  4839. offset = parseFloat(offset) / (/%$/.test(offset) ? 100 : 1);
  4840. offset = offset < 0 ? 0 : offset > 1 ? 1 : offset;
  4841. if (style) {
  4842. var keyValuePairs = style.split(/\s*;\s*/);
  4843.  
  4844. if (keyValuePairs[keyValuePairs.length - 1] === '') {
  4845. keyValuePairs.pop();
  4846. }
  4847.  
  4848. for (var i = keyValuePairs.length; i--; ) {
  4849.  
  4850. var split = keyValuePairs[i].split(/\s*:\s*/),
  4851. key = split[0].trim(),
  4852. value = split[1].trim();
  4853.  
  4854. if (key === 'stop-color') {
  4855. color = value;
  4856. }
  4857. else if (key === 'stop-opacity') {
  4858. opacity = value;
  4859. }
  4860. }
  4861. }
  4862.  
  4863. if (!color) {
  4864. color = el.getAttribute('stop-color') || 'rgb(0,0,0)';
  4865. }
  4866. if (!opacity) {
  4867. opacity = el.getAttribute('stop-opacity');
  4868. }
  4869.  
  4870. color = new fabric.Color(color);
  4871. colorAlpha = color.getAlpha();
  4872. opacity = isNaN(parseFloat(opacity)) ? 1 : parseFloat(opacity);
  4873. opacity *= colorAlpha;
  4874.  
  4875. return {
  4876. offset: offset,
  4877. color: color.toRgb(),
  4878. opacity: opacity
  4879. };
  4880. }
  4881.  
  4882. function getLinearCoords(el) {
  4883. return {
  4884. x1: el.getAttribute('x1') || 0,
  4885. y1: el.getAttribute('y1') || 0,
  4886. x2: el.getAttribute('x2') || '100%',
  4887. y2: el.getAttribute('y2') || 0
  4888. };
  4889. }
  4890.  
  4891. function getRadialCoords(el) {
  4892. return {
  4893. x1: el.getAttribute('fx') || el.getAttribute('cx') || '50%',
  4894. y1: el.getAttribute('fy') || el.getAttribute('cy') || '50%',
  4895. r1: 0,
  4896. x2: el.getAttribute('cx') || '50%',
  4897. y2: el.getAttribute('cy') || '50%',
  4898. r2: el.getAttribute('r') || '50%'
  4899. };
  4900. }
  4901. /* _FROM_SVG_END_ */
  4902.  
  4903. /**
  4904. * Gradient class
  4905. * @class fabric.Gradient
  4906. * @tutorial {@link http://fabricjs.com/fabric-intro-part-2/#gradients}
  4907. * @see {@link fabric.Gradient#initialize} for constructor definition
  4908. */
  4909. fabric.Gradient = fabric.util.createClass(/** @lends fabric.Gradient.prototype */ {
  4910.  
  4911. /**
  4912. * Horizontal offset for aligning gradients coming from SVG when outside pathgroups
  4913. * @type Number
  4914. * @default 0
  4915. */
  4916. offsetX: 0,
  4917.  
  4918. /**
  4919. * Vertical offset for aligning gradients coming from SVG when outside pathgroups
  4920. * @type Number
  4921. * @default 0
  4922. */
  4923. offsetY: 0,
  4924.  
  4925. /**
  4926. * Constructor
  4927. * @param {Object} [options] Options object with type, coords, gradientUnits and colorStops
  4928. * @return {fabric.Gradient} thisArg
  4929. */
  4930. initialize: function(options) {
  4931. options || (options = { });
  4932.  
  4933. var coords = { };
  4934.  
  4935. this.id = fabric.Object.__uid++;
  4936. this.type = options.type || 'linear';
  4937.  
  4938. coords = {
  4939. x1: options.coords.x1 || 0,
  4940. y1: options.coords.y1 || 0,
  4941. x2: options.coords.x2 || 0,
  4942. y2: options.coords.y2 || 0
  4943. };
  4944.  
  4945. if (this.type === 'radial') {
  4946. coords.r1 = options.coords.r1 || 0;
  4947. coords.r2 = options.coords.r2 || 0;
  4948. }
  4949. this.coords = coords;
  4950. this.colorStops = options.colorStops.slice();
  4951. if (options.gradientTransform) {
  4952. this.gradientTransform = options.gradientTransform;
  4953. }
  4954. this.offsetX = options.offsetX || this.offsetX;
  4955. this.offsetY = options.offsetY || this.offsetY;
  4956. },
  4957.  
  4958. /**
  4959. * Adds another colorStop
  4960. * @param {Object} colorStop Object with offset and color
  4961. * @return {fabric.Gradient} thisArg
  4962. */
  4963. addColorStop: function(colorStop) {
  4964. for (var position in colorStop) {
  4965. var color = new fabric.Color(colorStop[position]);
  4966. this.colorStops.push({
  4967. offset: position,
  4968. color: color.toRgb(),
  4969. opacity: color.getAlpha()
  4970. });
  4971. }
  4972. return this;
  4973. },
  4974.  
  4975. /**
  4976. * Returns object representation of a gradient
  4977. * @return {Object}
  4978. */
  4979. toObject: function() {
  4980. return {
  4981. type: this.type,
  4982. coords: this.coords,
  4983. colorStops: this.colorStops,
  4984. offsetX: this.offsetX,
  4985. offsetY: this.offsetY
  4986. };
  4987. },
  4988.  
  4989. /* _TO_SVG_START_ */
  4990. /**
  4991. * Returns SVG representation of an gradient
  4992. * @param {Object} object Object to create a gradient for
  4993. * @param {Boolean} normalize Whether coords should be normalized
  4994. * @return {String} SVG representation of an gradient (linear/radial)
  4995. */
  4996. toSVG: function(object) {
  4997. var coords = fabric.util.object.clone(this.coords),
  4998. markup, commonAttributes;
  4999.  
  5000. // colorStops must be sorted ascending
  5001. this.colorStops.sort(function(a, b) {
  5002. return a.offset - b.offset;
  5003. });
  5004.  
  5005. if (!(object.group && object.group.type === 'path-group')) {
  5006. for (var prop in coords) {
  5007. if (prop === 'x1' || prop === 'x2' || prop === 'r2') {
  5008. coords[prop] += this.offsetX - object.width / 2;
  5009. }
  5010. else if (prop === 'y1' || prop === 'y2') {
  5011. coords[prop] += this.offsetY - object.height / 2;
  5012. }
  5013. }
  5014. }
  5015.  
  5016. commonAttributes = 'id="SVGID_' + this.id +
  5017. '" gradientUnits="userSpaceOnUse"';
  5018. if (this.gradientTransform) {
  5019. commonAttributes += ' gradientTransform="matrix(' + this.gradientTransform.join(' ') + ')" ';
  5020. }
  5021. if (this.type === 'linear') {
  5022. markup = [
  5023. //jscs:disable validateIndentation
  5024. '<linearGradient ',
  5025. commonAttributes,
  5026. ' x1="', coords.x1,
  5027. '" y1="', coords.y1,
  5028. '" x2="', coords.x2,
  5029. '" y2="', coords.y2,
  5030. '">\n'
  5031. //jscs:enable validateIndentation
  5032. ];
  5033. }
  5034. else if (this.type === 'radial') {
  5035. markup = [
  5036. //jscs:disable validateIndentation
  5037. '<radialGradient ',
  5038. commonAttributes,
  5039. ' cx="', coords.x2,
  5040. '" cy="', coords.y2,
  5041. '" r="', coords.r2,
  5042. '" fx="', coords.x1,
  5043. '" fy="', coords.y1,
  5044. '">\n'
  5045. //jscs:enable validateIndentation
  5046. ];
  5047. }
  5048.  
  5049. for (var i = 0; i < this.colorStops.length; i++) {
  5050. markup.push(
  5051. //jscs:disable validateIndentation
  5052. '<stop ',
  5053. 'offset="', (this.colorStops[i].offset * 100) + '%',
  5054. '" style="stop-color:', this.colorStops[i].color,
  5055. (this.colorStops[i].opacity != null ? ';stop-opacity: ' + this.colorStops[i].opacity : ';'),
  5056. '"/>\n'
  5057. //jscs:enable validateIndentation
  5058. );
  5059. }
  5060.  
  5061. markup.push((this.type === 'linear' ? '</linearGradient>\n' : '</radialGradient>\n'));
  5062.  
  5063. return markup.join('');
  5064. },
  5065. /* _TO_SVG_END_ */
  5066.  
  5067. /**
  5068. * Returns an instance of CanvasGradient
  5069. * @param {CanvasRenderingContext2D} ctx Context to render on
  5070. * @return {CanvasGradient}
  5071. */
  5072. toLive: function(ctx, object) {
  5073. var gradient, coords = fabric.util.object.clone(this.coords);
  5074.  
  5075. if (!this.type) {
  5076. return;
  5077. }
  5078.  
  5079. if (object.group && object.group.type === 'path-group') {
  5080. for (var prop in coords) {
  5081. if (prop === 'x1' || prop === 'x2') {
  5082. coords[prop] += -this.offsetX + object.width / 2;
  5083. }
  5084. else if (prop === 'y1' || prop === 'y2') {
  5085. coords[prop] += -this.offsetY + object.height / 2;
  5086. }
  5087. }
  5088. }
  5089.  
  5090. if (this.type === 'linear') {
  5091. gradient = ctx.createLinearGradient(
  5092. coords.x1, coords.y1, coords.x2, coords.y2);
  5093. }
  5094. else if (this.type === 'radial') {
  5095. gradient = ctx.createRadialGradient(
  5096. coords.x1, coords.y1, coords.r1, coords.x2, coords.y2, coords.r2);
  5097. }
  5098.  
  5099. for (var i = 0, len = this.colorStops.length; i < len; i++) {
  5100. var color = this.colorStops[i].color,
  5101. opacity = this.colorStops[i].opacity,
  5102. offset = this.colorStops[i].offset;
  5103.  
  5104. if (typeof opacity !== 'undefined') {
  5105. color = new fabric.Color(color).setAlpha(opacity).toRgba();
  5106. }
  5107. gradient.addColorStop(parseFloat(offset), color);
  5108. }
  5109.  
  5110. return gradient;
  5111. }
  5112. });
  5113.  
  5114. fabric.util.object.extend(fabric.Gradient, {
  5115.  
  5116. /* _FROM_SVG_START_ */
  5117. /**
  5118. * Returns {@link fabric.Gradient} instance from an SVG element
  5119. * @static
  5120. * @memberof fabric.Gradient
  5121. * @param {SVGGradientElement} el SVG gradient element
  5122. * @param {fabric.Object} instance
  5123. * @return {fabric.Gradient} Gradient instance
  5124. * @see http://www.w3.org/TR/SVG/pservers.html#LinearGradientElement
  5125. * @see http://www.w3.org/TR/SVG/pservers.html#RadialGradientElement
  5126. */
  5127. fromElement: function(el, instance) {
  5128.  
  5129. /**
  5130. * @example:
  5131. *
  5132. * <linearGradient id="linearGrad1">
  5133. * <stop offset="0%" stop-color="white"/>
  5134. * <stop offset="100%" stop-color="black"/>
  5135. * </linearGradient>
  5136. *
  5137. * OR
  5138. *
  5139. * <linearGradient id="linearGrad2">
  5140. * <stop offset="0" style="stop-color:rgb(255,255,255)"/>
  5141. * <stop offset="1" style="stop-color:rgb(0,0,0)"/>
  5142. * </linearGradient>
  5143. *
  5144. * OR
  5145. *
  5146. * <radialGradient id="radialGrad1">
  5147. * <stop offset="0%" stop-color="white" stop-opacity="1" />
  5148. * <stop offset="50%" stop-color="black" stop-opacity="0.5" />
  5149. * <stop offset="100%" stop-color="white" stop-opacity="1" />
  5150. * </radialGradient>
  5151. *
  5152. * OR
  5153. *
  5154. * <radialGradient id="radialGrad2">
  5155. * <stop offset="0" stop-color="rgb(255,255,255)" />
  5156. * <stop offset="0.5" stop-color="rgb(0,0,0)" />
  5157. * <stop offset="1" stop-color="rgb(255,255,255)" />
  5158. * </radialGradient>
  5159. *
  5160. */
  5161.  
  5162. var colorStopEls = el.getElementsByTagName('stop'),
  5163. type = (el.nodeName === 'linearGradient' ? 'linear' : 'radial'),
  5164. gradientUnits = el.getAttribute('gradientUnits') || 'objectBoundingBox',
  5165. gradientTransform = el.getAttribute('gradientTransform'),
  5166. colorStops = [],
  5167. coords = { }, ellipseMatrix;
  5168.  
  5169. if (type === 'linear') {
  5170. coords = getLinearCoords(el);
  5171. }
  5172. else if (type === 'radial') {
  5173. coords = getRadialCoords(el);
  5174. }
  5175.  
  5176. for (var i = colorStopEls.length; i--; ) {
  5177. colorStops.push(getColorStop(colorStopEls[i]));
  5178. }
  5179.  
  5180. ellipseMatrix = _convertPercentUnitsToValues(instance, coords, gradientUnits);
  5181.  
  5182. var gradient = new fabric.Gradient({
  5183. type: type,
  5184. coords: coords,
  5185. colorStops: colorStops,
  5186. offsetX: -instance.left,
  5187. offsetY: -instance.top
  5188. });
  5189.  
  5190. if (gradientTransform || ellipseMatrix !== '') {
  5191. gradient.gradientTransform = fabric.parseTransformAttribute((gradientTransform || '') + ellipseMatrix);
  5192. }
  5193. return gradient;
  5194. },
  5195. /* _FROM_SVG_END_ */
  5196.  
  5197. /**
  5198. * Returns {@link fabric.Gradient} instance from its object representation
  5199. * @static
  5200. * @memberof fabric.Gradient
  5201. * @param {Object} obj
  5202. * @param {Object} [options] Options object
  5203. */
  5204. forObject: function(obj, options) {
  5205. options || (options = { });
  5206. _convertPercentUnitsToValues(obj, options.coords, 'userSpaceOnUse');
  5207. return new fabric.Gradient(options);
  5208. }
  5209. });
  5210.  
  5211. /**
  5212. * @private
  5213. */
  5214. function _convertPercentUnitsToValues(object, options, gradientUnits) {
  5215. var propValue, addFactor = 0, multFactor = 1, ellipseMatrix = '';
  5216. for (var prop in options) {
  5217. propValue = parseFloat(options[prop], 10);
  5218. if (typeof options[prop] === 'string' && /^\d+%$/.test(options[prop])) {
  5219. multFactor = 0.01;
  5220. }
  5221. else {
  5222. multFactor = 1;
  5223. }
  5224. if (prop === 'x1' || prop === 'x2' || prop === 'r2') {
  5225. multFactor *= gradientUnits === 'objectBoundingBox' ? object.width : 1;
  5226. addFactor = gradientUnits === 'objectBoundingBox' ? object.left || 0 : 0;
  5227. }
  5228. else if (prop === 'y1' || prop === 'y2') {
  5229. multFactor *= gradientUnits === 'objectBoundingBox' ? object.height : 1;
  5230. addFactor = gradientUnits === 'objectBoundingBox' ? object.top || 0 : 0;
  5231. }
  5232. options[prop] = propValue * multFactor + addFactor;
  5233. }
  5234. if (object.type === 'ellipse' &&
  5235. options.r2 !== null &&
  5236. gradientUnits === 'objectBoundingBox' &&
  5237. object.rx !== object.ry) {
  5238.  
  5239. var scaleFactor = object.ry/object.rx;
  5240. ellipseMatrix = ' scale(1, ' + scaleFactor + ')';
  5241. if (options.y1) {
  5242. options.y1 /= scaleFactor;
  5243. }
  5244. if (options.y2) {
  5245. options.y2 /= scaleFactor;
  5246. }
  5247. }
  5248. return ellipseMatrix;
  5249. }
  5250. })();
  5251.  
  5252.  
  5253. /**
  5254. * Pattern class
  5255. * @class fabric.Pattern
  5256. * @see {@link http://fabricjs.com/patterns/|Pattern demo}
  5257. * @see {@link http://fabricjs.com/dynamic-patterns/|DynamicPattern demo}
  5258. * @see {@link fabric.Pattern#initialize} for constructor definition
  5259. */
  5260. fabric.Pattern = fabric.util.createClass(/** @lends fabric.Pattern.prototype */ {
  5261.  
  5262. /**
  5263. * Repeat property of a pattern (one of repeat, repeat-x, repeat-y or no-repeat)
  5264. * @type String
  5265. * @default
  5266. */
  5267. repeat: 'repeat',
  5268.  
  5269. /**
  5270. * Pattern horizontal offset from object's left/top corner
  5271. * @type Number
  5272. * @default
  5273. */
  5274. offsetX: 0,
  5275.  
  5276. /**
  5277. * Pattern vertical offset from object's left/top corner
  5278. * @type Number
  5279. * @default
  5280. */
  5281. offsetY: 0,
  5282.  
  5283. /**
  5284. * Constructor
  5285. * @param {Object} [options] Options object
  5286. * @return {fabric.Pattern} thisArg
  5287. */
  5288. initialize: function(options) {
  5289. options || (options = { });
  5290.  
  5291. this.id = fabric.Object.__uid++;
  5292.  
  5293. if (options.source) {
  5294. if (typeof options.source === 'string') {
  5295. // function string
  5296. if (typeof fabric.util.getFunctionBody(options.source) !== 'undefined') {
  5297. this.source = new Function(fabric.util.getFunctionBody(options.source));
  5298. }
  5299. else {
  5300. // img src string
  5301. var _this = this;
  5302. this.source = fabric.util.createImage();
  5303. fabric.util.loadImage(options.source, function(img) {
  5304. _this.source = img;
  5305. });
  5306. }
  5307. }
  5308. else {
  5309. // img element
  5310. this.source = options.source;
  5311. }
  5312. }
  5313. if (options.repeat) {
  5314. this.repeat = options.repeat;
  5315. }
  5316. if (options.offsetX) {
  5317. this.offsetX = options.offsetX;
  5318. }
  5319. if (options.offsetY) {
  5320. this.offsetY = options.offsetY;
  5321. }
  5322. },
  5323.  
  5324. /**
  5325. * Returns object representation of a pattern
  5326. * @return {Object} Object representation of a pattern instance
  5327. */
  5328. toObject: function() {
  5329.  
  5330. var source;
  5331.  
  5332. // callback
  5333. if (typeof this.source === 'function') {
  5334. source = String(this.source);
  5335. }
  5336. // <img> element
  5337. else if (typeof this.source.src === 'string') {
  5338. source = this.source.src;
  5339. }
  5340.  
  5341. return {
  5342. source: source,
  5343. repeat: this.repeat,
  5344. offsetX: this.offsetX,
  5345. offsetY: this.offsetY
  5346. };
  5347. },
  5348.  
  5349. /* _TO_SVG_START_ */
  5350. /**
  5351. * Returns SVG representation of a pattern
  5352. * @param {fabric.Object} object
  5353. * @return {String} SVG representation of a pattern
  5354. */
  5355. toSVG: function(object) {
  5356. var patternSource = typeof this.source === 'function' ? this.source() : this.source,
  5357. patternWidth = patternSource.width / object.getWidth(),
  5358. patternHeight = patternSource.height / object.getHeight(),
  5359. patternImgSrc = '';
  5360.  
  5361. if (patternSource.src) {
  5362. patternImgSrc = patternSource.src;
  5363. }
  5364. else if (patternSource.toDataURL) {
  5365. patternImgSrc = patternSource.toDataURL();
  5366. }
  5367.  
  5368. return '<pattern id="SVGID_' + this.id +
  5369. '" x="' + this.offsetX +
  5370. '" y="' + this.offsetY +
  5371. '" width="' + patternWidth +
  5372. '" height="' + patternHeight + '">' +
  5373. '<image x="0" y="0"' +
  5374. ' width="' + patternSource.width +
  5375. '" height="' + patternSource.height +
  5376. '" xlink:href="' + patternImgSrc +
  5377. '"></image>' +
  5378. '</pattern>';
  5379. },
  5380. /* _TO_SVG_END_ */
  5381.  
  5382. /**
  5383. * Returns an instance of CanvasPattern
  5384. * @param {CanvasRenderingContext2D} ctx Context to create pattern
  5385. * @return {CanvasPattern}
  5386. */
  5387. toLive: function(ctx) {
  5388. var source = typeof this.source === 'function'
  5389. ? this.source()
  5390. : this.source;
  5391.  
  5392. // if the image failed to load, return, and allow rest to continue loading
  5393. if (!source) {
  5394. return '';
  5395. }
  5396.  
  5397. // if an image
  5398. if (typeof source.src !== 'undefined') {
  5399. if (!source.complete) {
  5400. return '';
  5401. }
  5402. if (source.naturalWidth === 0 || source.naturalHeight === 0) {
  5403. return '';
  5404. }
  5405. }
  5406. return ctx.createPattern(source, this.repeat);
  5407. }
  5408. });
  5409.  
  5410.  
  5411. (function(global) {
  5412.  
  5413. 'use strict';
  5414.  
  5415. var fabric = global.fabric || (global.fabric = { });
  5416.  
  5417. if (fabric.Shadow) {
  5418. fabric.warn('fabric.Shadow is already defined.');
  5419. return;
  5420. }
  5421.  
  5422. /**
  5423. * Shadow class
  5424. * @class fabric.Shadow
  5425. * @see {@link http://fabricjs.com/shadows/|Shadow demo}
  5426. * @see {@link fabric.Shadow#initialize} for constructor definition
  5427. */
  5428. fabric.Shadow = fabric.util.createClass(/** @lends fabric.Shadow.prototype */ {
  5429.  
  5430. /**
  5431. * Shadow color
  5432. * @type String
  5433. * @default
  5434. */
  5435. color: 'rgb(0,0,0)',
  5436.  
  5437. /**
  5438. * Shadow blur
  5439. * @type Number
  5440. */
  5441. blur: 0,
  5442.  
  5443. /**
  5444. * Shadow horizontal offset
  5445. * @type Number
  5446. * @default
  5447. */
  5448. offsetX: 0,
  5449.  
  5450. /**
  5451. * Shadow vertical offset
  5452. * @type Number
  5453. * @default
  5454. */
  5455. offsetY: 0,
  5456.  
  5457. /**
  5458. * Whether the shadow should affect stroke operations
  5459. * @type Boolean
  5460. * @default
  5461. */
  5462. affectStroke: false,
  5463.  
  5464. /**
  5465. * Indicates whether toObject should include default values
  5466. * @type Boolean
  5467. * @default
  5468. */
  5469. includeDefaultValues: true,
  5470.  
  5471. /**
  5472. * Constructor
  5473. * @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)")
  5474. * @return {fabric.Shadow} thisArg
  5475. */
  5476. initialize: function(options) {
  5477.  
  5478. if (typeof options === 'string') {
  5479. options = this._parseShadow(options);
  5480. }
  5481.  
  5482. for (var prop in options) {
  5483. this[prop] = options[prop];
  5484. }
  5485.  
  5486. this.id = fabric.Object.__uid++;
  5487. },
  5488.  
  5489. /**
  5490. * @private
  5491. * @param {String} shadow Shadow value to parse
  5492. * @return {Object} Shadow object with color, offsetX, offsetY and blur
  5493. */
  5494. _parseShadow: function(shadow) {
  5495. var shadowStr = shadow.trim(),
  5496. offsetsAndBlur = fabric.Shadow.reOffsetsAndBlur.exec(shadowStr) || [ ],
  5497. color = shadowStr.replace(fabric.Shadow.reOffsetsAndBlur, '') || 'rgb(0,0,0)';
  5498.  
  5499. return {
  5500. color: color.trim(),
  5501. offsetX: parseInt(offsetsAndBlur[1], 10) || 0,
  5502. offsetY: parseInt(offsetsAndBlur[2], 10) || 0,
  5503. blur: parseInt(offsetsAndBlur[3], 10) || 0
  5504. };
  5505. },
  5506.  
  5507. /**
  5508. * Returns a string representation of an instance
  5509. * @see http://www.w3.org/TR/css-text-decor-3/#text-shadow
  5510. * @return {String} Returns CSS3 text-shadow declaration
  5511. */
  5512. toString: function() {
  5513. return [this.offsetX, this.offsetY, this.blur, this.color].join('px ');
  5514. },
  5515.  
  5516. /* _TO_SVG_START_ */
  5517. /**
  5518. * Returns SVG representation of a shadow
  5519. * @param {fabric.Object} object
  5520. * @return {String} SVG representation of a shadow
  5521. */
  5522. toSVG: function(object) {
  5523. var mode = 'SourceAlpha';
  5524.  
  5525. if (object && (object.fill === this.color || object.stroke === this.color)) {
  5526. mode = 'SourceGraphic';
  5527. }
  5528.  
  5529. return (
  5530. '<filter id="SVGID_' + this.id + '" y="-40%" height="180%">' +
  5531. '<feGaussianBlur in="' + mode + '" stdDeviation="' +
  5532. (this.blur ? this.blur / 3 : 0) +
  5533. '"></feGaussianBlur>' +
  5534. '<feOffset dx="' + this.offsetX + '" dy="' + this.offsetY + '"></feOffset>' +
  5535. '<feMerge>' +
  5536. '<feMergeNode></feMergeNode>' +
  5537. '<feMergeNode in="SourceGraphic"></feMergeNode>' +
  5538. '</feMerge>' +
  5539. '</filter>');
  5540. },
  5541. /* _TO_SVG_END_ */
  5542.  
  5543. /**
  5544. * Returns object representation of a shadow
  5545. * @return {Object} Object representation of a shadow instance
  5546. */
  5547. toObject: function() {
  5548. if (this.includeDefaultValues) {
  5549. return {
  5550. color: this.color,
  5551. blur: this.blur,
  5552. offsetX: this.offsetX,
  5553. offsetY: this.offsetY
  5554. };
  5555. }
  5556. var obj = { }, proto = fabric.Shadow.prototype;
  5557. if (this.color !== proto.color) {
  5558. obj.color = this.color;
  5559. }
  5560. if (this.blur !== proto.blur) {
  5561. obj.blur = this.blur;
  5562. }
  5563. if (this.offsetX !== proto.offsetX) {
  5564. obj.offsetX = this.offsetX;
  5565. }
  5566. if (this.offsetY !== proto.offsetY) {
  5567. obj.offsetY = this.offsetY;
  5568. }
  5569. return obj;
  5570. }
  5571. });
  5572.  
  5573. /**
  5574. * Regex matching shadow offsetX, offsetY and blur (ex: "2px 2px 10px rgba(0,0,0,0.2)", "rgb(0,255,0) 2px 2px")
  5575. * @static
  5576. * @field
  5577. * @memberOf fabric.Shadow
  5578. */
  5579. fabric.Shadow.reOffsetsAndBlur = /(?:\s|^)(-?\d+(?:px)?(?:\s?|$))?(-?\d+(?:px)?(?:\s?|$))?(\d+(?:px)?)?(?:\s?|$)(?:$|\s)/;
  5580.  
  5581. })(typeof exports !== 'undefined' ? exports : this);
  5582.  
  5583.  
  5584. (function () {
  5585.  
  5586. 'use strict';
  5587.  
  5588. if (fabric.StaticCanvas) {
  5589. fabric.warn('fabric.StaticCanvas is already defined.');
  5590. return;
  5591. }
  5592.  
  5593. // aliases for faster resolution
  5594. var extend = fabric.util.object.extend,
  5595. getElementOffset = fabric.util.getElementOffset,
  5596. removeFromArray = fabric.util.removeFromArray,
  5597.  
  5598. CANVAS_INIT_ERROR = new Error('Could not initialize `canvas` element');
  5599.  
  5600. /**
  5601. * Static canvas class
  5602. * @class fabric.StaticCanvas
  5603. * @mixes fabric.Collection
  5604. * @mixes fabric.Observable
  5605. * @see {@link http://fabricjs.com/static_canvas/|StaticCanvas demo}
  5606. * @see {@link fabric.StaticCanvas#initialize} for constructor definition
  5607. * @fires before:render
  5608. * @fires after:render
  5609. * @fires canvas:cleared
  5610. * @fires object:added
  5611. * @fires object:removed
  5612. */
  5613. fabric.StaticCanvas = fabric.util.createClass(/** @lends fabric.StaticCanvas.prototype */ {
  5614.  
  5615. /**
  5616. * Constructor
  5617. * @param {HTMLElement | String} el &lt;canvas> element to initialize instance on
  5618. * @param {Object} [options] Options object
  5619. * @return {Object} thisArg
  5620. */
  5621. initialize: function(el, options) {
  5622. options || (options = { });
  5623.  
  5624. this._initStatic(el, options);
  5625. fabric.StaticCanvas.activeInstance = this;
  5626. },
  5627.  
  5628. /**
  5629. * Background color of canvas instance.
  5630. * Should be set via {@link fabric.StaticCanvas#setBackgroundColor}.
  5631. * @type {(String|fabric.Pattern)}
  5632. * @default
  5633. */
  5634. backgroundColor: '',
  5635.  
  5636. /**
  5637. * Background image of canvas instance.
  5638. * Should be set via {@link fabric.StaticCanvas#setBackgroundImage}.
  5639. * <b>Backwards incompatibility note:</b> The "backgroundImageOpacity"
  5640. * and "backgroundImageStretch" properties are deprecated since 1.3.9.
  5641. * Use {@link fabric.Image#opacity}, {@link fabric.Image#width} and {@link fabric.Image#height}.
  5642. * @type fabric.Image
  5643. * @default
  5644. */
  5645. backgroundImage: null,
  5646.  
  5647. /**
  5648. * Overlay color of canvas instance.
  5649. * Should be set via {@link fabric.StaticCanvas#setOverlayColor}
  5650. * @since 1.3.9
  5651. * @type {(String|fabric.Pattern)}
  5652. * @default
  5653. */
  5654. overlayColor: '',
  5655.  
  5656. /**
  5657. * Overlay image of canvas instance.
  5658. * Should be set via {@link fabric.StaticCanvas#setOverlayImage}.
  5659. * <b>Backwards incompatibility note:</b> The "overlayImageLeft"
  5660. * and "overlayImageTop" properties are deprecated since 1.3.9.
  5661. * Use {@link fabric.Image#left} and {@link fabric.Image#top}.
  5662. * @type fabric.Image
  5663. * @default
  5664. */
  5665. overlayImage: null,
  5666.  
  5667. /**
  5668. * Indicates whether toObject/toDatalessObject should include default values
  5669. * @type Boolean
  5670. * @default
  5671. */
  5672. includeDefaultValues: true,
  5673.  
  5674. /**
  5675. * Indicates whether objects' state should be saved
  5676. * @type Boolean
  5677. * @default
  5678. */
  5679. stateful: true,
  5680.  
  5681. /**
  5682. * Indicates whether {@link fabric.Collection.add}, {@link fabric.Collection.insertAt} and {@link fabric.Collection.remove} should also re-render canvas.
  5683. * Disabling this option could give a great performance boost when adding/removing a lot of objects to/from canvas at once
  5684. * (followed by a manual rendering after addition/deletion)
  5685. * @type Boolean
  5686. * @default
  5687. */
  5688. renderOnAddRemove: true,
  5689.  
  5690. /**
  5691. * Function that determines clipping of entire canvas area
  5692. * Being passed context as first argument. See clipping canvas area in {@link https://github.com/kangax/fabric.js/wiki/FAQ}
  5693. * @type Function
  5694. * @default
  5695. */
  5696. clipTo: null,
  5697.  
  5698. /**
  5699. * Indicates whether object controls (borders/controls) are rendered above overlay image
  5700. * @type Boolean
  5701. * @default
  5702. */
  5703. controlsAboveOverlay: false,
  5704.  
  5705. /**
  5706. * Indicates whether the browser can be scrolled when using a touchscreen and dragging on the canvas
  5707. * @type Boolean
  5708. * @default
  5709. */
  5710. allowTouchScrolling: false,
  5711.  
  5712. /**
  5713. * Indicates whether this canvas will use image smoothing, this is on by default in browsers
  5714. * @type Boolean
  5715. * @default
  5716. */
  5717. imageSmoothingEnabled: true,
  5718.  
  5719. /**
  5720. * Indicates whether objects should remain in current stack position when selected. When false objects are brought to top and rendered as part of the selection group
  5721. * @type Boolean
  5722. * @default
  5723. */
  5724. preserveObjectStacking: false,
  5725.  
  5726. /**
  5727. * The transformation (in the format of Canvas transform) which focuses the viewport
  5728. * @type Array
  5729. * @default
  5730. */
  5731. viewportTransform: [1, 0, 0, 1, 0, 0],
  5732.  
  5733. /**
  5734. * Callback; invoked right before object is about to be scaled/rotated
  5735. */
  5736. onBeforeScaleRotate: function () {
  5737. /* NOOP */
  5738. },
  5739.  
  5740. /**
  5741. * @private
  5742. * @param {HTMLElement | String} el &lt;canvas> element to initialize instance on
  5743. * @param {Object} [options] Options object
  5744. */
  5745. _initStatic: function(el, options) {
  5746. this._objects = [];
  5747.  
  5748. this._createLowerCanvas(el);
  5749. this._initOptions(options);
  5750. this._setImageSmoothing();
  5751.  
  5752. if (options.overlayImage) {
  5753. this.setOverlayImage(options.overlayImage, this.renderAll.bind(this));
  5754. }
  5755. if (options.backgroundImage) {
  5756. this.setBackgroundImage(options.backgroundImage, this.renderAll.bind(this));
  5757. }
  5758. if (options.backgroundColor) {
  5759. this.setBackgroundColor(options.backgroundColor, this.renderAll.bind(this));
  5760. }
  5761. if (options.overlayColor) {
  5762. this.setOverlayColor(options.overlayColor, this.renderAll.bind(this));
  5763. }
  5764. this.calcOffset();
  5765. },
  5766.  
  5767. /**
  5768. * Calculates canvas element offset relative to the document
  5769. * This method is also attached as "resize" event handler of window
  5770. * @return {fabric.Canvas} instance
  5771. * @chainable
  5772. */
  5773. calcOffset: function () {
  5774. this._offset = getElementOffset(this.lowerCanvasEl);
  5775. return this;
  5776. },
  5777.  
  5778. /**
  5779. * Sets {@link fabric.StaticCanvas#overlayImage|overlay image} for this canvas
  5780. * @param {(fabric.Image|String)} image fabric.Image instance or URL of an image to set overlay to
  5781. * @param {Function} callback callback to invoke when image is loaded and set as an overlay
  5782. * @param {Object} [options] Optional options to set for the {@link fabric.Image|overlay image}.
  5783. * @return {fabric.Canvas} thisArg
  5784. * @chainable
  5785. * @see {@link http://jsfiddle.net/fabricjs/MnzHT/|jsFiddle demo}
  5786. * @example <caption>Normal overlayImage with left/top = 0</caption>
  5787. * canvas.setOverlayImage('http://fabricjs.com/assets/jail_cell_bars.png', canvas.renderAll.bind(canvas), {
  5788. * // Needed to position overlayImage at 0/0
  5789. * originX: 'left',
  5790. * originY: 'top'
  5791. * });
  5792. * @example <caption>overlayImage with different properties</caption>
  5793. * canvas.setOverlayImage('http://fabricjs.com/assets/jail_cell_bars.png', canvas.renderAll.bind(canvas), {
  5794. * opacity: 0.5,
  5795. * angle: 45,
  5796. * left: 400,
  5797. * top: 400,
  5798. * originX: 'left',
  5799. * originY: 'top'
  5800. * });
  5801. * @example <caption>Stretched overlayImage #1 - width/height correspond to canvas width/height</caption>
  5802. * fabric.Image.fromURL('http://fabricjs.com/assets/jail_cell_bars.png', function(img) {
  5803. * img.set({width: canvas.width, height: canvas.height, originX: 'left', originY: 'top'});
  5804. * canvas.setOverlayImage(img, canvas.renderAll.bind(canvas));
  5805. * });
  5806. * @example <caption>Stretched overlayImage #2 - width/height correspond to canvas width/height</caption>
  5807. * canvas.setOverlayImage('http://fabricjs.com/assets/jail_cell_bars.png', canvas.renderAll.bind(canvas), {
  5808. * width: canvas.width,
  5809. * height: canvas.height,
  5810. * // Needed to position overlayImage at 0/0
  5811. * originX: 'left',
  5812. * originY: 'top'
  5813. * });
  5814. */
  5815. setOverlayImage: function (image, callback, options) {
  5816. return this.__setBgOverlayImage('overlayImage', image, callback, options);
  5817. },
  5818.  
  5819. /**
  5820. * Sets {@link fabric.StaticCanvas#backgroundImage|background image} for this canvas
  5821. * @param {(fabric.Image|String)} image fabric.Image instance or URL of an image to set background to
  5822. * @param {Function} callback Callback to invoke when image is loaded and set as background
  5823. * @param {Object} [options] Optional options to set for the {@link fabric.Image|background image}.
  5824. * @return {fabric.Canvas} thisArg
  5825. * @chainable
  5826. * @see {@link http://jsfiddle.net/fabricjs/YH9yD/|jsFiddle demo}
  5827. * @example <caption>Normal backgroundImage with left/top = 0</caption>
  5828. * canvas.setBackgroundImage('http://fabricjs.com/assets/honey_im_subtle.png', canvas.renderAll.bind(canvas), {
  5829. * // Needed to position backgroundImage at 0/0
  5830. * originX: 'left',
  5831. * originY: 'top'
  5832. * });
  5833. * @example <caption>backgroundImage with different properties</caption>
  5834. * canvas.setBackgroundImage('http://fabricjs.com/assets/honey_im_subtle.png', canvas.renderAll.bind(canvas), {
  5835. * opacity: 0.5,
  5836. * angle: 45,
  5837. * left: 400,
  5838. * top: 400,
  5839. * originX: 'left',
  5840. * originY: 'top'
  5841. * });
  5842. * @example <caption>Stretched backgroundImage #1 - width/height correspond to canvas width/height</caption>
  5843. * fabric.Image.fromURL('http://fabricjs.com/assets/honey_im_subtle.png', function(img) {
  5844. * img.set({width: canvas.width, height: canvas.height, originX: 'left', originY: 'top'});
  5845. * canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas));
  5846. * });
  5847. * @example <caption>Stretched backgroundImage #2 - width/height correspond to canvas width/height</caption>
  5848. * canvas.setBackgroundImage('http://fabricjs.com/assets/honey_im_subtle.png', canvas.renderAll.bind(canvas), {
  5849. * width: canvas.width,
  5850. * height: canvas.height,
  5851. * // Needed to position backgroundImage at 0/0
  5852. * originX: 'left',
  5853. * originY: 'top'
  5854. * });
  5855. */
  5856. setBackgroundImage: function (image, callback, options) {
  5857. return this.__setBgOverlayImage('backgroundImage', image, callback, options);
  5858. },
  5859.  
  5860. /**
  5861. * Sets {@link fabric.StaticCanvas#overlayColor|background color} for this canvas
  5862. * @param {(String|fabric.Pattern)} overlayColor Color or pattern to set background color to
  5863. * @param {Function} callback Callback to invoke when background color is set
  5864. * @return {fabric.Canvas} thisArg
  5865. * @chainable
  5866. * @see {@link http://jsfiddle.net/fabricjs/pB55h/|jsFiddle demo}
  5867. * @example <caption>Normal overlayColor - color value</caption>
  5868. * canvas.setOverlayColor('rgba(255, 73, 64, 0.6)', canvas.renderAll.bind(canvas));
  5869. * @example <caption>fabric.Pattern used as overlayColor</caption>
  5870. * canvas.setOverlayColor({
  5871. * source: 'http://fabricjs.com/assets/escheresque_ste.png'
  5872. * }, canvas.renderAll.bind(canvas));
  5873. * @example <caption>fabric.Pattern used as overlayColor with repeat and offset</caption>
  5874. * canvas.setOverlayColor({
  5875. * source: 'http://fabricjs.com/assets/escheresque_ste.png',
  5876. * repeat: 'repeat',
  5877. * offsetX: 200,
  5878. * offsetY: 100
  5879. * }, canvas.renderAll.bind(canvas));
  5880. */
  5881. setOverlayColor: function(overlayColor, callback) {
  5882. return this.__setBgOverlayColor('overlayColor', overlayColor, callback);
  5883. },
  5884.  
  5885. /**
  5886. * Sets {@link fabric.StaticCanvas#backgroundColor|background color} for this canvas
  5887. * @param {(String|fabric.Pattern)} backgroundColor Color or pattern to set background color to
  5888. * @param {Function} callback Callback to invoke when background color is set
  5889. * @return {fabric.Canvas} thisArg
  5890. * @chainable
  5891. * @see {@link http://jsfiddle.net/fabricjs/hXzvk/|jsFiddle demo}
  5892. * @example <caption>Normal backgroundColor - color value</caption>
  5893. * canvas.setBackgroundColor('rgba(255, 73, 64, 0.6)', canvas.renderAll.bind(canvas));
  5894. * @example <caption>fabric.Pattern used as backgroundColor</caption>
  5895. * canvas.setBackgroundColor({
  5896. * source: 'http://fabricjs.com/assets/escheresque_ste.png'
  5897. * }, canvas.renderAll.bind(canvas));
  5898. * @example <caption>fabric.Pattern used as backgroundColor with repeat and offset</caption>
  5899. * canvas.setBackgroundColor({
  5900. * source: 'http://fabricjs.com/assets/escheresque_ste.png',
  5901. * repeat: 'repeat',
  5902. * offsetX: 200,
  5903. * offsetY: 100
  5904. * }, canvas.renderAll.bind(canvas));
  5905. */
  5906. setBackgroundColor: function(backgroundColor, callback) {
  5907. return this.__setBgOverlayColor('backgroundColor', backgroundColor, callback);
  5908. },
  5909.  
  5910. /**
  5911. * @private
  5912. * @see {@link http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-context-2d-imagesmoothingenabled|WhatWG Canvas Standard}
  5913. */
  5914. _setImageSmoothing: function() {
  5915. var ctx = this.getContext();
  5916.  
  5917. ctx.imageSmoothingEnabled = this.imageSmoothingEnabled;
  5918. ctx.webkitImageSmoothingEnabled = this.imageSmoothingEnabled;
  5919. ctx.mozImageSmoothingEnabled = this.imageSmoothingEnabled;
  5920. ctx.msImageSmoothingEnabled = this.imageSmoothingEnabled;
  5921. ctx.oImageSmoothingEnabled = this.imageSmoothingEnabled;
  5922. },
  5923.  
  5924. /**
  5925. * @private
  5926. * @param {String} property Property to set ({@link fabric.StaticCanvas#backgroundImage|backgroundImage}
  5927. * or {@link fabric.StaticCanvas#overlayImage|overlayImage})
  5928. * @param {(fabric.Image|String|null)} image fabric.Image instance, URL of an image or null to set background or overlay to
  5929. * @param {Function} callback Callback to invoke when image is loaded and set as background or overlay
  5930. * @param {Object} [options] Optional options to set for the {@link fabric.Image|image}.
  5931. */
  5932. __setBgOverlayImage: function(property, image, callback, options) {
  5933. if (typeof image === 'string') {
  5934. fabric.util.loadImage(image, function(img) {
  5935. this[property] = new fabric.Image(img, options);
  5936. callback && callback();
  5937. }, this);
  5938. }
  5939. else {
  5940. this[property] = image;
  5941. callback && callback();
  5942. }
  5943.  
  5944. return this;
  5945. },
  5946.  
  5947. /**
  5948. * @private
  5949. * @param {String} property Property to set ({@link fabric.StaticCanvas#backgroundColor|backgroundColor}
  5950. * or {@link fabric.StaticCanvas#overlayColor|overlayColor})
  5951. * @param {(Object|String|null)} color Object with pattern information, color value or null
  5952. * @param {Function} [callback] Callback is invoked when color is set
  5953. */
  5954. __setBgOverlayColor: function(property, color, callback) {
  5955. if (color && color.source) {
  5956. var _this = this;
  5957. fabric.util.loadImage(color.source, function(img) {
  5958. _this[property] = new fabric.Pattern({
  5959. source: img,
  5960. repeat: color.repeat,
  5961. offsetX: color.offsetX,
  5962. offsetY: color.offsetY
  5963. });
  5964. callback && callback();
  5965. });
  5966. }
  5967. else {
  5968. this[property] = color;
  5969. callback && callback();
  5970. }
  5971.  
  5972. return this;
  5973. },
  5974.  
  5975. /**
  5976. * @private
  5977. */
  5978. _createCanvasElement: function() {
  5979. var element = fabric.document.createElement('canvas');
  5980. if (!element.style) {
  5981. element.style = { };
  5982. }
  5983. if (!element) {
  5984. throw CANVAS_INIT_ERROR;
  5985. }
  5986. this._initCanvasElement(element);
  5987. return element;
  5988. },
  5989.  
  5990. /**
  5991. * @private
  5992. * @param {HTMLElement} element
  5993. */
  5994. _initCanvasElement: function(element) {
  5995. fabric.util.createCanvasElement(element);
  5996.  
  5997. if (typeof element.getContext === 'undefined') {
  5998. throw CANVAS_INIT_ERROR;
  5999. }
  6000. },
  6001.  
  6002. /**
  6003. * @private
  6004. * @param {Object} [options] Options object
  6005. */
  6006. _initOptions: function (options) {
  6007. for (var prop in options) {
  6008. this[prop] = options[prop];
  6009. }
  6010.  
  6011. this.width = this.width || parseInt(this.lowerCanvasEl.width, 10) || 0;
  6012. this.height = this.height || parseInt(this.lowerCanvasEl.height, 10) || 0;
  6013.  
  6014. if (!this.lowerCanvasEl.style) {
  6015. return;
  6016. }
  6017.  
  6018. this.lowerCanvasEl.width = this.width;
  6019. this.lowerCanvasEl.height = this.height;
  6020.  
  6021. this.lowerCanvasEl.style.width = this.width + 'px';
  6022. this.lowerCanvasEl.style.height = this.height + 'px';
  6023.  
  6024. this.viewportTransform = this.viewportTransform.slice();
  6025. },
  6026.  
  6027. /**
  6028. * Creates a bottom canvas
  6029. * @private
  6030. * @param {HTMLElement} [canvasEl]
  6031. */
  6032. _createLowerCanvas: function (canvasEl) {
  6033. this.lowerCanvasEl = fabric.util.getById(canvasEl) || this._createCanvasElement();
  6034. this._initCanvasElement(this.lowerCanvasEl);
  6035.  
  6036. fabric.util.addClass(this.lowerCanvasEl, 'lower-canvas');
  6037.  
  6038. if (this.interactive) {
  6039. this._applyCanvasStyle(this.lowerCanvasEl);
  6040. }
  6041.  
  6042. this.contextContainer = this.lowerCanvasEl.getContext('2d');
  6043. },
  6044.  
  6045. /**
  6046. * Returns canvas width (in px)
  6047. * @return {Number}
  6048. */
  6049. getWidth: function () {
  6050. return this.width;
  6051. },
  6052.  
  6053. /**
  6054. * Returns canvas height (in px)
  6055. * @return {Number}
  6056. */
  6057. getHeight: function () {
  6058. return this.height;
  6059. },
  6060.  
  6061. /**
  6062. * Sets width of this canvas instance
  6063. * @param {Number|String} value Value to set width to
  6064. * @param {Object} [options] Options object
  6065. * @param {Boolean} [options.backstoreOnly=false] Set the given dimensions only as canvas backstore dimensions
  6066. * @param {Boolean} [options.cssOnly=false] Set the given dimensions only as css dimensions
  6067. * @return {fabric.Canvas} instance
  6068. * @chainable true
  6069. */
  6070. setWidth: function (value, options) {
  6071. return this.setDimensions({ width: value }, options);
  6072. },
  6073.  
  6074. /**
  6075. * Sets height of this canvas instance
  6076. * @param {Number|String} value Value to set height to
  6077. * @param {Object} [options] Options object
  6078. * @param {Boolean} [options.backstoreOnly=false] Set the given dimensions only as canvas backstore dimensions
  6079. * @param {Boolean} [options.cssOnly=false] Set the given dimensions only as css dimensions
  6080. * @return {fabric.Canvas} instance
  6081. * @chainable true
  6082. */
  6083. setHeight: function (value, options) {
  6084. return this.setDimensions({ height: value }, options);
  6085. },
  6086.  
  6087. /**
  6088. * Sets dimensions (width, height) of this canvas instance. when options.cssOnly flag active you should also supply the unit of measure (px/%/em)
  6089. * @param {Object} dimensions Object with width/height properties
  6090. * @param {Number|String} [dimensions.width] Width of canvas element
  6091. * @param {Number|String} [dimensions.height] Height of canvas element
  6092. * @param {Object} [options] Options object
  6093. * @param {Boolean} [options.backstoreOnly=false] Set the given dimensions only as canvas backstore dimensions
  6094. * @param {Boolean} [options.cssOnly=false] Set the given dimensions only as css dimensions
  6095. * @return {fabric.Canvas} thisArg
  6096. * @chainable
  6097. */
  6098. setDimensions: function (dimensions, options) {
  6099. var cssValue;
  6100.  
  6101. options = options || {};
  6102.  
  6103. for (var prop in dimensions) {
  6104. cssValue = dimensions[prop];
  6105.  
  6106. if (!options.cssOnly) {
  6107. this._setBackstoreDimension(prop, dimensions[prop]);
  6108. cssValue += 'px';
  6109. }
  6110.  
  6111. if (!options.backstoreOnly) {
  6112. this._setCssDimension(prop, cssValue);
  6113. }
  6114. }
  6115.  
  6116. if (!options.cssOnly) {
  6117. this.renderAll();
  6118. }
  6119.  
  6120. this.calcOffset();
  6121.  
  6122. return this;
  6123. },
  6124.  
  6125. /**
  6126. * Helper for setting width/height
  6127. * @private
  6128. * @param {String} prop property (width|height)
  6129. * @param {Number} value value to set property to
  6130. * @return {fabric.Canvas} instance
  6131. * @chainable true
  6132. */
  6133. _setBackstoreDimension: function (prop, value) {
  6134. this.lowerCanvasEl[prop] = value;
  6135.  
  6136. if (this.upperCanvasEl) {
  6137. this.upperCanvasEl[prop] = value;
  6138. }
  6139.  
  6140. if (this.cacheCanvasEl) {
  6141. this.cacheCanvasEl[prop] = value;
  6142. }
  6143.  
  6144. this[prop] = value;
  6145.  
  6146. return this;
  6147. },
  6148.  
  6149. /**
  6150. * Helper for setting css width/height
  6151. * @private
  6152. * @param {String} prop property (width|height)
  6153. * @param {String} value value to set property to
  6154. * @return {fabric.Canvas} instance
  6155. * @chainable true
  6156. */
  6157. _setCssDimension: function (prop, value) {
  6158. this.lowerCanvasEl.style[prop] = value;
  6159.  
  6160. if (this.upperCanvasEl) {
  6161. this.upperCanvasEl.style[prop] = value;
  6162. }
  6163.  
  6164. if (this.wrapperEl) {
  6165. this.wrapperEl.style[prop] = value;
  6166. }
  6167.  
  6168. return this;
  6169. },
  6170.  
  6171. /**
  6172. * Returns canvas zoom level
  6173. * @return {Number}
  6174. */
  6175. getZoom: function () {
  6176. return Math.sqrt(this.viewportTransform[0] * this.viewportTransform[3]);
  6177. },
  6178.  
  6179. /**
  6180. * Sets viewport transform of this canvas instance
  6181. * @param {Array} vpt the transform in the form of context.transform
  6182. * @return {fabric.Canvas} instance
  6183. * @chainable true
  6184. */
  6185. setViewportTransform: function (vpt) {
  6186. this.viewportTransform = vpt;
  6187. this.renderAll();
  6188. for (var i = 0, len = this._objects.length; i < len; i++) {
  6189. this._objects[i].setCoords();
  6190. }
  6191. return this;
  6192. },
  6193.  
  6194. /**
  6195. * Sets zoom level of this canvas instance, zoom centered around point
  6196. * @param {fabric.Point} point to zoom with respect to
  6197. * @param {Number} value to set zoom to, less than 1 zooms out
  6198. * @return {fabric.Canvas} instance
  6199. * @chainable true
  6200. */
  6201. zoomToPoint: function (point, value) {
  6202. // TODO: just change the scale, preserve other transformations
  6203. var before = point;
  6204. point = fabric.util.transformPoint(point, fabric.util.invertTransform(this.viewportTransform));
  6205. this.viewportTransform[0] = value;
  6206. this.viewportTransform[3] = value;
  6207. var after = fabric.util.transformPoint(point, this.viewportTransform);
  6208. this.viewportTransform[4] += before.x - after.x;
  6209. this.viewportTransform[5] += before.y - after.y;
  6210. this.renderAll();
  6211. for (var i = 0, len = this._objects.length; i < len; i++) {
  6212. this._objects[i].setCoords();
  6213. }
  6214. return this;
  6215. },
  6216.  
  6217. /**
  6218. * Sets zoom level of this canvas instance
  6219. * @param {Number} value to set zoom to, less than 1 zooms out
  6220. * @return {fabric.Canvas} instance
  6221. * @chainable true
  6222. */
  6223. setZoom: function (value) {
  6224. this.zoomToPoint(new fabric.Point(0, 0), value);
  6225. return this;
  6226. },
  6227.  
  6228. /**
  6229. * Pan viewport so as to place point at top left corner of canvas
  6230. * @param {fabric.Point} point to move to
  6231. * @return {fabric.Canvas} instance
  6232. * @chainable true
  6233. */
  6234. absolutePan: function (point) {
  6235. this.viewportTransform[4] = -point.x;
  6236. this.viewportTransform[5] = -point.y;
  6237. this.renderAll();
  6238. for (var i = 0, len = this._objects.length; i < len; i++) {
  6239. this._objects[i].setCoords();
  6240. }
  6241. return this;
  6242. },
  6243.  
  6244. /**
  6245. * Pans viewpoint relatively
  6246. * @param {fabric.Point} point (position vector) to move by
  6247. * @return {fabric.Canvas} instance
  6248. * @chainable true
  6249. */
  6250. relativePan: function (point) {
  6251. return this.absolutePan(new fabric.Point(
  6252. -point.x - this.viewportTransform[4],
  6253. -point.y - this.viewportTransform[5]
  6254. ));
  6255. },
  6256.  
  6257. /**
  6258. * Returns &lt;canvas> element corresponding to this instance
  6259. * @return {HTMLCanvasElement}
  6260. */
  6261. getElement: function () {
  6262. return this.lowerCanvasEl;
  6263. },
  6264.  
  6265. /**
  6266. * Returns currently selected object, if any
  6267. * @return {fabric.Object}
  6268. */
  6269. getActiveObject: function() {
  6270. return null;
  6271. },
  6272.  
  6273. /**
  6274. * Returns currently selected group of object, if any
  6275. * @return {fabric.Group}
  6276. */
  6277. getActiveGroup: function() {
  6278. return null;
  6279. },
  6280.  
  6281. /**
  6282. * Given a context, renders an object on that context
  6283. * @param {CanvasRenderingContext2D} ctx Context to render object on
  6284. * @param {fabric.Object} object Object to render
  6285. * @private
  6286. */
  6287. _draw: function (ctx, object) {
  6288. if (!object) {
  6289. return;
  6290. }
  6291.  
  6292. ctx.save();
  6293. var v = this.viewportTransform;
  6294. ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]);
  6295. if (this._shouldRenderObject(object)) {
  6296. object.render(ctx);
  6297. }
  6298. ctx.restore();
  6299. if (!this.controlsAboveOverlay) {
  6300. object._renderControls(ctx);
  6301. }
  6302. },
  6303.  
  6304. _shouldRenderObject: function(object) {
  6305. if (!object) {
  6306. return false;
  6307. }
  6308. return (object !== this.getActiveGroup() || !this.preserveObjectStacking);
  6309. },
  6310.  
  6311. /**
  6312. * @private
  6313. * @param {fabric.Object} obj Object that was added
  6314. */
  6315. _onObjectAdded: function(obj) {
  6316. this.stateful && obj.setupState();
  6317. obj.canvas = this;
  6318. obj.setCoords();
  6319. this.fire('object:added', { target: obj });
  6320. obj.fire('added');
  6321. },
  6322.  
  6323. /**
  6324. * @private
  6325. * @param {fabric.Object} obj Object that was removed
  6326. */
  6327. _onObjectRemoved: function(obj) {
  6328. // removing active object should fire "selection:cleared" events
  6329. if (this.getActiveObject() === obj) {
  6330. this.fire('before:selection:cleared', { target: obj });
  6331. this._discardActiveObject();
  6332. this.fire('selection:cleared');
  6333. }
  6334.  
  6335. this.fire('object:removed', { target: obj });
  6336. obj.fire('removed');
  6337. },
  6338.  
  6339. /**
  6340. * Clears specified context of canvas element
  6341. * @param {CanvasRenderingContext2D} ctx Context to clear
  6342. * @return {fabric.Canvas} thisArg
  6343. * @chainable
  6344. */
  6345. clearContext: function(ctx) {
  6346. ctx.clearRect(0, 0, this.width, this.height);
  6347. return this;
  6348. },
  6349.  
  6350. /**
  6351. * Returns context of canvas where objects are drawn
  6352. * @return {CanvasRenderingContext2D}
  6353. */
  6354. getContext: function () {
  6355. return this.contextContainer;
  6356. },
  6357.  
  6358. /**
  6359. * Clears all contexts (background, main, top) of an instance
  6360. * @return {fabric.Canvas} thisArg
  6361. * @chainable
  6362. */
  6363. clear: function () {
  6364. this._objects.length = 0;
  6365. if (this.discardActiveGroup) {
  6366. this.discardActiveGroup();
  6367. }
  6368. if (this.discardActiveObject) {
  6369. this.discardActiveObject();
  6370. }
  6371. this.clearContext(this.contextContainer);
  6372. if (this.contextTop) {
  6373. this.clearContext(this.contextTop);
  6374. }
  6375. this.fire('canvas:cleared');
  6376. this.renderAll();
  6377. return this;
  6378. },
  6379.  
  6380. /**
  6381. * Renders both the top canvas and the secondary container canvas.
  6382. * @param {Boolean} [allOnTop] Whether we want to force all images to be rendered on the top canvas
  6383. * @return {fabric.Canvas} instance
  6384. * @chainable
  6385. */
  6386. renderAll: function (allOnTop) {
  6387. var canvasToDrawOn = this[(allOnTop === true && this.interactive) ? 'contextTop' : 'contextContainer'],
  6388. activeGroup = this.getActiveGroup();
  6389.  
  6390. if (this.contextTop && this.selection && !this._groupSelector) {
  6391. this.clearContext(this.contextTop);
  6392. }
  6393.  
  6394. if (!allOnTop) {
  6395. this.clearContext(canvasToDrawOn);
  6396. }
  6397.  
  6398. this.fire('before:render');
  6399.  
  6400. if (this.clipTo) {
  6401. fabric.util.clipContext(this, canvasToDrawOn);
  6402. }
  6403.  
  6404. this._renderBackground(canvasToDrawOn);
  6405. this._renderObjects(canvasToDrawOn, activeGroup);
  6406. this._renderActiveGroup(canvasToDrawOn, activeGroup);
  6407.  
  6408. if (this.clipTo) {
  6409. canvasToDrawOn.restore();
  6410. }
  6411.  
  6412. this._renderOverlay(canvasToDrawOn);
  6413.  
  6414. if (this.controlsAboveOverlay && this.interactive) {
  6415. this.drawControls(canvasToDrawOn);
  6416. }
  6417.  
  6418. this.fire('after:render');
  6419.  
  6420. return this;
  6421. },
  6422.  
  6423. /**
  6424. * @private
  6425. * @param {CanvasRenderingContext2D} ctx Context to render on
  6426. * @param {fabric.Group} activeGroup
  6427. */
  6428. _renderObjects: function(ctx, activeGroup) {
  6429. var i, length;
  6430.  
  6431. // fast path
  6432. if (!activeGroup || this.preserveObjectStacking) {
  6433. for (i = 0, length = this._objects.length; i < length; ++i) {
  6434. this._draw(ctx, this._objects[i]);
  6435. }
  6436. }
  6437. else {
  6438. for (i = 0, length = this._objects.length; i < length; ++i) {
  6439. if (this._objects[i] && !activeGroup.contains(this._objects[i])) {
  6440. this._draw(ctx, this._objects[i]);
  6441. }
  6442. }
  6443. }
  6444. },
  6445.  
  6446. /**
  6447. * @private
  6448. * @param {CanvasRenderingContext2D} ctx Context to render on
  6449. * @param {fabric.Group} activeGroup
  6450. */
  6451. _renderActiveGroup: function(ctx, activeGroup) {
  6452.  
  6453. // delegate rendering to group selection (if one exists)
  6454. if (activeGroup) {
  6455.  
  6456. //Store objects in group preserving order, then replace
  6457. var sortedObjects = [];
  6458. this.forEachObject(function (object) {
  6459. if (activeGroup.contains(object)) {
  6460. sortedObjects.push(object);
  6461. }
  6462. });
  6463. activeGroup._set('objects', sortedObjects);
  6464. this._draw(ctx, activeGroup);
  6465. }
  6466. },
  6467.  
  6468. /**
  6469. * @private
  6470. * @param {CanvasRenderingContext2D} ctx Context to render on
  6471. */
  6472. _renderBackground: function(ctx) {
  6473. if (this.backgroundColor) {
  6474. ctx.fillStyle = this.backgroundColor.toLive
  6475. ? this.backgroundColor.toLive(ctx)
  6476. : this.backgroundColor;
  6477.  
  6478. ctx.fillRect(
  6479. this.backgroundColor.offsetX || 0,
  6480. this.backgroundColor.offsetY || 0,
  6481. this.width,
  6482. this.height);
  6483. }
  6484. if (this.backgroundImage) {
  6485. this._draw(ctx, this.backgroundImage);
  6486. }
  6487. },
  6488.  
  6489. /**
  6490. * @private
  6491. * @param {CanvasRenderingContext2D} ctx Context to render on
  6492. */
  6493. _renderOverlay: function(ctx) {
  6494. if (this.overlayColor) {
  6495. ctx.fillStyle = this.overlayColor.toLive
  6496. ? this.overlayColor.toLive(ctx)
  6497. : this.overlayColor;
  6498.  
  6499. ctx.fillRect(
  6500. this.overlayColor.offsetX || 0,
  6501. this.overlayColor.offsetY || 0,
  6502. this.width,
  6503. this.height);
  6504. }
  6505. if (this.overlayImage) {
  6506. this._draw(ctx, this.overlayImage);
  6507. }
  6508. },
  6509.  
  6510. /**
  6511. * Method to render only the top canvas.
  6512. * Also used to render the group selection box.
  6513. * @return {fabric.Canvas} thisArg
  6514. * @chainable
  6515. */
  6516. renderTop: function () {
  6517. var ctx = this.contextTop || this.contextContainer;
  6518. this.clearContext(ctx);
  6519.  
  6520. // we render the top context - last object
  6521. if (this.selection && this._groupSelector) {
  6522. this._drawSelection();
  6523. }
  6524.  
  6525. // delegate rendering to group selection if one exists
  6526. // used for drawing selection borders/controls
  6527. var activeGroup = this.getActiveGroup();
  6528. if (activeGroup) {
  6529. activeGroup.render(ctx);
  6530. }
  6531.  
  6532. this._renderOverlay(ctx);
  6533.  
  6534. this.fire('after:render');
  6535.  
  6536. return this;
  6537. },
  6538.  
  6539. /**
  6540. * Returns coordinates of a center of canvas.
  6541. * Returned value is an object with top and left properties
  6542. * @return {Object} object with "top" and "left" number values
  6543. */
  6544. getCenter: function () {
  6545. return {
  6546. top: this.getHeight() / 2,
  6547. left: this.getWidth() / 2
  6548. };
  6549. },
  6550.  
  6551. /**
  6552. * Centers object horizontally.
  6553. * You might need to call `setCoords` on an object after centering, to update controls area.
  6554. * @param {fabric.Object} object Object to center horizontally
  6555. * @return {fabric.Canvas} thisArg
  6556. */
  6557. centerObjectH: function (object) {
  6558. this._centerObject(object, new fabric.Point(this.getCenter().left, object.getCenterPoint().y));
  6559. this.renderAll();
  6560. return this;
  6561. },
  6562.  
  6563. /**
  6564. * Centers object vertically.
  6565. * You might need to call `setCoords` on an object after centering, to update controls area.
  6566. * @param {fabric.Object} object Object to center vertically
  6567. * @return {fabric.Canvas} thisArg
  6568. * @chainable
  6569. */
  6570. centerObjectV: function (object) {
  6571. this._centerObject(object, new fabric.Point(object.getCenterPoint().x, this.getCenter().top));
  6572. this.renderAll();
  6573. return this;
  6574. },
  6575.  
  6576. /**
  6577. * Centers object vertically and horizontally.
  6578. * You might need to call `setCoords` on an object after centering, to update controls area.
  6579. * @param {fabric.Object} object Object to center vertically and horizontally
  6580. * @return {fabric.Canvas} thisArg
  6581. * @chainable
  6582. */
  6583. centerObject: function(object) {
  6584. var center = this.getCenter();
  6585.  
  6586. this._centerObject(object, new fabric.Point(center.left, center.top));
  6587. this.renderAll();
  6588. return this;
  6589. },
  6590.  
  6591. /**
  6592. * @private
  6593. * @param {fabric.Object} object Object to center
  6594. * @param {fabric.Point} center Center point
  6595. * @return {fabric.Canvas} thisArg
  6596. * @chainable
  6597. */
  6598. _centerObject: function(object, center) {
  6599. object.setPositionByOrigin(center, 'center', 'center');
  6600. return this;
  6601. },
  6602.  
  6603. /**
  6604. * Returs dataless JSON representation of canvas
  6605. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  6606. * @return {String} json string
  6607. */
  6608. toDatalessJSON: function (propertiesToInclude) {
  6609. return this.toDatalessObject(propertiesToInclude);
  6610. },
  6611.  
  6612. /**
  6613. * Returns object representation of canvas
  6614. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  6615. * @return {Object} object representation of an instance
  6616. */
  6617. toObject: function (propertiesToInclude) {
  6618. return this._toObjectMethod('toObject', propertiesToInclude);
  6619. },
  6620.  
  6621. /**
  6622. * Returns dataless object representation of canvas
  6623. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  6624. * @return {Object} object representation of an instance
  6625. */
  6626. toDatalessObject: function (propertiesToInclude) {
  6627. return this._toObjectMethod('toDatalessObject', propertiesToInclude);
  6628. },
  6629.  
  6630. /**
  6631. * @private
  6632. */
  6633. _toObjectMethod: function (methodName, propertiesToInclude) {
  6634.  
  6635. var activeGroup = this.getActiveGroup();
  6636. if (activeGroup) {
  6637. this.discardActiveGroup();
  6638. }
  6639.  
  6640. var data = {
  6641. objects: this._toObjects(methodName, propertiesToInclude)
  6642. };
  6643.  
  6644. extend(data, this.__serializeBgOverlay());
  6645.  
  6646. fabric.util.populateWithProperties(this, data, propertiesToInclude);
  6647.  
  6648. if (activeGroup) {
  6649. this.setActiveGroup(new fabric.Group(activeGroup.getObjects(), {
  6650. originX: 'center',
  6651. originY: 'center'
  6652. }));
  6653. activeGroup.forEachObject(function(o) {
  6654. o.set('active', true);
  6655. });
  6656.  
  6657. if (this._currentTransform) {
  6658. this._currentTransform.target = this.getActiveGroup();
  6659. }
  6660. }
  6661.  
  6662. return data;
  6663. },
  6664.  
  6665. /**
  6666. * @private
  6667. */
  6668. _toObjects: function(methodName, propertiesToInclude) {
  6669. return this.getObjects().map(function(instance) {
  6670. return this._toObject(instance, methodName, propertiesToInclude);
  6671. }, this);
  6672. },
  6673.  
  6674. /**
  6675. * @private
  6676. */
  6677. _toObject: function(instance, methodName, propertiesToInclude) {
  6678. var originalValue;
  6679.  
  6680. if (!this.includeDefaultValues) {
  6681. originalValue = instance.includeDefaultValues;
  6682. instance.includeDefaultValues = false;
  6683. }
  6684. var object = instance[methodName](propertiesToInclude);
  6685. if (!this.includeDefaultValues) {
  6686. instance.includeDefaultValues = originalValue;
  6687. }
  6688. return object;
  6689. },
  6690.  
  6691. /**
  6692. * @private
  6693. */
  6694. __serializeBgOverlay: function() {
  6695. var data = {
  6696. background: (this.backgroundColor && this.backgroundColor.toObject)
  6697. ? this.backgroundColor.toObject()
  6698. : this.backgroundColor
  6699. };
  6700.  
  6701. if (this.overlayColor) {
  6702. data.overlay = this.overlayColor.toObject
  6703. ? this.overlayColor.toObject()
  6704. : this.overlayColor;
  6705. }
  6706. if (this.backgroundImage) {
  6707. data.backgroundImage = this.backgroundImage.toObject();
  6708. }
  6709. if (this.overlayImage) {
  6710. data.overlayImage = this.overlayImage.toObject();
  6711. }
  6712.  
  6713. return data;
  6714. },
  6715.  
  6716. /* _TO_SVG_START_ */
  6717. /**
  6718. * When true, getSvgTransform() will apply the StaticCanvas.viewportTransform to the SVG transformation. When true,
  6719. * a zoomed canvas will then produce zoomed SVG output.
  6720. * @type Boolean
  6721. * @default
  6722. */
  6723. svgViewportTransformation: true,
  6724.  
  6725. /**
  6726. * Returns SVG representation of canvas
  6727. * @function
  6728. * @param {Object} [options] Options object for SVG output
  6729. * @param {Boolean} [options.suppressPreamble=false] If true xml tag is not included
  6730. * @param {Object} [options.viewBox] SVG viewbox object
  6731. * @param {Number} [options.viewBox.x] x-cooridnate of viewbox
  6732. * @param {Number} [options.viewBox.y] y-coordinate of viewbox
  6733. * @param {Number} [options.viewBox.width] Width of viewbox
  6734. * @param {Number} [options.viewBox.height] Height of viewbox
  6735. * @param {String} [options.encoding=UTF-8] Encoding of SVG output
  6736. * @param {Function} [reviver] Method for further parsing of svg elements, called after each fabric object converted into svg representation.
  6737. * @return {String} SVG string
  6738. * @tutorial {@link http://fabricjs.com/fabric-intro-part-3/#serialization}
  6739. * @see {@link http://jsfiddle.net/fabricjs/jQ3ZZ/|jsFiddle demo}
  6740. * @example <caption>Normal SVG output</caption>
  6741. * var svg = canvas.toSVG();
  6742. * @example <caption>SVG output without preamble (without &lt;?xml ../>)</caption>
  6743. * var svg = canvas.toSVG({suppressPreamble: true});
  6744. * @example <caption>SVG output with viewBox attribute</caption>
  6745. * var svg = canvas.toSVG({
  6746. * viewBox: {
  6747. * x: 100,
  6748. * y: 100,
  6749. * width: 200,
  6750. * height: 300
  6751. * }
  6752. * });
  6753. * @example <caption>SVG output with different encoding (default: UTF-8)</caption>
  6754. * var svg = canvas.toSVG({encoding: 'ISO-8859-1'});
  6755. * @example <caption>Modify SVG output with reviver function</caption>
  6756. * var svg = canvas.toSVG(null, function(svg) {
  6757. * return svg.replace('stroke-dasharray: ; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; ', '');
  6758. * });
  6759. */
  6760. toSVG: function(options, reviver) {
  6761. options || (options = { });
  6762.  
  6763. var markup = [];
  6764.  
  6765. this._setSVGPreamble(markup, options);
  6766. this._setSVGHeader(markup, options);
  6767.  
  6768. this._setSVGBgOverlayColor(markup, 'backgroundColor');
  6769. this._setSVGBgOverlayImage(markup, 'backgroundImage');
  6770.  
  6771. this._setSVGObjects(markup, reviver);
  6772.  
  6773. this._setSVGBgOverlayColor(markup, 'overlayColor');
  6774. this._setSVGBgOverlayImage(markup, 'overlayImage');
  6775.  
  6776. markup.push('</svg>');
  6777.  
  6778. return markup.join('');
  6779. },
  6780.  
  6781. /**
  6782. * @private
  6783. */
  6784. _setSVGPreamble: function(markup, options) {
  6785. if (!options.suppressPreamble) {
  6786. markup.push(
  6787. '<?xml version="1.0" encoding="', (options.encoding || 'UTF-8'), '" standalone="no" ?>',
  6788. '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" ',
  6789. '"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n'
  6790. );
  6791. }
  6792. },
  6793.  
  6794. /**
  6795. * @private
  6796. */
  6797. _setSVGHeader: function(markup, options) {
  6798. var width, height, vpt;
  6799.  
  6800. if (options.viewBox) {
  6801. width = options.viewBox.width;
  6802. height = options.viewBox.height;
  6803. }
  6804. else {
  6805. width = this.width;
  6806. height = this.height;
  6807. if (!this.svgViewportTransformation) {
  6808. vpt = this.viewportTransform;
  6809. width /= vpt[0];
  6810. height /= vpt[3];
  6811. }
  6812. }
  6813.  
  6814. markup.push(
  6815. '<svg ',
  6816. 'xmlns="http://www.w3.org/2000/svg" ',
  6817. 'xmlns:xlink="http://www.w3.org/1999/xlink" ',
  6818. 'version="1.1" ',
  6819. 'width="', width, '" ',
  6820. 'height="', height, '" ',
  6821. (this.backgroundColor && !this.backgroundColor.toLive
  6822. ? 'style="background-color: ' + this.backgroundColor + '" '
  6823. : null),
  6824. (options.viewBox
  6825. ? 'viewBox="' +
  6826. options.viewBox.x + ' ' +
  6827. options.viewBox.y + ' ' +
  6828. options.viewBox.width + ' ' +
  6829. options.viewBox.height + '" '
  6830. : null),
  6831. 'xml:space="preserve">',
  6832. '<desc>Created with Fabric.js ', fabric.version, '</desc>',
  6833. '<defs>',
  6834. fabric.createSVGFontFacesMarkup(this.getObjects()),
  6835. fabric.createSVGRefElementsMarkup(this),
  6836. '</defs>'
  6837. );
  6838. },
  6839.  
  6840. /**
  6841. * @private
  6842. */
  6843. _setSVGObjects: function(markup, reviver) {
  6844. var activeGroup = this.getActiveGroup();
  6845. if (activeGroup) {
  6846. this.discardActiveGroup();
  6847. }
  6848. for (var i = 0, objects = this.getObjects(), len = objects.length; i < len; i++) {
  6849. markup.push(objects[i].toSVG(reviver));
  6850. }
  6851. if (activeGroup) {
  6852. this.setActiveGroup(new fabric.Group(activeGroup.getObjects()));
  6853. activeGroup.forEachObject(function(o) {
  6854. o.set('active', true);
  6855. });
  6856. }
  6857. },
  6858.  
  6859. /**
  6860. * @private
  6861. */
  6862. _setSVGBgOverlayImage: function(markup, property) {
  6863. if (this[property] && this[property].toSVG) {
  6864. markup.push(this[property].toSVG());
  6865. }
  6866. },
  6867.  
  6868. /**
  6869. * @private
  6870. */
  6871. _setSVGBgOverlayColor: function(markup, property) {
  6872. if (this[property] && this[property].source) {
  6873. markup.push(
  6874. '<rect x="', this[property].offsetX, '" y="', this[property].offsetY, '" ',
  6875. 'width="',
  6876. (this[property].repeat === 'repeat-y' || this[property].repeat === 'no-repeat'
  6877. ? this[property].source.width
  6878. : this.width),
  6879. '" height="',
  6880. (this[property].repeat === 'repeat-x' || this[property].repeat === 'no-repeat'
  6881. ? this[property].source.height
  6882. : this.height),
  6883. '" fill="url(#' + property + 'Pattern)"',
  6884. '></rect>'
  6885. );
  6886. }
  6887. else if (this[property] && property === 'overlayColor') {
  6888. markup.push(
  6889. '<rect x="0" y="0" ',
  6890. 'width="', this.width,
  6891. '" height="', this.height,
  6892. '" fill="', this[property], '"',
  6893. '></rect>'
  6894. );
  6895. }
  6896. },
  6897. /* _TO_SVG_END_ */
  6898.  
  6899. /**
  6900. * Moves an object to the bottom of the stack of drawn objects
  6901. * @param {fabric.Object} object Object to send to back
  6902. * @return {fabric.Canvas} thisArg
  6903. * @chainable
  6904. */
  6905. sendToBack: function (object) {
  6906. removeFromArray(this._objects, object);
  6907. this._objects.unshift(object);
  6908. return this.renderAll && this.renderAll();
  6909. },
  6910.  
  6911. /**
  6912. * Moves an object to the top of the stack of drawn objects
  6913. * @param {fabric.Object} object Object to send
  6914. * @return {fabric.Canvas} thisArg
  6915. * @chainable
  6916. */
  6917. bringToFront: function (object) {
  6918. removeFromArray(this._objects, object);
  6919. this._objects.push(object);
  6920. return this.renderAll && this.renderAll();
  6921. },
  6922.  
  6923. /**
  6924. * Moves an object down in stack of drawn objects
  6925. * @param {fabric.Object} object Object to send
  6926. * @param {Boolean} [intersecting] If `true`, send object behind next lower intersecting object
  6927. * @return {fabric.Canvas} thisArg
  6928. * @chainable
  6929. */
  6930. sendBackwards: function (object, intersecting) {
  6931. var idx = this._objects.indexOf(object);
  6932.  
  6933. // if object is not on the bottom of stack
  6934. if (idx !== 0) {
  6935. var newIdx = this._findNewLowerIndex(object, idx, intersecting);
  6936.  
  6937. removeFromArray(this._objects, object);
  6938. this._objects.splice(newIdx, 0, object);
  6939. this.renderAll && this.renderAll();
  6940. }
  6941. return this;
  6942. },
  6943.  
  6944. /**
  6945. * @private
  6946. */
  6947. _findNewLowerIndex: function(object, idx, intersecting) {
  6948. var newIdx;
  6949.  
  6950. if (intersecting) {
  6951. newIdx = idx;
  6952.  
  6953. // traverse down the stack looking for the nearest intersecting object
  6954. for (var i = idx - 1; i >= 0; --i) {
  6955.  
  6956. var isIntersecting = object.intersectsWithObject(this._objects[i]) ||
  6957. object.isContainedWithinObject(this._objects[i]) ||
  6958. this._objects[i].isContainedWithinObject(object);
  6959.  
  6960. if (isIntersecting) {
  6961. newIdx = i;
  6962. break;
  6963. }
  6964. }
  6965. }
  6966. else {
  6967. newIdx = idx - 1;
  6968. }
  6969.  
  6970. return newIdx;
  6971. },
  6972.  
  6973. /**
  6974. * Moves an object up in stack of drawn objects
  6975. * @param {fabric.Object} object Object to send
  6976. * @param {Boolean} [intersecting] If `true`, send object in front of next upper intersecting object
  6977. * @return {fabric.Canvas} thisArg
  6978. * @chainable
  6979. */
  6980. bringForward: function (object, intersecting) {
  6981. var idx = this._objects.indexOf(object);
  6982.  
  6983. // if object is not on top of stack (last item in an array)
  6984. if (idx !== this._objects.length - 1) {
  6985. var newIdx = this._findNewUpperIndex(object, idx, intersecting);
  6986.  
  6987. removeFromArray(this._objects, object);
  6988. this._objects.splice(newIdx, 0, object);
  6989. this.renderAll && this.renderAll();
  6990. }
  6991. return this;
  6992. },
  6993.  
  6994. /**
  6995. * @private
  6996. */
  6997. _findNewUpperIndex: function(object, idx, intersecting) {
  6998. var newIdx;
  6999.  
  7000. if (intersecting) {
  7001. newIdx = idx;
  7002.  
  7003. // traverse up the stack looking for the nearest intersecting object
  7004. for (var i = idx + 1; i < this._objects.length; ++i) {
  7005.  
  7006. var isIntersecting = object.intersectsWithObject(this._objects[i]) ||
  7007. object.isContainedWithinObject(this._objects[i]) ||
  7008. this._objects[i].isContainedWithinObject(object);
  7009.  
  7010. if (isIntersecting) {
  7011. newIdx = i;
  7012. break;
  7013. }
  7014. }
  7015. }
  7016. else {
  7017. newIdx = idx + 1;
  7018. }
  7019.  
  7020. return newIdx;
  7021. },
  7022.  
  7023. /**
  7024. * Moves an object to specified level in stack of drawn objects
  7025. * @param {fabric.Object} object Object to send
  7026. * @param {Number} index Position to move to
  7027. * @return {fabric.Canvas} thisArg
  7028. * @chainable
  7029. */
  7030. moveTo: function (object, index) {
  7031. removeFromArray(this._objects, object);
  7032. this._objects.splice(index, 0, object);
  7033. return this.renderAll && this.renderAll();
  7034. },
  7035.  
  7036. /**
  7037. * Clears a canvas element and removes all event listeners
  7038. * @return {fabric.Canvas} thisArg
  7039. * @chainable
  7040. */
  7041. dispose: function () {
  7042. this.clear();
  7043. this.interactive && this.removeListeners();
  7044. return this;
  7045. },
  7046.  
  7047. /**
  7048. * Returns a string representation of an instance
  7049. * @return {String} string representation of an instance
  7050. */
  7051. toString: function () {
  7052. return '#<fabric.Canvas (' + this.complexity() + '): ' +
  7053. '{ objects: ' + this.getObjects().length + ' }>';
  7054. }
  7055. });
  7056.  
  7057. extend(fabric.StaticCanvas.prototype, fabric.Observable);
  7058. extend(fabric.StaticCanvas.prototype, fabric.Collection);
  7059. extend(fabric.StaticCanvas.prototype, fabric.DataURLExporter);
  7060.  
  7061. extend(fabric.StaticCanvas, /** @lends fabric.StaticCanvas */ {
  7062.  
  7063. /**
  7064. * @static
  7065. * @type String
  7066. * @default
  7067. */
  7068. EMPTY_JSON: '{"objects": [], "background": "white"}',
  7069.  
  7070. /**
  7071. * Provides a way to check support of some of the canvas methods
  7072. * (either those of HTMLCanvasElement itself, or rendering context)
  7073. *
  7074. * @param {String} methodName Method to check support for;
  7075. * Could be one of "getImageData", "toDataURL", "toDataURLWithQuality" or "setLineDash"
  7076. * @return {Boolean | null} `true` if method is supported (or at least exists),
  7077. * `null` if canvas element or context can not be initialized
  7078. */
  7079. supports: function (methodName) {
  7080. var el = fabric.util.createCanvasElement();
  7081.  
  7082. if (!el || !el.getContext) {
  7083. return null;
  7084. }
  7085.  
  7086. var ctx = el.getContext('2d');
  7087. if (!ctx) {
  7088. return null;
  7089. }
  7090.  
  7091. switch (methodName) {
  7092.  
  7093. case 'getImageData':
  7094. return typeof ctx.getImageData !== 'undefined';
  7095.  
  7096. case 'setLineDash':
  7097. return typeof ctx.setLineDash !== 'undefined';
  7098.  
  7099. case 'toDataURL':
  7100. return typeof el.toDataURL !== 'undefined';
  7101.  
  7102. case 'toDataURLWithQuality':
  7103. try {
  7104. el.toDataURL('image/jpeg', 0);
  7105. return true;
  7106. }
  7107. catch (e) { }
  7108. return false;
  7109.  
  7110. default:
  7111. return null;
  7112. }
  7113. }
  7114. });
  7115.  
  7116. /**
  7117. * Returns JSON representation of canvas
  7118. * @function
  7119. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  7120. * @return {String} JSON string
  7121. * @tutorial {@link http://fabricjs.com/fabric-intro-part-3/#serialization}
  7122. * @see {@link http://jsfiddle.net/fabricjs/pec86/|jsFiddle demo}
  7123. * @example <caption>JSON without additional properties</caption>
  7124. * var json = canvas.toJSON();
  7125. * @example <caption>JSON with additional properties included</caption>
  7126. * var json = canvas.toJSON(['lockMovementX', 'lockMovementY', 'lockRotation', 'lockScalingX', 'lockScalingY', 'lockUniScaling']);
  7127. * @example <caption>JSON without default values</caption>
  7128. * canvas.includeDefaultValues = false;
  7129. * var json = canvas.toJSON();
  7130. */
  7131. fabric.StaticCanvas.prototype.toJSON = fabric.StaticCanvas.prototype.toObject;
  7132.  
  7133. })();
  7134.  
  7135.  
  7136. /**
  7137. * BaseBrush class
  7138. * @class fabric.BaseBrush
  7139. * @see {@link http://fabricjs.com/freedrawing/|Freedrawing demo}
  7140. */
  7141. fabric.BaseBrush = fabric.util.createClass(/** @lends fabric.BaseBrush.prototype */ {
  7142.  
  7143. /**
  7144. * Color of a brush
  7145. * @type String
  7146. * @default
  7147. */
  7148. color: 'rgb(0, 0, 0)',
  7149.  
  7150. /**
  7151. * Width of a brush
  7152. * @type Number
  7153. * @default
  7154. */
  7155. width: 1,
  7156.  
  7157. /**
  7158. * Shadow object representing shadow of this shape.
  7159. * <b>Backwards incompatibility note:</b> This property replaces "shadowColor" (String), "shadowOffsetX" (Number),
  7160. * "shadowOffsetY" (Number) and "shadowBlur" (Number) since v1.2.12
  7161. * @type fabric.Shadow
  7162. * @default
  7163. */
  7164. shadow: null,
  7165.  
  7166. /**
  7167. * Line endings style of a brush (one of "butt", "round", "square")
  7168. * @type String
  7169. * @default
  7170. */
  7171. strokeLineCap: 'round',
  7172.  
  7173. /**
  7174. * Corner style of a brush (one of "bevil", "round", "miter")
  7175. * @type String
  7176. * @default
  7177. */
  7178. strokeLineJoin: 'round',
  7179.  
  7180. /**
  7181. * Sets shadow of an object
  7182. * @param {Object|String} [options] Options object or string (e.g. "2px 2px 10px rgba(0,0,0,0.2)")
  7183. * @return {fabric.Object} thisArg
  7184. * @chainable
  7185. */
  7186. setShadow: function(options) {
  7187. this.shadow = new fabric.Shadow(options);
  7188. return this;
  7189. },
  7190.  
  7191. /**
  7192. * Sets brush styles
  7193. * @private
  7194. */
  7195. _setBrushStyles: function() {
  7196. var ctx = this.canvas.contextTop;
  7197.  
  7198. ctx.strokeStyle = this.color;
  7199. ctx.lineWidth = this.width;
  7200. ctx.lineCap = this.strokeLineCap;
  7201. ctx.lineJoin = this.strokeLineJoin;
  7202. },
  7203.  
  7204. /**
  7205. * Sets brush shadow styles
  7206. * @private
  7207. */
  7208. _setShadow: function() {
  7209. if (!this.shadow) {
  7210. return;
  7211. }
  7212.  
  7213. var ctx = this.canvas.contextTop;
  7214.  
  7215. ctx.shadowColor = this.shadow.color;
  7216. ctx.shadowBlur = this.shadow.blur;
  7217. ctx.shadowOffsetX = this.shadow.offsetX;
  7218. ctx.shadowOffsetY = this.shadow.offsetY;
  7219. },
  7220.  
  7221. /**
  7222. * Removes brush shadow styles
  7223. * @private
  7224. */
  7225. _resetShadow: function() {
  7226. var ctx = this.canvas.contextTop;
  7227.  
  7228. ctx.shadowColor = '';
  7229. ctx.shadowBlur = ctx.shadowOffsetX = ctx.shadowOffsetY = 0;
  7230. }
  7231. });
  7232.  
  7233.  
  7234. (function() {
  7235.  
  7236. /**
  7237. * PencilBrush class
  7238. * @class fabric.PencilBrush
  7239. * @extends fabric.BaseBrush
  7240. */
  7241. fabric.PencilBrush = fabric.util.createClass(fabric.BaseBrush, /** @lends fabric.PencilBrush.prototype */ {
  7242.  
  7243. /**
  7244. * Constructor
  7245. * @param {fabric.Canvas} canvas
  7246. * @return {fabric.PencilBrush} Instance of a pencil brush
  7247. */
  7248. initialize: function(canvas) {
  7249. this.canvas = canvas;
  7250. this._points = [ ];
  7251. },
  7252.  
  7253. /**
  7254. * Inovoked on mouse down
  7255. * @param {Object} pointer
  7256. */
  7257. onMouseDown: function(pointer) {
  7258. this._prepareForDrawing(pointer);
  7259. // capture coordinates immediately
  7260. // this allows to draw dots (when movement never occurs)
  7261. this._captureDrawingPath(pointer);
  7262. this._render();
  7263. },
  7264.  
  7265. /**
  7266. * Inovoked on mouse move
  7267. * @param {Object} pointer
  7268. */
  7269. onMouseMove: function(pointer) {
  7270. this._captureDrawingPath(pointer);
  7271. // redraw curve
  7272. // clear top canvas
  7273. this.canvas.clearContext(this.canvas.contextTop);
  7274. this._render();
  7275. },
  7276.  
  7277. /**
  7278. * Invoked on mouse up
  7279. */
  7280. onMouseUp: function() {
  7281. this._finalizeAndAddPath();
  7282. },
  7283.  
  7284. /**
  7285. * @private
  7286. * @param {Object} pointer Actual mouse position related to the canvas.
  7287. */
  7288. _prepareForDrawing: function(pointer) {
  7289.  
  7290. var p = new fabric.Point(pointer.x, pointer.y);
  7291.  
  7292. this._reset();
  7293. this._addPoint(p);
  7294.  
  7295. this.canvas.contextTop.moveTo(p.x, p.y);
  7296. },
  7297.  
  7298. /**
  7299. * @private
  7300. * @param {fabric.Point} point Point to be added to points array
  7301. */
  7302. _addPoint: function(point) {
  7303. this._points.push(point);
  7304. },
  7305.  
  7306. /**
  7307. * Clear points array and set contextTop canvas style.
  7308. * @private
  7309. */
  7310. _reset: function() {
  7311. this._points.length = 0;
  7312.  
  7313. this._setBrushStyles();
  7314. this._setShadow();
  7315. },
  7316.  
  7317. /**
  7318. * @private
  7319. * @param {Object} pointer Actual mouse position related to the canvas.
  7320. */
  7321. _captureDrawingPath: function(pointer) {
  7322. var pointerPoint = new fabric.Point(pointer.x, pointer.y);
  7323. this._addPoint(pointerPoint);
  7324. },
  7325.  
  7326. /**
  7327. * Draw a smooth path on the topCanvas using quadraticCurveTo
  7328. * @private
  7329. */
  7330. _render: function() {
  7331. var ctx = this.canvas.contextTop,
  7332. v = this.canvas.viewportTransform,
  7333. p1 = this._points[0],
  7334. p2 = this._points[1];
  7335.  
  7336. ctx.save();
  7337. ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]);
  7338. ctx.beginPath();
  7339.  
  7340. //if we only have 2 points in the path and they are the same
  7341. //it means that the user only clicked the canvas without moving the mouse
  7342. //then we should be drawing a dot. A path isn't drawn between two identical dots
  7343. //that's why we set them apart a bit
  7344. if (this._points.length === 2 && p1.x === p2.x && p1.y === p2.y) {
  7345. p1.x -= 0.5;
  7346. p2.x += 0.5;
  7347. }
  7348. ctx.moveTo(p1.x, p1.y);
  7349.  
  7350. for (var i = 1, len = this._points.length; i < len; i++) {
  7351. // we pick the point between pi + 1 & pi + 2 as the
  7352. // end point and p1 as our control point.
  7353. var midPoint = p1.midPointFrom(p2);
  7354. ctx.quadraticCurveTo(p1.x, p1.y, midPoint.x, midPoint.y);
  7355.  
  7356. p1 = this._points[i];
  7357. p2 = this._points[i + 1];
  7358. }
  7359. // Draw last line as a straight line while
  7360. // we wait for the next point to be able to calculate
  7361. // the bezier control point
  7362. ctx.lineTo(p1.x, p1.y);
  7363. ctx.stroke();
  7364. ctx.restore();
  7365. },
  7366.  
  7367. /**
  7368. * Converts points to SVG path
  7369. * @param {Array} points Array of points
  7370. * @param {Number} minX
  7371. * @param {Number} minY
  7372. * @return {String} SVG path
  7373. */
  7374. convertPointsToSVGPath: function(points) {
  7375. var path = [],
  7376. p1 = new fabric.Point(points[0].x, points[0].y),
  7377. p2 = new fabric.Point(points[1].x, points[1].y);
  7378.  
  7379. path.push('M ', points[0].x, ' ', points[0].y, ' ');
  7380. for (var i = 1, len = points.length; i < len; i++) {
  7381. var midPoint = p1.midPointFrom(p2);
  7382. // p1 is our bezier control point
  7383. // midpoint is our endpoint
  7384. // start point is p(i-1) value.
  7385. path.push('Q ', p1.x, ' ', p1.y, ' ', midPoint.x, ' ', midPoint.y, ' ');
  7386. p1 = new fabric.Point(points[i].x, points[i].y);
  7387. if ((i + 1) < points.length) {
  7388. p2 = new fabric.Point(points[i + 1].x, points[i + 1].y);
  7389. }
  7390. }
  7391. path.push('L ', p1.x, ' ', p1.y, ' ');
  7392. return path;
  7393. },
  7394.  
  7395. /**
  7396. * Creates fabric.Path object to add on canvas
  7397. * @param {String} pathData Path data
  7398. * @return {fabric.Path} Path to add on canvas
  7399. */
  7400. createPath: function(pathData) {
  7401. var path = new fabric.Path(pathData);
  7402. path.fill = null;
  7403. path.stroke = this.color;
  7404. path.strokeWidth = this.width;
  7405. path.strokeLineCap = this.strokeLineCap;
  7406. path.strokeLineJoin = this.strokeLineJoin;
  7407.  
  7408. if (this.shadow) {
  7409. this.shadow.affectStroke = true;
  7410. path.setShadow(this.shadow);
  7411. }
  7412.  
  7413. return path;
  7414. },
  7415.  
  7416. /**
  7417. * On mouseup after drawing the path on contextTop canvas
  7418. * we use the points captured to create an new fabric path object
  7419. * and add it to the fabric canvas.
  7420. */
  7421. _finalizeAndAddPath: function() {
  7422. var ctx = this.canvas.contextTop;
  7423. ctx.closePath();
  7424.  
  7425. var pathData = this.convertPointsToSVGPath(this._points).join('');
  7426. if (pathData === 'M 0 0 Q 0 0 0 0 L 0 0') {
  7427. // do not create 0 width/height paths, as they are
  7428. // rendered inconsistently across browsers
  7429. // Firefox 4, for example, renders a dot,
  7430. // whereas Chrome 10 renders nothing
  7431. this.canvas.renderAll();
  7432. return;
  7433. }
  7434.  
  7435. var path = this.createPath(pathData);
  7436.  
  7437. this.canvas.add(path);
  7438. path.setCoords();
  7439.  
  7440. this.canvas.clearContext(this.canvas.contextTop);
  7441. this._resetShadow();
  7442. this.canvas.renderAll();
  7443.  
  7444. // fire event 'path' created
  7445. this.canvas.fire('path:created', { path: path });
  7446. }
  7447. });
  7448. })();
  7449.  
  7450.  
  7451. /**
  7452. * CircleBrush class
  7453. * @class fabric.CircleBrush
  7454. */
  7455. fabric.CircleBrush = fabric.util.createClass(fabric.BaseBrush, /** @lends fabric.CircleBrush.prototype */ {
  7456.  
  7457. /**
  7458. * Width of a brush
  7459. * @type Number
  7460. * @default
  7461. */
  7462. width: 10,
  7463.  
  7464. /**
  7465. * Constructor
  7466. * @param {fabric.Canvas} canvas
  7467. * @return {fabric.CircleBrush} Instance of a circle brush
  7468. */
  7469. initialize: function(canvas) {
  7470. this.canvas = canvas;
  7471. this.points = [ ];
  7472. },
  7473. /**
  7474. * Invoked inside on mouse down and mouse move
  7475. * @param {Object} pointer
  7476. */
  7477. drawDot: function(pointer) {
  7478. var point = this.addPoint(pointer),
  7479. ctx = this.canvas.contextTop,
  7480. v = this.canvas.viewportTransform;
  7481. ctx.save();
  7482. ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]);
  7483.  
  7484. ctx.fillStyle = point.fill;
  7485. ctx.beginPath();
  7486. ctx.arc(point.x, point.y, point.radius, 0, Math.PI * 2, false);
  7487. ctx.closePath();
  7488. ctx.fill();
  7489.  
  7490. ctx.restore();
  7491. },
  7492.  
  7493. /**
  7494. * Invoked on mouse down
  7495. */
  7496. onMouseDown: function(pointer) {
  7497. this.points.length = 0;
  7498. this.canvas.clearContext(this.canvas.contextTop);
  7499. this._setShadow();
  7500. this.drawDot(pointer);
  7501. },
  7502.  
  7503. /**
  7504. * Invoked on mouse move
  7505. * @param {Object} pointer
  7506. */
  7507. onMouseMove: function(pointer) {
  7508. this.drawDot(pointer);
  7509. },
  7510.  
  7511. /**
  7512. * Invoked on mouse up
  7513. */
  7514. onMouseUp: function() {
  7515. var originalRenderOnAddRemove = this.canvas.renderOnAddRemove;
  7516. this.canvas.renderOnAddRemove = false;
  7517.  
  7518. var circles = [ ];
  7519.  
  7520. for (var i = 0, len = this.points.length; i < len; i++) {
  7521. var point = this.points[i],
  7522. circle = new fabric.Circle({
  7523. radius: point.radius,
  7524. left: point.x,
  7525. top: point.y,
  7526. originX: 'center',
  7527. originY: 'center',
  7528. fill: point.fill
  7529. });
  7530.  
  7531. this.shadow && circle.setShadow(this.shadow);
  7532.  
  7533. circles.push(circle);
  7534. }
  7535. var group = new fabric.Group(circles, { originX: 'center', originY: 'center' });
  7536. group.canvas = this.canvas;
  7537.  
  7538. this.canvas.add(group);
  7539. this.canvas.fire('path:created', { path: group });
  7540.  
  7541. this.canvas.clearContext(this.canvas.contextTop);
  7542. this._resetShadow();
  7543. this.canvas.renderOnAddRemove = originalRenderOnAddRemove;
  7544. this.canvas.renderAll();
  7545. },
  7546.  
  7547. /**
  7548. * @param {Object} pointer
  7549. * @return {fabric.Point} Just added pointer point
  7550. */
  7551. addPoint: function(pointer) {
  7552. var pointerPoint = new fabric.Point(pointer.x, pointer.y),
  7553.  
  7554. circleRadius = fabric.util.getRandomInt(
  7555. Math.max(0, this.width - 20), this.width + 20) / 2,
  7556.  
  7557. circleColor = new fabric.Color(this.color)
  7558. .setAlpha(fabric.util.getRandomInt(0, 100) / 100)
  7559. .toRgba();
  7560.  
  7561. pointerPoint.radius = circleRadius;
  7562. pointerPoint.fill = circleColor;
  7563.  
  7564. this.points.push(pointerPoint);
  7565.  
  7566. return pointerPoint;
  7567. }
  7568. });
  7569.  
  7570.  
  7571. /**
  7572. * SprayBrush class
  7573. * @class fabric.SprayBrush
  7574. */
  7575. fabric.SprayBrush = fabric.util.createClass( fabric.BaseBrush, /** @lends fabric.SprayBrush.prototype */ {
  7576.  
  7577. /**
  7578. * Width of a spray
  7579. * @type Number
  7580. * @default
  7581. */
  7582. width: 10,
  7583.  
  7584. /**
  7585. * Density of a spray (number of dots per chunk)
  7586. * @type Number
  7587. * @default
  7588. */
  7589. density: 20,
  7590.  
  7591. /**
  7592. * Width of spray dots
  7593. * @type Number
  7594. * @default
  7595. */
  7596. dotWidth: 1,
  7597.  
  7598. /**
  7599. * Width variance of spray dots
  7600. * @type Number
  7601. * @default
  7602. */
  7603. dotWidthVariance: 1,
  7604.  
  7605. /**
  7606. * Whether opacity of a dot should be random
  7607. * @type Boolean
  7608. * @default
  7609. */
  7610. randomOpacity: false,
  7611.  
  7612. /**
  7613. * Whether overlapping dots (rectangles) should be removed (for performance reasons)
  7614. * @type Boolean
  7615. * @default
  7616. */
  7617. optimizeOverlapping: true,
  7618.  
  7619. /**
  7620. * Constructor
  7621. * @param {fabric.Canvas} canvas
  7622. * @return {fabric.SprayBrush} Instance of a spray brush
  7623. */
  7624. initialize: function(canvas) {
  7625. this.canvas = canvas;
  7626. this.sprayChunks = [ ];
  7627. },
  7628.  
  7629. /**
  7630. * Invoked on mouse down
  7631. * @param {Object} pointer
  7632. */
  7633. onMouseDown: function(pointer) {
  7634. this.sprayChunks.length = 0;
  7635. this.canvas.clearContext(this.canvas.contextTop);
  7636. this._setShadow();
  7637.  
  7638. this.addSprayChunk(pointer);
  7639. this.render();
  7640. },
  7641.  
  7642. /**
  7643. * Invoked on mouse move
  7644. * @param {Object} pointer
  7645. */
  7646. onMouseMove: function(pointer) {
  7647. this.addSprayChunk(pointer);
  7648. this.render();
  7649. },
  7650.  
  7651. /**
  7652. * Invoked on mouse up
  7653. */
  7654. onMouseUp: function() {
  7655. var originalRenderOnAddRemove = this.canvas.renderOnAddRemove;
  7656. this.canvas.renderOnAddRemove = false;
  7657.  
  7658. var rects = [ ];
  7659.  
  7660. for (var i = 0, ilen = this.sprayChunks.length; i < ilen; i++) {
  7661. var sprayChunk = this.sprayChunks[i];
  7662.  
  7663. for (var j = 0, jlen = sprayChunk.length; j < jlen; j++) {
  7664.  
  7665. var rect = new fabric.Rect({
  7666. width: sprayChunk[j].width,
  7667. height: sprayChunk[j].width,
  7668. left: sprayChunk[j].x + 1,
  7669. top: sprayChunk[j].y + 1,
  7670. originX: 'center',
  7671. originY: 'center',
  7672. fill: this.color
  7673. });
  7674.  
  7675. this.shadow && rect.setShadow(this.shadow);
  7676. rects.push(rect);
  7677. }
  7678. }
  7679.  
  7680. if (this.optimizeOverlapping) {
  7681. rects = this._getOptimizedRects(rects);
  7682. }
  7683.  
  7684. var group = new fabric.Group(rects, { originX: 'center', originY: 'center' });
  7685. group.canvas = this.canvas;
  7686.  
  7687. this.canvas.add(group);
  7688. this.canvas.fire('path:created', { path: group });
  7689.  
  7690. this.canvas.clearContext(this.canvas.contextTop);
  7691. this._resetShadow();
  7692. this.canvas.renderOnAddRemove = originalRenderOnAddRemove;
  7693. this.canvas.renderAll();
  7694. },
  7695.  
  7696. /**
  7697. * @private
  7698. * @param {Array} rects
  7699. */
  7700. _getOptimizedRects: function(rects) {
  7701.  
  7702. // avoid creating duplicate rects at the same coordinates
  7703. var uniqueRects = { }, key;
  7704.  
  7705. for (var i = 0, len = rects.length; i < len; i++) {
  7706. key = rects[i].left + '' + rects[i].top;
  7707. if (!uniqueRects[key]) {
  7708. uniqueRects[key] = rects[i];
  7709. }
  7710. }
  7711. var uniqueRectsArray = [ ];
  7712. for (key in uniqueRects) {
  7713. uniqueRectsArray.push(uniqueRects[key]);
  7714. }
  7715.  
  7716. return uniqueRectsArray;
  7717. },
  7718.  
  7719. /**
  7720. * Renders brush
  7721. */
  7722. render: function() {
  7723. var ctx = this.canvas.contextTop;
  7724. ctx.fillStyle = this.color;
  7725.  
  7726. var v = this.canvas.viewportTransform;
  7727. ctx.save();
  7728. ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]);
  7729.  
  7730. for (var i = 0, len = this.sprayChunkPoints.length; i < len; i++) {
  7731. var point = this.sprayChunkPoints[i];
  7732. if (typeof point.opacity !== 'undefined') {
  7733. ctx.globalAlpha = point.opacity;
  7734. }
  7735. ctx.fillRect(point.x, point.y, point.width, point.width);
  7736. }
  7737. ctx.restore();
  7738. },
  7739.  
  7740. /**
  7741. * @param {Object} pointer
  7742. */
  7743. addSprayChunk: function(pointer) {
  7744. this.sprayChunkPoints = [ ];
  7745.  
  7746. var x, y, width, radius = this.width / 2;
  7747.  
  7748. for (var i = 0; i < this.density; i++) {
  7749.  
  7750. x = fabric.util.getRandomInt(pointer.x - radius, pointer.x + radius);
  7751. y = fabric.util.getRandomInt(pointer.y - radius, pointer.y + radius);
  7752.  
  7753. if (this.dotWidthVariance) {
  7754. width = fabric.util.getRandomInt(
  7755. // bottom clamp width to 1
  7756. Math.max(1, this.dotWidth - this.dotWidthVariance),
  7757. this.dotWidth + this.dotWidthVariance);
  7758. }
  7759. else {
  7760. width = this.dotWidth;
  7761. }
  7762.  
  7763. var point = new fabric.Point(x, y);
  7764. point.width = width;
  7765.  
  7766. if (this.randomOpacity) {
  7767. point.opacity = fabric.util.getRandomInt(0, 100) / 100;
  7768. }
  7769.  
  7770. this.sprayChunkPoints.push(point);
  7771. }
  7772.  
  7773. this.sprayChunks.push(this.sprayChunkPoints);
  7774. }
  7775. });
  7776.  
  7777.  
  7778. /**
  7779. * PatternBrush class
  7780. * @class fabric.PatternBrush
  7781. * @extends fabric.BaseBrush
  7782. */
  7783. fabric.PatternBrush = fabric.util.createClass(fabric.PencilBrush, /** @lends fabric.PatternBrush.prototype */ {
  7784.  
  7785. getPatternSrc: function() {
  7786.  
  7787. var dotWidth = 20,
  7788. dotDistance = 5,
  7789. patternCanvas = fabric.document.createElement('canvas'),
  7790. patternCtx = patternCanvas.getContext('2d');
  7791.  
  7792. patternCanvas.width = patternCanvas.height = dotWidth + dotDistance;
  7793.  
  7794. patternCtx.fillStyle = this.color;
  7795. patternCtx.beginPath();
  7796. patternCtx.arc(dotWidth / 2, dotWidth / 2, dotWidth / 2, 0, Math.PI * 2, false);
  7797. patternCtx.closePath();
  7798. patternCtx.fill();
  7799.  
  7800. return patternCanvas;
  7801. },
  7802.  
  7803. getPatternSrcFunction: function() {
  7804. return String(this.getPatternSrc).replace('this.color', '"' + this.color + '"');
  7805. },
  7806.  
  7807. /**
  7808. * Creates "pattern" instance property
  7809. */
  7810. getPattern: function() {
  7811. return this.canvas.contextTop.createPattern(this.source || this.getPatternSrc(), 'repeat');
  7812. },
  7813.  
  7814. /**
  7815. * Sets brush styles
  7816. */
  7817. _setBrushStyles: function() {
  7818. this.callSuper('_setBrushStyles');
  7819. this.canvas.contextTop.strokeStyle = this.getPattern();
  7820. },
  7821.  
  7822. /**
  7823. * Creates path
  7824. */
  7825. createPath: function(pathData) {
  7826. var path = this.callSuper('createPath', pathData);
  7827. path.stroke = new fabric.Pattern({
  7828. source: this.source || this.getPatternSrcFunction()
  7829. });
  7830. return path;
  7831. }
  7832. });
  7833.  
  7834.  
  7835. (function() {
  7836.  
  7837. var getPointer = fabric.util.getPointer,
  7838. degreesToRadians = fabric.util.degreesToRadians,
  7839. radiansToDegrees = fabric.util.radiansToDegrees,
  7840. atan2 = Math.atan2,
  7841. abs = Math.abs,
  7842.  
  7843. STROKE_OFFSET = 0.5;
  7844.  
  7845. /**
  7846. * Canvas class
  7847. * @class fabric.Canvas
  7848. * @extends fabric.StaticCanvas
  7849. * @tutorial {@link http://fabricjs.com/fabric-intro-part-1/#canvas}
  7850. * @see {@link fabric.Canvas#initialize} for constructor definition
  7851. *
  7852. * @fires object:modified
  7853. * @fires object:rotating
  7854. * @fires object:scaling
  7855. * @fires object:moving
  7856. * @fires object:selected
  7857. *
  7858. * @fires before:selection:cleared
  7859. * @fires selection:cleared
  7860. * @fires selection:created
  7861. *
  7862. * @fires path:created
  7863. * @fires mouse:down
  7864. * @fires mouse:move
  7865. * @fires mouse:up
  7866. * @fires mouse:over
  7867. * @fires mouse:out
  7868. *
  7869. */
  7870. fabric.Canvas = fabric.util.createClass(fabric.StaticCanvas, /** @lends fabric.Canvas.prototype */ {
  7871.  
  7872. /**
  7873. * Constructor
  7874. * @param {HTMLElement | String} el &lt;canvas> element to initialize instance on
  7875. * @param {Object} [options] Options object
  7876. * @return {Object} thisArg
  7877. */
  7878. initialize: function(el, options) {
  7879. options || (options = { });
  7880.  
  7881. this._initStatic(el, options);
  7882. this._initInteractive();
  7883. this._createCacheCanvas();
  7884.  
  7885. fabric.Canvas.activeInstance = this;
  7886. },
  7887.  
  7888. /**
  7889. * When true, objects can be transformed by one side (unproportionally)
  7890. * @type Boolean
  7891. * @default
  7892. */
  7893. uniScaleTransform: false,
  7894.  
  7895. /**
  7896. * When true, objects use center point as the origin of scale transformation.
  7897. * <b>Backwards incompatibility note:</b> This property replaces "centerTransform" (Boolean).
  7898. * @since 1.3.4
  7899. * @type Boolean
  7900. * @default
  7901. */
  7902. centeredScaling: false,
  7903.  
  7904. /**
  7905. * When true, objects use center point as the origin of rotate transformation.
  7906. * <b>Backwards incompatibility note:</b> This property replaces "centerTransform" (Boolean).
  7907. * @since 1.3.4
  7908. * @type Boolean
  7909. * @default
  7910. */
  7911. centeredRotation: false,
  7912.  
  7913. /**
  7914. * Indicates that canvas is interactive. This property should not be changed.
  7915. * @type Boolean
  7916. * @default
  7917. */
  7918. interactive: true,
  7919.  
  7920. /**
  7921. * Indicates whether group selection should be enabled
  7922. * @type Boolean
  7923. * @default
  7924. */
  7925. selection: true,
  7926.  
  7927. /**
  7928. * Color of selection
  7929. * @type String
  7930. * @default
  7931. */
  7932. selectionColor: 'rgba(100, 100, 255, 0.3)', // blue
  7933.  
  7934. /**
  7935. * Default dash array pattern
  7936. * If not empty the selection border is dashed
  7937. * @type Array
  7938. */
  7939. selectionDashArray: [ ],
  7940.  
  7941. /**
  7942. * Color of the border of selection (usually slightly darker than color of selection itself)
  7943. * @type String
  7944. * @default
  7945. */
  7946. selectionBorderColor: 'rgba(255, 255, 255, 0.3)',
  7947.  
  7948. /**
  7949. * Width of a line used in object/group selection
  7950. * @type Number
  7951. * @default
  7952. */
  7953. selectionLineWidth: 1,
  7954.  
  7955. /**
  7956. * Default cursor value used when hovering over an object on canvas
  7957. * @type String
  7958. * @default
  7959. */
  7960. hoverCursor: 'move',
  7961.  
  7962. /**
  7963. * Default cursor value used when moving an object on canvas
  7964. * @type String
  7965. * @default
  7966. */
  7967. moveCursor: 'move',
  7968.  
  7969. /**
  7970. * Default cursor value used for the entire canvas
  7971. * @type String
  7972. * @default
  7973. */
  7974. defaultCursor: 'default',
  7975.  
  7976. /**
  7977. * Cursor value used during free drawing
  7978. * @type String
  7979. * @default
  7980. */
  7981. freeDrawingCursor: 'crosshair',
  7982.  
  7983. /**
  7984. * Cursor value used for rotation point
  7985. * @type String
  7986. * @default
  7987. */
  7988. rotationCursor: 'crosshair',
  7989.  
  7990. /**
  7991. * Default element class that's given to wrapper (div) element of canvas
  7992. * @type String
  7993. * @default
  7994. */
  7995. containerClass: 'canvas-container',
  7996.  
  7997. /**
  7998. * When true, object detection happens on per-pixel basis rather than on per-bounding-box
  7999. * @type Boolean
  8000. * @default
  8001. */
  8002. perPixelTargetFind: false,
  8003.  
  8004. /**
  8005. * Number of pixels around target pixel to tolerate (consider active) during object detection
  8006. * @type Number
  8007. * @default
  8008. */
  8009. targetFindTolerance: 0,
  8010.  
  8011. /**
  8012. * When true, target detection is skipped when hovering over canvas. This can be used to improve performance.
  8013. * @type Boolean
  8014. * @default
  8015. */
  8016. skipTargetFind: false,
  8017.  
  8018. /**
  8019. * @private
  8020. */
  8021. _initInteractive: function() {
  8022. this._currentTransform = null;
  8023. this._groupSelector = null;
  8024. this._initWrapperElement();
  8025. this._createUpperCanvas();
  8026. this._initEventListeners();
  8027.  
  8028. this.freeDrawingBrush = fabric.PencilBrush && new fabric.PencilBrush(this);
  8029.  
  8030. this.calcOffset();
  8031. },
  8032.  
  8033. /**
  8034. * Resets the current transform to its original values and chooses the type of resizing based on the event
  8035. * @private
  8036. * @param {Event} e Event object fired on mousemove
  8037. */
  8038. _resetCurrentTransform: function(e) {
  8039. var t = this._currentTransform;
  8040.  
  8041. t.target.set({
  8042. scaleX: t.original.scaleX,
  8043. scaleY: t.original.scaleY,
  8044. left: t.original.left,
  8045. top: t.original.top
  8046. });
  8047.  
  8048. if (this._shouldCenterTransform(e, t.target)) {
  8049. if (t.action === 'rotate') {
  8050. this._setOriginToCenter(t.target);
  8051. }
  8052. else {
  8053. if (t.originX !== 'center') {
  8054. if (t.originX === 'right') {
  8055. t.mouseXSign = -1;
  8056. }
  8057. else {
  8058. t.mouseXSign = 1;
  8059. }
  8060. }
  8061. if (t.originY !== 'center') {
  8062. if (t.originY === 'bottom') {
  8063. t.mouseYSign = -1;
  8064. }
  8065. else {
  8066. t.mouseYSign = 1;
  8067. }
  8068. }
  8069.  
  8070. t.originX = 'center';
  8071. t.originY = 'center';
  8072. }
  8073. }
  8074. else {
  8075. t.originX = t.original.originX;
  8076. t.originY = t.original.originY;
  8077. }
  8078. },
  8079.  
  8080. /**
  8081. * Checks if point is contained within an area of given object
  8082. * @param {Event} e Event object
  8083. * @param {fabric.Object} target Object to test against
  8084. * @return {Boolean} true if point is contained within an area of given object
  8085. */
  8086. containsPoint: function (e, target) {
  8087. var pointer = this.getPointer(e, true),
  8088. xy = this._normalizePointer(target, pointer);
  8089.  
  8090. // http://www.geog.ubc.ca/courses/klink/gis.notes/ncgia/u32.html
  8091. // http://idav.ucdavis.edu/~okreylos/TAship/Spring2000/PointInPolygon.html
  8092. return (target.containsPoint(xy) || target._findTargetCorner(pointer));
  8093. },
  8094.  
  8095. /**
  8096. * @private
  8097. */
  8098. _normalizePointer: function (object, pointer) {
  8099. var activeGroup = this.getActiveGroup(),
  8100. x = pointer.x,
  8101. y = pointer.y,
  8102. isObjectInGroup = (
  8103. activeGroup &&
  8104. object.type !== 'group' &&
  8105. activeGroup.contains(object)),
  8106. lt;
  8107.  
  8108. if (isObjectInGroup) {
  8109. lt = new fabric.Point(activeGroup.left, activeGroup.top);
  8110. lt = fabric.util.transformPoint(lt, this.viewportTransform, true);
  8111. x -= lt.x;
  8112. y -= lt.y;
  8113. }
  8114. return { x: x, y: y };
  8115. },
  8116.  
  8117. /**
  8118. * Returns true if object is transparent at a certain location
  8119. * @param {fabric.Object} target Object to check
  8120. * @param {Number} x Left coordinate
  8121. * @param {Number} y Top coordinate
  8122. * @return {Boolean}
  8123. */
  8124. isTargetTransparent: function (target, x, y) {
  8125. var hasBorders = target.hasBorders,
  8126. transparentCorners = target.transparentCorners;
  8127.  
  8128. target.hasBorders = target.transparentCorners = false;
  8129.  
  8130. this._draw(this.contextCache, target);
  8131.  
  8132. target.hasBorders = hasBorders;
  8133. target.transparentCorners = transparentCorners;
  8134.  
  8135. var isTransparent = fabric.util.isTransparent(
  8136. this.contextCache, x, y, this.targetFindTolerance);
  8137.  
  8138. this.clearContext(this.contextCache);
  8139.  
  8140. return isTransparent;
  8141. },
  8142.  
  8143. /**
  8144. * @private
  8145. * @param {Event} e Event object
  8146. * @param {fabric.Object} target
  8147. */
  8148. _shouldClearSelection: function (e, target) {
  8149. var activeGroup = this.getActiveGroup(),
  8150. activeObject = this.getActiveObject();
  8151.  
  8152. return (
  8153. !target
  8154. ||
  8155. (target &&
  8156. activeGroup &&
  8157. !activeGroup.contains(target) &&
  8158. activeGroup !== target &&
  8159. !e.shiftKey)
  8160. ||
  8161. (target && !target.evented)
  8162. ||
  8163. (target &&
  8164. !target.selectable &&
  8165. activeObject &&
  8166. activeObject !== target)
  8167. );
  8168. },
  8169.  
  8170. /**
  8171. * @private
  8172. * @param {Event} e Event object
  8173. * @param {fabric.Object} target
  8174. */
  8175. _shouldCenterTransform: function (e, target) {
  8176. if (!target) {
  8177. return;
  8178. }
  8179.  
  8180. var t = this._currentTransform,
  8181. centerTransform;
  8182.  
  8183. if (t.action === 'scale' || t.action === 'scaleX' || t.action === 'scaleY') {
  8184. centerTransform = this.centeredScaling || target.centeredScaling;
  8185. }
  8186. else if (t.action === 'rotate') {
  8187. centerTransform = this.centeredRotation || target.centeredRotation;
  8188. }
  8189.  
  8190. return centerTransform ? !e.altKey : e.altKey;
  8191. },
  8192.  
  8193. /**
  8194. * @private
  8195. */
  8196. _getOriginFromCorner: function(target, corner) {
  8197. var origin = {
  8198. x: target.originX,
  8199. y: target.originY
  8200. };
  8201.  
  8202. if (corner === 'ml' || corner === 'tl' || corner === 'bl') {
  8203. origin.x = 'right';
  8204. }
  8205. else if (corner === 'mr' || corner === 'tr' || corner === 'br') {
  8206. origin.x = 'left';
  8207. }
  8208.  
  8209. if (corner === 'tl' || corner === 'mt' || corner === 'tr') {
  8210. origin.y = 'bottom';
  8211. }
  8212. else if (corner === 'bl' || corner === 'mb' || corner === 'br') {
  8213. origin.y = 'top';
  8214. }
  8215.  
  8216. return origin;
  8217. },
  8218.  
  8219. /**
  8220. * @private
  8221. */
  8222. _getActionFromCorner: function(target, corner) {
  8223. var action = 'drag';
  8224. if (corner) {
  8225. action = (corner === 'ml' || corner === 'mr')
  8226. ? 'scaleX'
  8227. : (corner === 'mt' || corner === 'mb')
  8228. ? 'scaleY'
  8229. : corner === 'mtr'
  8230. ? 'rotate'
  8231. : 'scale';
  8232. }
  8233. return action;
  8234. },
  8235.  
  8236. /**
  8237. * @private
  8238. * @param {Event} e Event object
  8239. * @param {fabric.Object} target
  8240. */
  8241. _setupCurrentTransform: function (e, target) {
  8242. if (!target) {
  8243. return;
  8244. }
  8245.  
  8246. var pointer = this.getPointer(e),
  8247. corner = target._findTargetCorner(this.getPointer(e, true)),
  8248. action = this._getActionFromCorner(target, corner),
  8249. origin = this._getOriginFromCorner(target, corner);
  8250.  
  8251. this._currentTransform = {
  8252. target: target,
  8253. action: action,
  8254. scaleX: target.scaleX,
  8255. scaleY: target.scaleY,
  8256. offsetX: pointer.x - target.left,
  8257. offsetY: pointer.y - target.top,
  8258. originX: origin.x,
  8259. originY: origin.y,
  8260. ex: pointer.x,
  8261. ey: pointer.y,
  8262. left: target.left,
  8263. top: target.top,
  8264. theta: degreesToRadians(target.angle),
  8265. width: target.width * target.scaleX,
  8266. mouseXSign: 1,
  8267. mouseYSign: 1
  8268. };
  8269.  
  8270. this._currentTransform.original = {
  8271. left: target.left,
  8272. top: target.top,
  8273. scaleX: target.scaleX,
  8274. scaleY: target.scaleY,
  8275. originX: origin.x,
  8276. originY: origin.y
  8277. };
  8278.  
  8279. this._resetCurrentTransform(e);
  8280. },
  8281.  
  8282. /**
  8283. * Translates object by "setting" its left/top
  8284. * @private
  8285. * @param {Number} x pointer's x coordinate
  8286. * @param {Number} y pointer's y coordinate
  8287. */
  8288. _translateObject: function (x, y) {
  8289. var target = this._currentTransform.target;
  8290.  
  8291. if (!target.get('lockMovementX')) {
  8292. target.set('left', x - this._currentTransform.offsetX);
  8293. }
  8294. if (!target.get('lockMovementY')) {
  8295. target.set('top', y - this._currentTransform.offsetY);
  8296. }
  8297. },
  8298.  
  8299. /**
  8300. * Scales object by invoking its scaleX/scaleY methods
  8301. * @private
  8302. * @param {Number} x pointer's x coordinate
  8303. * @param {Number} y pointer's y coordinate
  8304. * @param {String} by Either 'x' or 'y' - specifies dimension constraint by which to scale an object.
  8305. * When not provided, an object is scaled by both dimensions equally
  8306. */
  8307. _scaleObject: function (x, y, by) {
  8308. var t = this._currentTransform,
  8309. target = t.target,
  8310. lockScalingX = target.get('lockScalingX'),
  8311. lockScalingY = target.get('lockScalingY'),
  8312. lockScalingFlip = target.get('lockScalingFlip');
  8313.  
  8314. if (lockScalingX && lockScalingY) {
  8315. return;
  8316. }
  8317.  
  8318. // Get the constraint point
  8319. var constraintPosition = target.translateToOriginPoint(target.getCenterPoint(), t.originX, t.originY),
  8320. localMouse = target.toLocalPoint(new fabric.Point(x, y), t.originX, t.originY);
  8321.  
  8322. this._setLocalMouse(localMouse, t);
  8323.  
  8324. // Actually scale the object
  8325. this._setObjectScale(localMouse, t, lockScalingX, lockScalingY, by, lockScalingFlip);
  8326.  
  8327. // Make sure the constraints apply
  8328. target.setPositionByOrigin(constraintPosition, t.originX, t.originY);
  8329. },
  8330.  
  8331. /**
  8332. * @private
  8333. */
  8334. _setObjectScale: function(localMouse, transform, lockScalingX, lockScalingY, by, lockScalingFlip) {
  8335. var target = transform.target, forbidScalingX = false, forbidScalingY = false;
  8336.  
  8337. transform.newScaleX = localMouse.x / (target.width + target.strokeWidth);
  8338. transform.newScaleY = localMouse.y / (target.height + target.strokeWidth);
  8339.  
  8340. if (lockScalingFlip && transform.newScaleX <= 0 && transform.newScaleX < target.scaleX) {
  8341. forbidScalingX = true;
  8342. }
  8343.  
  8344. if (lockScalingFlip && transform.newScaleY <= 0 && transform.newScaleY < target.scaleY) {
  8345. forbidScalingY = true;
  8346. }
  8347.  
  8348. if (by === 'equally' && !lockScalingX && !lockScalingY) {
  8349. forbidScalingX || forbidScalingY || this._scaleObjectEqually(localMouse, target, transform);
  8350. }
  8351. else if (!by) {
  8352. forbidScalingX || lockScalingX || target.set('scaleX', transform.newScaleX);
  8353. forbidScalingY || lockScalingY || target.set('scaleY', transform.newScaleY);
  8354. }
  8355. else if (by === 'x' && !target.get('lockUniScaling')) {
  8356. forbidScalingX || lockScalingX || target.set('scaleX', transform.newScaleX);
  8357. }
  8358. else if (by === 'y' && !target.get('lockUniScaling')) {
  8359. forbidScalingY || lockScalingY || target.set('scaleY', transform.newScaleY);
  8360. }
  8361.  
  8362. forbidScalingX || forbidScalingY || this._flipObject(transform, by);
  8363.  
  8364. },
  8365.  
  8366. /**
  8367. * @private
  8368. */
  8369. _scaleObjectEqually: function(localMouse, target, transform) {
  8370.  
  8371. var dist = localMouse.y + localMouse.x,
  8372. lastDist = (target.height + (target.strokeWidth)) * transform.original.scaleY +
  8373. (target.width + (target.strokeWidth)) * transform.original.scaleX;
  8374.  
  8375. // We use transform.scaleX/Y instead of target.scaleX/Y
  8376. // because the object may have a min scale and we'll loose the proportions
  8377. transform.newScaleX = transform.original.scaleX * dist / lastDist;
  8378. transform.newScaleY = transform.original.scaleY * dist / lastDist;
  8379.  
  8380. target.set('scaleX', transform.newScaleX);
  8381. target.set('scaleY', transform.newScaleY);
  8382. },
  8383.  
  8384. /**
  8385. * @private
  8386. */
  8387. _flipObject: function(transform, by) {
  8388. if (transform.newScaleX < 0 && by !== 'y') {
  8389. if (transform.originX === 'left') {
  8390. transform.originX = 'right';
  8391. }
  8392. else if (transform.originX === 'right') {
  8393. transform.originX = 'left';
  8394. }
  8395. }
  8396.  
  8397. if (transform.newScaleY < 0 && by !== 'x') {
  8398. if (transform.originY === 'top') {
  8399. transform.originY = 'bottom';
  8400. }
  8401. else if (transform.originY === 'bottom') {
  8402. transform.originY = 'top';
  8403. }
  8404. }
  8405. },
  8406.  
  8407. /**
  8408. * @private
  8409. */
  8410. _setLocalMouse: function(localMouse, t) {
  8411. var target = t.target;
  8412.  
  8413. if (t.originX === 'right') {
  8414. localMouse.x *= -1;
  8415. }
  8416. else if (t.originX === 'center') {
  8417. localMouse.x *= t.mouseXSign * 2;
  8418.  
  8419. if (localMouse.x < 0) {
  8420. t.mouseXSign = -t.mouseXSign;
  8421. }
  8422. }
  8423.  
  8424. if (t.originY === 'bottom') {
  8425. localMouse.y *= -1;
  8426. }
  8427. else if (t.originY === 'center') {
  8428. localMouse.y *= t.mouseYSign * 2;
  8429.  
  8430. if (localMouse.y < 0) {
  8431. t.mouseYSign = -t.mouseYSign;
  8432. }
  8433. }
  8434.  
  8435. // adjust the mouse coordinates when dealing with padding
  8436. if (abs(localMouse.x) > target.padding) {
  8437. if (localMouse.x < 0) {
  8438. localMouse.x += target.padding;
  8439. }
  8440. else {
  8441. localMouse.x -= target.padding;
  8442. }
  8443. }
  8444. else { // mouse is within the padding, set to 0
  8445. localMouse.x = 0;
  8446. }
  8447.  
  8448. if (abs(localMouse.y) > target.padding) {
  8449. if (localMouse.y < 0) {
  8450. localMouse.y += target.padding;
  8451. }
  8452. else {
  8453. localMouse.y -= target.padding;
  8454. }
  8455. }
  8456. else {
  8457. localMouse.y = 0;
  8458. }
  8459. },
  8460.  
  8461. /**
  8462. * Rotates object by invoking its rotate method
  8463. * @private
  8464. * @param {Number} x pointer's x coordinate
  8465. * @param {Number} y pointer's y coordinate
  8466. */
  8467. _rotateObject: function (x, y) {
  8468.  
  8469. var t = this._currentTransform;
  8470.  
  8471. if (t.target.get('lockRotation')) {
  8472. return;
  8473. }
  8474.  
  8475. var lastAngle = atan2(t.ey - t.top, t.ex - t.left),
  8476. curAngle = atan2(y - t.top, x - t.left),
  8477. angle = radiansToDegrees(curAngle - lastAngle + t.theta);
  8478.  
  8479. // normalize angle to positive value
  8480. if (angle < 0) {
  8481. angle = 360 + angle;
  8482. }
  8483.  
  8484. t.target.angle = angle;
  8485. },
  8486.  
  8487. /**
  8488. * Set the cursor type of the canvas element
  8489. * @param {String} value Cursor type of the canvas element.
  8490. * @see http://www.w3.org/TR/css3-ui/#cursor
  8491. */
  8492. setCursor: function (value) {
  8493. this.upperCanvasEl.style.cursor = value;
  8494. },
  8495.  
  8496. /**
  8497. * @private
  8498. */
  8499. _resetObjectTransform: function (target) {
  8500. target.scaleX = 1;
  8501. target.scaleY = 1;
  8502. target.setAngle(0);
  8503. },
  8504.  
  8505. /**
  8506. * @private
  8507. */
  8508. _drawSelection: function () {
  8509. var ctx = this.contextTop,
  8510. groupSelector = this._groupSelector,
  8511. left = groupSelector.left,
  8512. top = groupSelector.top,
  8513. aleft = abs(left),
  8514. atop = abs(top);
  8515.  
  8516. ctx.fillStyle = this.selectionColor;
  8517.  
  8518. ctx.fillRect(
  8519. groupSelector.ex - ((left > 0) ? 0 : -left),
  8520. groupSelector.ey - ((top > 0) ? 0 : -top),
  8521. aleft,
  8522. atop
  8523. );
  8524.  
  8525. ctx.lineWidth = this.selectionLineWidth;
  8526. ctx.strokeStyle = this.selectionBorderColor;
  8527.  
  8528. // selection border
  8529. if (this.selectionDashArray.length > 1) {
  8530.  
  8531. var px = groupSelector.ex + STROKE_OFFSET - ((left > 0) ? 0: aleft),
  8532. py = groupSelector.ey + STROKE_OFFSET - ((top > 0) ? 0: atop);
  8533.  
  8534. ctx.beginPath();
  8535.  
  8536. fabric.util.drawDashedLine(ctx, px, py, px + aleft, py, this.selectionDashArray);
  8537. fabric.util.drawDashedLine(ctx, px, py + atop - 1, px + aleft, py + atop - 1, this.selectionDashArray);
  8538. fabric.util.drawDashedLine(ctx, px, py, px, py + atop, this.selectionDashArray);
  8539. fabric.util.drawDashedLine(ctx, px + aleft - 1, py, px + aleft - 1, py + atop, this.selectionDashArray);
  8540.  
  8541. ctx.closePath();
  8542. ctx.stroke();
  8543. }
  8544. else {
  8545. ctx.strokeRect(
  8546. groupSelector.ex + STROKE_OFFSET - ((left > 0) ? 0 : aleft),
  8547. groupSelector.ey + STROKE_OFFSET - ((top > 0) ? 0 : atop),
  8548. aleft,
  8549. atop
  8550. );
  8551. }
  8552. },
  8553.  
  8554. /**
  8555. * @private
  8556. */
  8557. _isLastRenderedObject: function(e) {
  8558. return (
  8559. this.controlsAboveOverlay &&
  8560. this.lastRenderedObjectWithControlsAboveOverlay &&
  8561. this.lastRenderedObjectWithControlsAboveOverlay.visible &&
  8562. this.containsPoint(e, this.lastRenderedObjectWithControlsAboveOverlay) &&
  8563. this.lastRenderedObjectWithControlsAboveOverlay._findTargetCorner(this.getPointer(e, true)));
  8564. },
  8565.  
  8566. /**
  8567. * Method that determines what object we are clicking on
  8568. * @param {Event} e mouse event
  8569. * @param {Boolean} skipGroup when true, group is skipped and only objects are traversed through
  8570. */
  8571. findTarget: function (e, skipGroup) {
  8572. if (this.skipTargetFind) {
  8573. return;
  8574. }
  8575.  
  8576. if (this._isLastRenderedObject(e)) {
  8577. return this.lastRenderedObjectWithControlsAboveOverlay;
  8578. }
  8579.  
  8580. // first check current group (if one exists)
  8581. var activeGroup = this.getActiveGroup();
  8582. if (activeGroup && !skipGroup && this.containsPoint(e, activeGroup)) {
  8583. return activeGroup;
  8584. }
  8585.  
  8586. var target = this._searchPossibleTargets(e);
  8587. this._fireOverOutEvents(target);
  8588.  
  8589. return target;
  8590. },
  8591.  
  8592. /**
  8593. * @private
  8594. */
  8595. _fireOverOutEvents: function(target) {
  8596. if (target) {
  8597. if (this._hoveredTarget !== target) {
  8598. this.fire('mouse:over', { target: target });
  8599. target.fire('mouseover');
  8600. if (this._hoveredTarget) {
  8601. this.fire('mouse:out', { target: this._hoveredTarget });
  8602. //TODO: Sean fixed bug 5-19-2014
  8603. if (!this._hoveredTarget.fire)
  8604. return;
  8605. this._hoveredTarget.fire('mouseout');
  8606. }
  8607. this._hoveredTarget = target;
  8608. }
  8609. }
  8610. else if (this._hoveredTarget) {
  8611. this.fire('mouse:out', { target: this._hoveredTarget });
  8612. //TODO: Sean fixed bug 6-4-2014
  8613. if (!this._hoveredTarget.fire)
  8614. return;
  8615. this._hoveredTarget.fire('mouseout');
  8616. this._hoveredTarget = null;
  8617. }
  8618. },
  8619.  
  8620. /**
  8621. * @private
  8622. */
  8623. _checkTarget: function(e, obj, pointer) {
  8624. if (obj &&
  8625. obj.visible &&
  8626. obj.evented &&
  8627. this.containsPoint(e, obj)){
  8628. if ((this.perPixelTargetFind || obj.perPixelTargetFind) && !obj.isEditing) {
  8629. var isTransparent = this.isTargetTransparent(obj, pointer.x, pointer.y);
  8630. if (!isTransparent) {
  8631. return true;
  8632. }
  8633. }
  8634. else {
  8635. return true;
  8636. }
  8637. }
  8638. },
  8639.  
  8640. /**
  8641. * @private
  8642. */
  8643. _searchPossibleTargets: function(e) {
  8644.  
  8645. // Cache all targets where their bounding box contains point.
  8646. var target,
  8647. pointer = this.getPointer(e, true),
  8648. i = this._objects.length;
  8649.  
  8650. while (i--) {
  8651. if (this._checkTarget(e, this._objects[i], pointer)){
  8652. this.relatedTarget = this._objects[i];
  8653. target = this._objects[i];
  8654. break;
  8655. }
  8656. }
  8657.  
  8658. return target;
  8659. },
  8660.  
  8661. /**
  8662. * Returns pointer coordinates relative to canvas.
  8663. * @param {Event} e
  8664. * @return {Object} object with "x" and "y" number values
  8665. */
  8666. getPointer: function (e, ignoreZoom, upperCanvasEl) {
  8667. if (!upperCanvasEl) {
  8668. upperCanvasEl = this.upperCanvasEl;
  8669. }
  8670. var pointer = getPointer(e, upperCanvasEl),
  8671. bounds = upperCanvasEl.getBoundingClientRect(),
  8672. boundsWidth = bounds.width || 0,
  8673. boundsHeight = bounds.height || 0,
  8674. cssScale;
  8675.  
  8676. if (!boundsWidth || !boundsHeight ) {
  8677. if ('top' in bounds && 'bottom' in bounds) {
  8678. boundsHeight = Math.abs( bounds.top - bounds.bottom );
  8679. }
  8680. if ('right' in bounds && 'left' in bounds) {
  8681. boundsWidth = Math.abs( bounds.right - bounds.left );
  8682. }
  8683. }
  8684.  
  8685. this.calcOffset();
  8686.  
  8687. pointer.x = pointer.x - this._offset.left;
  8688. pointer.y = pointer.y - this._offset.top;
  8689. if (!ignoreZoom) {
  8690. pointer = fabric.util.transformPoint(
  8691. pointer,
  8692. fabric.util.invertTransform(this.viewportTransform)
  8693. );
  8694. }
  8695.  
  8696. if (boundsWidth === 0 || boundsHeight === 0) {
  8697. // If bounds are not available (i.e. not visible), do not apply scale.
  8698. cssScale = { width: 1, height: 1 };
  8699. }
  8700. else {
  8701. cssScale = {
  8702. width: upperCanvasEl.width / boundsWidth,
  8703. height: upperCanvasEl.height / boundsHeight
  8704. };
  8705. }
  8706.  
  8707. return {
  8708. x: pointer.x * cssScale.width,
  8709. y: pointer.y * cssScale.height
  8710. };
  8711. },
  8712.  
  8713. /**
  8714. * @private
  8715. * @throws {CANVAS_INIT_ERROR} If canvas can not be initialized
  8716. */
  8717. _createUpperCanvas: function () {
  8718. var lowerCanvasClass = this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/, '');
  8719.  
  8720. this.upperCanvasEl = this._createCanvasElement();
  8721. fabric.util.addClass(this.upperCanvasEl, 'upper-canvas ' + lowerCanvasClass);
  8722.  
  8723. this.wrapperEl.appendChild(this.upperCanvasEl);
  8724.  
  8725. this._copyCanvasStyle(this.lowerCanvasEl, this.upperCanvasEl);
  8726. this._applyCanvasStyle(this.upperCanvasEl);
  8727. this.contextTop = this.upperCanvasEl.getContext('2d');
  8728. },
  8729.  
  8730. /**
  8731. * @private
  8732. */
  8733. _createCacheCanvas: function () {
  8734. this.cacheCanvasEl = this._createCanvasElement();
  8735. this.cacheCanvasEl.setAttribute('width', this.width);
  8736. this.cacheCanvasEl.setAttribute('height', this.height);
  8737. this.contextCache = this.cacheCanvasEl.getContext('2d');
  8738. },
  8739.  
  8740. /**
  8741. * @private
  8742. */
  8743. _initWrapperElement: function () {
  8744. this.wrapperEl = fabric.util.wrapElement(this.lowerCanvasEl, 'div', {
  8745. 'class': this.containerClass
  8746. });
  8747. fabric.util.setStyle(this.wrapperEl, {
  8748. width: this.getWidth() + 'px',
  8749. height: this.getHeight() + 'px',
  8750. position: 'relative'
  8751. });
  8752. fabric.util.makeElementUnselectable(this.wrapperEl);
  8753. },
  8754.  
  8755. /**
  8756. * @private
  8757. * @param {HTMLElement} element canvas element to apply styles on
  8758. */
  8759. _applyCanvasStyle: function (element) {
  8760. var width = this.getWidth() || element.width,
  8761. height = this.getHeight() || element.height;
  8762.  
  8763. fabric.util.setStyle(element, {
  8764. position: 'absolute',
  8765. width: width + 'px',
  8766. height: height + 'px',
  8767. left: 0,
  8768. top: 0
  8769. });
  8770. element.width = width;
  8771. element.height = height;
  8772. fabric.util.makeElementUnselectable(element);
  8773. },
  8774.  
  8775. /**
  8776. * Copys the the entire inline style from one element (fromEl) to another (toEl)
  8777. * @private
  8778. * @param {Element} fromEl Element style is copied from
  8779. * @param {Element} toEl Element copied style is applied to
  8780. */
  8781. _copyCanvasStyle: function (fromEl, toEl) {
  8782. toEl.style.cssText = fromEl.style.cssText;
  8783. },
  8784.  
  8785. /**
  8786. * Returns context of canvas where object selection is drawn
  8787. * @return {CanvasRenderingContext2D}
  8788. */
  8789. getSelectionContext: function() {
  8790. return this.contextTop;
  8791. },
  8792.  
  8793. /**
  8794. * Returns &lt;canvas> element on which object selection is drawn
  8795. * @return {HTMLCanvasElement}
  8796. */
  8797. getSelectionElement: function () {
  8798. return this.upperCanvasEl;
  8799. },
  8800.  
  8801. /**
  8802. * @private
  8803. * @param {Object} object
  8804. */
  8805. _setActiveObject: function(object) {
  8806. if (this._activeObject) {
  8807. this._activeObject.set('active', false);
  8808. }
  8809. this._activeObject = object;
  8810. object.set('active', true);
  8811. },
  8812.  
  8813. /**
  8814. * Sets given object as the only active object on canvas
  8815. * @param {fabric.Object} object Object to set as an active one
  8816. * @param {Event} [e] Event (passed along when firing "object:selected")
  8817. * @return {fabric.Canvas} thisArg
  8818. * @chainable
  8819. */
  8820. setActiveObject: function (object, e) {
  8821. this._setActiveObject(object);
  8822. this.renderAll();
  8823. this.fire('object:selected', { target: object, e: e });
  8824. object.fire('selected', { e: e });
  8825. return this;
  8826. },
  8827.  
  8828. /**
  8829. * Returns currently active object
  8830. * @return {fabric.Object} active object
  8831. */
  8832. getActiveObject: function () {
  8833. return this._activeObject;
  8834. },
  8835.  
  8836. /**
  8837. * @private
  8838. */
  8839. _discardActiveObject: function() {
  8840. if (this._activeObject) {
  8841. this._activeObject.set('active', false);
  8842. }
  8843. this._activeObject = null;
  8844. },
  8845.  
  8846. /**
  8847. * Discards currently active object
  8848. * @return {fabric.Canvas} thisArg
  8849. * @chainable
  8850. */
  8851. discardActiveObject: function (e) {
  8852. this._discardActiveObject();
  8853. this.renderAll();
  8854. this.fire('selection:cleared', { e: e });
  8855. return this;
  8856. },
  8857.  
  8858. /**
  8859. * @private
  8860. * @param {fabric.Group} group
  8861. */
  8862. _setActiveGroup: function(group) {
  8863. this._activeGroup = group;
  8864. if (group) {
  8865. group.set('active', true);
  8866. }
  8867. },
  8868.  
  8869. /**
  8870. * Sets active group to a speicified one
  8871. * @param {fabric.Group} group Group to set as a current one
  8872. * @return {fabric.Canvas} thisArg
  8873. * @chainable
  8874. */
  8875. setActiveGroup: function (group, e) {
  8876. this._setActiveGroup(group);
  8877. if (group) {
  8878. this.fire('object:selected', { target: group, e: e });
  8879. group.fire('selected', { e: e });
  8880. }
  8881. return this;
  8882. },
  8883.  
  8884. /**
  8885. * Returns currently active group
  8886. * @return {fabric.Group} Current group
  8887. */
  8888. getActiveGroup: function () {
  8889. return this._activeGroup;
  8890. },
  8891.  
  8892. /**
  8893. * @private
  8894. */
  8895. _discardActiveGroup: function() {
  8896. var g = this.getActiveGroup();
  8897. if (g) {
  8898. g.destroy();
  8899. }
  8900. this.setActiveGroup(null);
  8901. },
  8902.  
  8903. /**
  8904. * Discards currently active group
  8905. * @return {fabric.Canvas} thisArg
  8906. */
  8907. discardActiveGroup: function (e) {
  8908. this._discardActiveGroup();
  8909. this.fire('selection:cleared', { e: e });
  8910. return this;
  8911. },
  8912.  
  8913. /**
  8914. * Deactivates all objects on canvas, removing any active group or object
  8915. * @return {fabric.Canvas} thisArg
  8916. */
  8917. deactivateAll: function () {
  8918. var allObjects = this.getObjects(),
  8919. i = 0,
  8920. len = allObjects.length;
  8921. for ( ; i < len; i++) {
  8922. allObjects[i].set('active', false);
  8923. }
  8924. this._discardActiveGroup();
  8925. this._discardActiveObject();
  8926. return this;
  8927. },
  8928.  
  8929. /**
  8930. * Deactivates all objects and dispatches appropriate events
  8931. * @return {fabric.Canvas} thisArg
  8932. */
  8933. deactivateAllWithDispatch: function (e) {
  8934. var activeObject = this.getActiveGroup() || this.getActiveObject();
  8935. if (activeObject) {
  8936. this.fire('before:selection:cleared', { target: activeObject, e: e });
  8937. }
  8938. this.deactivateAll();
  8939. if (activeObject) {
  8940. this.fire('selection:cleared', { e: e });
  8941. }
  8942. return this;
  8943. },
  8944.  
  8945. /**
  8946. * Draws objects' controls (borders/controls)
  8947. * @param {CanvasRenderingContext2D} ctx Context to render controls on
  8948. */
  8949. drawControls: function(ctx) {
  8950. var activeGroup = this.getActiveGroup();
  8951. if (activeGroup) {
  8952. this._drawGroupControls(ctx, activeGroup);
  8953. }
  8954. else {
  8955. this._drawObjectsControls(ctx);
  8956. }
  8957. },
  8958.  
  8959. /**
  8960. * @private
  8961. */
  8962. _drawGroupControls: function(ctx, activeGroup) {
  8963. activeGroup._renderControls(ctx);
  8964. },
  8965.  
  8966. /**
  8967. * @private
  8968. */
  8969. _drawObjectsControls: function(ctx) {
  8970. for (var i = 0, len = this._objects.length; i < len; ++i) {
  8971. if (!this._objects[i] || !this._objects[i].active) {
  8972. continue;
  8973. }
  8974. this._objects[i]._renderControls(ctx);
  8975. this.lastRenderedObjectWithControlsAboveOverlay = this._objects[i];
  8976. }
  8977. }
  8978. });
  8979.  
  8980. // copying static properties manually to work around Opera's bug,
  8981. // where "prototype" property is enumerable and overrides existing prototype
  8982. for (var prop in fabric.StaticCanvas) {
  8983. if (prop !== 'prototype') {
  8984. fabric.Canvas[prop] = fabric.StaticCanvas[prop];
  8985. }
  8986. }
  8987.  
  8988. if (fabric.isTouchSupported) {
  8989. /** @ignore */
  8990. fabric.Canvas.prototype._setCursorFromEvent = function() { };
  8991. }
  8992.  
  8993. /**
  8994. * @class fabric.Element
  8995. * @alias fabric.Canvas
  8996. * @deprecated Use {@link fabric.Canvas} instead.
  8997. * @constructor
  8998. */
  8999. fabric.Element = fabric.Canvas;
  9000. })()
  9001. ;
  9002.  
  9003.  
  9004. (function() {
  9005.  
  9006. var cursorOffset = {
  9007. mt: 0, // n
  9008. tr: 1, // ne
  9009. mr: 2, // e
  9010. br: 3, // se
  9011. mb: 4, // s
  9012. bl: 5, // sw
  9013. ml: 6, // w
  9014. tl: 7 // nw
  9015. },
  9016. addListener = fabric.util.addListener,
  9017. removeListener = fabric.util.removeListener;
  9018.  
  9019. fabric.util.object.extend(fabric.Canvas.prototype, /** @lends fabric.Canvas.prototype */ {
  9020.  
  9021. /**
  9022. * Map of cursor style values for each of the object controls
  9023. * @private
  9024. */
  9025. cursorMap: [
  9026. 'n-resize',
  9027. 'ne-resize',
  9028. 'e-resize',
  9029. 'se-resize',
  9030. 's-resize',
  9031. 'sw-resize',
  9032. 'w-resize',
  9033. 'nw-resize'
  9034. ],
  9035.  
  9036. /**
  9037. * Adds mouse listeners to canvas
  9038. * @private
  9039. */
  9040. _initEventListeners: function () {
  9041.  
  9042. this._bindEvents();
  9043.  
  9044. addListener(fabric.window, 'resize', this._onResize);
  9045.  
  9046. // mouse events
  9047. addListener(this.upperCanvasEl, 'mousedown', this._onMouseDown);
  9048. addListener(this.upperCanvasEl, 'mousemove', this._onMouseMove);
  9049. addListener(this.upperCanvasEl, 'mousewheel', this._onMouseWheel);
  9050.  
  9051. // touch events
  9052. addListener(this.upperCanvasEl, 'touchstart', this._onMouseDown);
  9053. addListener(this.upperCanvasEl, 'touchmove', this._onMouseMove);
  9054.  
  9055. if (typeof Event !== 'undefined' && 'add' in Event) {
  9056. Event.add(this.upperCanvasEl, 'gesture', this._onGesture);
  9057. Event.add(this.upperCanvasEl, 'drag', this._onDrag);
  9058. Event.add(this.upperCanvasEl, 'orientation', this._onOrientationChange);
  9059. Event.add(this.upperCanvasEl, 'shake', this._onShake);
  9060. }
  9061. },
  9062.  
  9063. /**
  9064. * @private
  9065. */
  9066. _bindEvents: function() {
  9067. this._onMouseDown = this._onMouseDown.bind(this);
  9068. this._onMouseMove = this._onMouseMove.bind(this);
  9069. this._onMouseUp = this._onMouseUp.bind(this);
  9070. this._onResize = this._onResize.bind(this);
  9071. this._onGesture = this._onGesture.bind(this);
  9072. this._onDrag = this._onDrag.bind(this);
  9073. this._onShake = this._onShake.bind(this);
  9074. this._onOrientationChange = this._onOrientationChange.bind(this);
  9075. this._onMouseWheel = this._onMouseWheel.bind(this);
  9076. },
  9077.  
  9078. /**
  9079. * Removes all event listeners
  9080. */
  9081. removeListeners: function() {
  9082. removeListener(fabric.window, 'resize', this._onResize);
  9083.  
  9084. removeListener(this.upperCanvasEl, 'mousedown', this._onMouseDown);
  9085. removeListener(this.upperCanvasEl, 'mousemove', this._onMouseMove);
  9086. removeListener(this.upperCanvasEl, 'mousewheel', this._onMouseWheel);
  9087.  
  9088. removeListener(this.upperCanvasEl, 'touchstart', this._onMouseDown);
  9089. removeListener(this.upperCanvasEl, 'touchmove', this._onMouseMove);
  9090.  
  9091. if (typeof Event !== 'undefined' && 'remove' in Event) {
  9092. Event.remove(this.upperCanvasEl, 'gesture', this._onGesture);
  9093. Event.remove(this.upperCanvasEl, 'drag', this._onDrag);
  9094. Event.remove(this.upperCanvasEl, 'orientation', this._onOrientationChange);
  9095. Event.remove(this.upperCanvasEl, 'shake', this._onShake);
  9096. }
  9097. },
  9098.  
  9099. /**
  9100. * @private
  9101. * @param {Event} [e] Event object fired on Event.js gesture
  9102. * @param {Event} [self] Inner Event object
  9103. */
  9104. _onGesture: function(e, self) {
  9105. this.__onTransformGesture && this.__onTransformGesture(e, self);
  9106. },
  9107.  
  9108. /**
  9109. * @private
  9110. * @param {Event} [e] Event object fired on Event.js drag
  9111. * @param {Event} [self] Inner Event object
  9112. */
  9113. _onDrag: function(e, self) {
  9114. this.__onDrag && this.__onDrag(e, self);
  9115. },
  9116.  
  9117. /**
  9118. * @private
  9119. * @param {Event} [e] Event object fired on Event.js wheel event
  9120. * @param {Event} [self] Inner Event object
  9121. */
  9122. _onMouseWheel: function(e, self) {
  9123. this.__onMouseWheel && this.__onMouseWheel(e, self);
  9124. },
  9125.  
  9126. /**
  9127. * @private
  9128. * @param {Event} [e] Event object fired on Event.js orientation change
  9129. * @param {Event} [self] Inner Event object
  9130. */
  9131. _onOrientationChange: function(e, self) {
  9132. this.__onOrientationChange && this.__onOrientationChange(e, self);
  9133. },
  9134.  
  9135. /**
  9136. * @private
  9137. * @param {Event} [e] Event object fired on Event.js shake
  9138. * @param {Event} [self] Inner Event object
  9139. */
  9140. _onShake: function(e, self) {
  9141. this.__onShake && this.__onShake(e, self);
  9142. },
  9143.  
  9144. /**
  9145. * @private
  9146. * @param {Event} e Event object fired on mousedown
  9147. */
  9148. _onMouseDown: function (e) {
  9149. this.__onMouseDown(e);
  9150.  
  9151. addListener(fabric.document, 'touchend', this._onMouseUp);
  9152. addListener(fabric.document, 'touchmove', this._onMouseMove);
  9153.  
  9154. removeListener(this.upperCanvasEl, 'mousemove', this._onMouseMove);
  9155. removeListener(this.upperCanvasEl, 'touchmove', this._onMouseMove);
  9156.  
  9157. if (e.type === 'touchstart') {
  9158. // Unbind mousedown to prevent double triggers from touch devices
  9159. removeListener(this.upperCanvasEl, 'mousedown', this._onMouseDown);
  9160. }
  9161. else {
  9162. addListener(fabric.document, 'mouseup', this._onMouseUp);
  9163. addListener(fabric.document, 'mousemove', this._onMouseMove);
  9164. }
  9165. },
  9166.  
  9167. /**
  9168. * @private
  9169. * @param {Event} e Event object fired on mouseup
  9170. */
  9171. _onMouseUp: function (e) {
  9172. this.__onMouseUp(e);
  9173.  
  9174. removeListener(fabric.document, 'mouseup', this._onMouseUp);
  9175. removeListener(fabric.document, 'touchend', this._onMouseUp);
  9176.  
  9177. removeListener(fabric.document, 'mousemove', this._onMouseMove);
  9178. removeListener(fabric.document, 'touchmove', this._onMouseMove);
  9179.  
  9180. addListener(this.upperCanvasEl, 'mousemove', this._onMouseMove);
  9181. addListener(this.upperCanvasEl, 'touchmove', this._onMouseMove);
  9182.  
  9183. if (e.type === 'touchend') {
  9184. // Wait 400ms before rebinding mousedown to prevent double triggers
  9185. // from touch devices
  9186. var _this = this;
  9187. setTimeout(function() {
  9188. addListener(_this.upperCanvasEl, 'mousedown', _this._onMouseDown);
  9189. }, 400);
  9190. }
  9191. },
  9192.  
  9193. /**
  9194. * @private
  9195. * @param {Event} e Event object fired on mousemove
  9196. */
  9197. _onMouseMove: function (e) {
  9198. !this.allowTouchScrolling && e.preventDefault && e.preventDefault();
  9199. this.__onMouseMove(e);
  9200. },
  9201.  
  9202. /**
  9203. * @private
  9204. */
  9205. _onResize: function () {
  9206. this.calcOffset();
  9207. },
  9208.  
  9209. /**
  9210. * Decides whether the canvas should be redrawn in mouseup and mousedown events.
  9211. * @private
  9212. * @param {Object} target
  9213. * @param {Object} pointer
  9214. */
  9215. _shouldRender: function(target, pointer) {
  9216. var activeObject = this.getActiveGroup() || this.getActiveObject();
  9217.  
  9218. return !!(
  9219. (target && (
  9220. target.isMoving ||
  9221. target !== activeObject))
  9222. ||
  9223. (!target && !!activeObject)
  9224. ||
  9225. (!target && !activeObject && !this._groupSelector)
  9226. ||
  9227. (pointer &&
  9228. this._previousPointer &&
  9229. this.selection && (
  9230. pointer.x !== this._previousPointer.x ||
  9231. pointer.y !== this._previousPointer.y))
  9232. );
  9233. },
  9234.  
  9235. /**
  9236. * Method that defines the actions when mouse is released on canvas.
  9237. * The method resets the currentTransform parameters, store the image corner
  9238. * position in the image object and render the canvas on top.
  9239. * @private
  9240. * @param {Event} e Event object fired on mouseup
  9241. */
  9242. __onMouseUp: function (e) {
  9243. var target;
  9244.  
  9245. if (this.isDrawingMode && this._isCurrentlyDrawing) {
  9246. this._onMouseUpInDrawingMode(e);
  9247. return;
  9248. }
  9249.  
  9250. if (this._currentTransform) {
  9251. this._finalizeCurrentTransform();
  9252. target = this._currentTransform.target;
  9253. }
  9254. else {
  9255. target = this.findTarget(e, true);
  9256. }
  9257.  
  9258. var shouldRender = this._shouldRender(target, this.getPointer(e));
  9259.  
  9260. this._maybeGroupObjects(e);
  9261.  
  9262. if (target) {
  9263. target.isMoving = false;
  9264. }
  9265.  
  9266. shouldRender && this.renderAll();
  9267.  
  9268. this._handleCursorAndEvent(e, target);
  9269. },
  9270.  
  9271. _handleCursorAndEvent: function(e, target) {
  9272. this._setCursorFromEvent(e, target);
  9273.  
  9274. // TODO: why are we doing this?
  9275. var _this = this;
  9276. setTimeout(function () {
  9277. _this._setCursorFromEvent(e, target);
  9278. }, 50);
  9279.  
  9280. this.fire('mouse:up', { target: target, e: e });
  9281. target && target.fire('mouseup', { e: e });
  9282. },
  9283.  
  9284. /**
  9285. * @private
  9286. */
  9287. _finalizeCurrentTransform: function() {
  9288.  
  9289. var transform = this._currentTransform,
  9290. target = transform.target;
  9291.  
  9292. if (target._scaling) {
  9293. target._scaling = false;
  9294. }
  9295.  
  9296. target.setCoords();
  9297.  
  9298. // only fire :modified event if target coordinates were changed during mousedown-mouseup
  9299. if (this.stateful && target.hasStateChanged()) {
  9300. this.fire('object:modified', { target: target });
  9301. target.fire('modified');
  9302. }
  9303.  
  9304. this._restoreOriginXY(target);
  9305. },
  9306.  
  9307. /**
  9308. * @private
  9309. * @param {Object} target Object to restore
  9310. */
  9311. _restoreOriginXY: function(target) {
  9312. if (this._previousOriginX && this._previousOriginY) {
  9313.  
  9314. var originPoint = target.translateToOriginPoint(
  9315. target.getCenterPoint(),
  9316. this._previousOriginX,
  9317. this._previousOriginY);
  9318.  
  9319. target.originX = this._previousOriginX;
  9320. target.originY = this._previousOriginY;
  9321.  
  9322. target.left = originPoint.x;
  9323. target.top = originPoint.y;
  9324.  
  9325. this._previousOriginX = null;
  9326. this._previousOriginY = null;
  9327. }
  9328. },
  9329.  
  9330. /**
  9331. * @private
  9332. * @param {Event} e Event object fired on mousedown
  9333. */
  9334. _onMouseDownInDrawingMode: function(e) {
  9335. this._isCurrentlyDrawing = true;
  9336. this.discardActiveObject(e).renderAll();
  9337. if (this.clipTo) {
  9338. fabric.util.clipContext(this, this.contextTop);
  9339. }
  9340. var ivt = fabric.util.invertTransform(this.viewportTransform),
  9341. pointer = fabric.util.transformPoint(this.getPointer(e, true), ivt);
  9342. this.freeDrawingBrush.onMouseDown(pointer);
  9343. this.fire('mouse:down', { e: e });
  9344. },
  9345.  
  9346. /**
  9347. * @private
  9348. * @param {Event} e Event object fired on mousemove
  9349. */
  9350. _onMouseMoveInDrawingMode: function(e) {
  9351. if (this._isCurrentlyDrawing) {
  9352. var ivt = fabric.util.invertTransform(this.viewportTransform),
  9353. pointer = fabric.util.transformPoint(this.getPointer(e, true), ivt);
  9354. this.freeDrawingBrush.onMouseMove(pointer);
  9355. }
  9356. this.setCursor(this.freeDrawingCursor);
  9357. this.fire('mouse:move', { e: e });
  9358. },
  9359.  
  9360. /**
  9361. * @private
  9362. * @param {Event} e Event object fired on mouseup
  9363. */
  9364. _onMouseUpInDrawingMode: function(e) {
  9365. this._isCurrentlyDrawing = false;
  9366. if (this.clipTo) {
  9367. this.contextTop.restore();
  9368. }
  9369. this.freeDrawingBrush.onMouseUp();
  9370. this.fire('mouse:up', { e: e });
  9371. },
  9372.  
  9373. /**
  9374. * Method that defines the actions when mouse is clic ked on canvas.
  9375. * The method inits the currentTransform parameters and renders all the
  9376. * canvas so the current image can be placed on the top canvas and the rest
  9377. * in on the container one.
  9378. * @private
  9379. * @param {Event} e Event object fired on mousedown
  9380. */
  9381. __onMouseDown: function (e) {
  9382.  
  9383. // accept only left clicks
  9384. var isLeftClick = 'which' in e ? e.which === 1 : e.button === 1;
  9385. if (!isLeftClick && !fabric.isTouchSupported) {
  9386. return;
  9387. }
  9388.  
  9389. if (this.isDrawingMode) {
  9390. this._onMouseDownInDrawingMode(e);
  9391. return;
  9392. }
  9393.  
  9394. // ignore if some object is being transformed at this moment
  9395. if (this._currentTransform) {
  9396. return;
  9397. }
  9398.  
  9399. var target = this.findTarget(e),
  9400. pointer = this.getPointer(e, true);
  9401.  
  9402. // save pointer for check in __onMouseUp event
  9403. this._previousPointer = pointer;
  9404.  
  9405. var shouldRender = this._shouldRender(target, pointer),
  9406. shouldGroup = this._shouldGroup(e, target);
  9407.  
  9408. if (this._shouldClearSelection(e, target)) {
  9409. this._clearSelection(e, target, pointer);
  9410. }
  9411. else if (shouldGroup) {
  9412. this._handleGrouping(e, target);
  9413. target = this.getActiveGroup();
  9414. }
  9415.  
  9416. if (target && target.selectable && !shouldGroup) {
  9417. this._beforeTransform(e, target);
  9418. this._setupCurrentTransform(e, target);
  9419. }
  9420. // we must renderAll so that active image is placed on the top canvas
  9421. shouldRender && this.renderAll();
  9422.  
  9423. this.fire('mouse:down', { target: target, e: e });
  9424. target && target.fire('mousedown', { e: e });
  9425. },
  9426.  
  9427. /**
  9428. * @private
  9429. */
  9430. _beforeTransform: function(e, target) {
  9431. var corner;
  9432.  
  9433. this.stateful && target.saveState();
  9434.  
  9435. // determine if it's a drag or rotate case
  9436. if ((corner = target._findTargetCorner(this.getPointer(e)))) {
  9437. this.onBeforeScaleRotate(target);
  9438. }
  9439.  
  9440. if (target !== this.getActiveGroup() && target !== this.getActiveObject()) {
  9441. this.deactivateAll();
  9442. this.setActiveObject(target, e);
  9443. }
  9444. },
  9445.  
  9446. /**
  9447. * @private
  9448. */
  9449. _clearSelection: function(e, target, pointer) {
  9450. this.deactivateAllWithDispatch(e);
  9451.  
  9452. if (target && target.selectable) {
  9453. this.setActiveObject(target, e);
  9454. }
  9455. else if (this.selection) {
  9456. this._groupSelector = {
  9457. ex: pointer.x,
  9458. ey: pointer.y,
  9459. top: 0,
  9460. left: 0
  9461. };
  9462. }
  9463. },
  9464.  
  9465. /**
  9466. * @private
  9467. * @param {Object} target Object for that origin is set to center
  9468. */
  9469. _setOriginToCenter: function(target) {
  9470. this._previousOriginX = this._currentTransform.target.originX;
  9471. this._previousOriginY = this._currentTransform.target.originY;
  9472.  
  9473. var center = target.getCenterPoint();
  9474.  
  9475. target.originX = 'center';
  9476. target.originY = 'center';
  9477.  
  9478. target.left = center.x;
  9479. target.top = center.y;
  9480.  
  9481. this._currentTransform.left = target.left;
  9482. this._currentTransform.top = target.top;
  9483. },
  9484.  
  9485. /**
  9486. * @private
  9487. * @param {Object} target Object for that center is set to origin
  9488. */
  9489. _setCenterToOrigin: function(target) {
  9490. var originPoint = target.translateToOriginPoint(
  9491. target.getCenterPoint(),
  9492. this._previousOriginX,
  9493. this._previousOriginY);
  9494.  
  9495. target.originX = this._previousOriginX;
  9496. target.originY = this._previousOriginY;
  9497.  
  9498. target.left = originPoint.x;
  9499. target.top = originPoint.y;
  9500.  
  9501. this._previousOriginX = null;
  9502. this._previousOriginY = null;
  9503. },
  9504.  
  9505. /**
  9506. * Method that defines the actions when mouse is hovering the canvas.
  9507. * The currentTransform parameter will definde whether the user is rotating/scaling/translating
  9508. * an image or neither of them (only hovering). A group selection is also possible and would cancel
  9509. * all any other type of action.
  9510. * In case of an image transformation only the top canvas will be rendered.
  9511. * @private
  9512. * @param {Event} e Event object fired on mousemove
  9513. */
  9514. __onMouseMove: function (e) {
  9515.  
  9516. var target, pointer;
  9517.  
  9518. if (this.isDrawingMode) {
  9519. this._onMouseMoveInDrawingMode(e);
  9520. return;
  9521. }
  9522.  
  9523. var groupSelector = this._groupSelector;
  9524.  
  9525. // We initially clicked in an empty area, so we draw a box for multiple selection
  9526. if (groupSelector) {
  9527. pointer = this.getPointer(e, true);
  9528.  
  9529. groupSelector.left = pointer.x - groupSelector.ex;
  9530. groupSelector.top = pointer.y - groupSelector.ey;
  9531.  
  9532. this.renderTop();
  9533. }
  9534. else if (!this._currentTransform) {
  9535.  
  9536. target = this.findTarget(e);
  9537.  
  9538. if (!target || target && !target.selectable) {
  9539. this.setCursor(this.defaultCursor);
  9540. }
  9541. else {
  9542. this._setCursorFromEvent(e, target);
  9543. }
  9544. }
  9545. else {
  9546. this._transformObject(e);
  9547. }
  9548.  
  9549. this.fire('mouse:move', { target: target, e: e });
  9550. target && target.fire('mousemove', { e: e });
  9551. },
  9552.  
  9553. /**
  9554. * @private
  9555. * @param {Event} e Event fired on mousemove
  9556. */
  9557. _transformObject: function(e) {
  9558. var pointer = this.getPointer(e),
  9559. transform = this._currentTransform;
  9560.  
  9561. transform.reset = false,
  9562. transform.target.isMoving = true;
  9563.  
  9564. this._beforeScaleTransform(e, transform);
  9565. this._performTransformAction(e, transform, pointer);
  9566.  
  9567. this.renderAll();
  9568. },
  9569.  
  9570. /**
  9571. * @private
  9572. */
  9573. _performTransformAction: function(e, transform, pointer) {
  9574. var x = pointer.x,
  9575. y = pointer.y,
  9576. target = transform.target,
  9577. action = transform.action;
  9578.  
  9579. if (action === 'rotate') {
  9580. this._rotateObject(x, y);
  9581. this._fire('rotating', target, e);
  9582. }
  9583. else if (action === 'scale') {
  9584. this._onScale(e, transform, x, y);
  9585. this._fire('scaling', target, e);
  9586. }
  9587. else if (action === 'scaleX') {
  9588. this._scaleObject(x, y, 'x');
  9589. this._fire('scaling', target, e);
  9590. }
  9591. else if (action === 'scaleY') {
  9592. this._scaleObject(x, y, 'y');
  9593. this._fire('scaling', target, e);
  9594. }
  9595. else {
  9596. this._translateObject(x, y);
  9597. this._fire('moving', target, e);
  9598. this.setCursor(this.moveCursor);
  9599. }
  9600. },
  9601.  
  9602. /**
  9603. * @private
  9604. */
  9605. _fire: function(eventName, target, e) {
  9606. this.fire('object:' + eventName, { target: target, e: e });
  9607. target.fire(eventName, { e: e });
  9608. },
  9609.  
  9610. /**
  9611. * @private
  9612. */
  9613. _beforeScaleTransform: function(e, transform) {
  9614. if (transform.action === 'scale' || transform.action === 'scaleX' || transform.action === 'scaleY') {
  9615. var centerTransform = this._shouldCenterTransform(e, transform.target);
  9616.  
  9617. // Switch from a normal resize to center-based
  9618. if ((centerTransform && (transform.originX !== 'center' || transform.originY !== 'center')) ||
  9619. // Switch from center-based resize to normal one
  9620. (!centerTransform && transform.originX === 'center' && transform.originY === 'center')
  9621. ) {
  9622. this._resetCurrentTransform(e);
  9623. transform.reset = true;
  9624. }
  9625. }
  9626. },
  9627.  
  9628. /**
  9629. * @private
  9630. */
  9631. _onScale: function(e, transform, x, y) {
  9632. // rotate object only if shift key is not pressed
  9633. // and if it is not a group we are transforming
  9634. if ((e.shiftKey || this.uniScaleTransform) && !transform.target.get('lockUniScaling')) {
  9635. transform.currentAction = 'scale';
  9636. this._scaleObject(x, y);
  9637. }
  9638. else {
  9639. // Switch from a normal resize to proportional
  9640. if (!transform.reset && transform.currentAction === 'scale') {
  9641. this._resetCurrentTransform(e, transform.target);
  9642. }
  9643.  
  9644. transform.currentAction = 'scaleEqually';
  9645. this._scaleObject(x, y, 'equally');
  9646. }
  9647. },
  9648.  
  9649. /**
  9650. * Sets the cursor depending on where the canvas is being hovered.
  9651. * Note: very buggy in Opera
  9652. * @param {Event} e Event object
  9653. * @param {Object} target Object that the mouse is hovering, if so.
  9654. */
  9655. _setCursorFromEvent: function (e, target) {
  9656. if (!target || !target.selectable) {
  9657. this.setCursor(this.defaultCursor);
  9658. return false;
  9659. }
  9660. else {
  9661. var activeGroup = this.getActiveGroup(),
  9662. // only show proper corner when group selection is not active
  9663. corner = target._findTargetCorner
  9664. && (!activeGroup || !activeGroup.contains(target))
  9665. && target._findTargetCorner(this.getPointer(e, true));
  9666.  
  9667. if (!corner) {
  9668. this.setCursor(target.hoverCursor || this.hoverCursor);
  9669. }
  9670. else {
  9671. this._setCornerCursor(corner, target);
  9672. }
  9673. }
  9674. return true;
  9675. },
  9676.  
  9677. /**
  9678. * @private
  9679. */
  9680. _setCornerCursor: function(corner, target) {
  9681. if (corner in cursorOffset) {
  9682. this.setCursor(this._getRotatedCornerCursor(corner, target));
  9683. }
  9684. else if (corner === 'mtr' && target.hasRotatingPoint) {
  9685. this.setCursor(this.rotationCursor);
  9686. }
  9687. else {
  9688. this.setCursor(this.defaultCursor);
  9689. return false;
  9690. }
  9691. },
  9692.  
  9693. /**
  9694. * @private
  9695. */
  9696. _getRotatedCornerCursor: function(corner, target) {
  9697. var n = Math.round((target.getAngle() % 360) / 45);
  9698.  
  9699. if (n < 0) {
  9700. n += 8; // full circle ahead
  9701. }
  9702. n += cursorOffset[corner];
  9703. // normalize n to be from 0 to 7
  9704. n %= 8;
  9705.  
  9706. return this.cursorMap[n];
  9707. }
  9708. });
  9709. })();
  9710.  
  9711.  
  9712. (function() {
  9713.  
  9714. var min = Math.min,
  9715. max = Math.max;
  9716.  
  9717. fabric.util.object.extend(fabric.Canvas.prototype, /** @lends fabric.Canvas.prototype */ {
  9718.  
  9719. /**
  9720. * @private
  9721. * @param {Event} e Event object
  9722. * @param {fabric.Object} target
  9723. * @return {Boolean}
  9724. */
  9725. _shouldGroup: function(e, target) {
  9726. var activeObject = this.getActiveObject();
  9727. return e.shiftKey &&
  9728. (this.getActiveGroup() || (activeObject && activeObject !== target))
  9729. && this.selection;
  9730. },
  9731.  
  9732. /**
  9733. * @private
  9734. * @param {Event} e Event object
  9735. * @param {fabric.Object} target
  9736. */
  9737. _handleGrouping: function (e, target) {
  9738.  
  9739. if (target === this.getActiveGroup()) {
  9740.  
  9741. // if it's a group, find target again, this time skipping group
  9742. target = this.findTarget(e, true);
  9743.  
  9744. // if even object is not found, bail out
  9745. if (!target || target.isType('group')) {
  9746. return;
  9747. }
  9748. }
  9749. if (this.getActiveGroup()) {
  9750. this._updateActiveGroup(target, e);
  9751. }
  9752. else {
  9753. this._createActiveGroup(target, e);
  9754. }
  9755.  
  9756. if (this._activeGroup) {
  9757. this._activeGroup.saveCoords();
  9758. }
  9759. },
  9760.  
  9761. /**
  9762. * @private
  9763. */
  9764. _updateActiveGroup: function(target, e) {
  9765. var activeGroup = this.getActiveGroup();
  9766.  
  9767. if (activeGroup.contains(target)) {
  9768.  
  9769. activeGroup.removeWithUpdate(target);
  9770. this._resetObjectTransform(activeGroup);
  9771. target.set('active', false);
  9772.  
  9773. if (activeGroup.size() === 1) {
  9774. // remove group alltogether if after removal it only contains 1 object
  9775. this.discardActiveGroup(e);
  9776. // activate last remaining object
  9777. this.setActiveObject(activeGroup.item(0));
  9778. return;
  9779. }
  9780. }
  9781. else {
  9782. activeGroup.addWithUpdate(target);
  9783. this._resetObjectTransform(activeGroup);
  9784. }
  9785. this.fire('selection:created', { target: activeGroup, e: e });
  9786. activeGroup.set('active', true);
  9787. },
  9788.  
  9789. /**
  9790. * @private
  9791. */
  9792. _createActiveGroup: function(target, e) {
  9793.  
  9794. if (this._activeObject && target !== this._activeObject) {
  9795.  
  9796. var group = this._createGroup(target);
  9797. group.addWithUpdate();
  9798.  
  9799. this.setActiveGroup(group);
  9800. this._activeObject = null;
  9801.  
  9802. this.fire('selection:created', { target: group, e: e });
  9803. }
  9804.  
  9805. target.set('active', true);
  9806. },
  9807.  
  9808. /**
  9809. * @private
  9810. * @param {Object} target
  9811. */
  9812. _createGroup: function(target) {
  9813.  
  9814. var objects = this.getObjects(),
  9815. isActiveLower = objects.indexOf(this._activeObject) < objects.indexOf(target),
  9816. groupObjects = isActiveLower
  9817. ? [ this._activeObject, target ]
  9818. : [ target, this._activeObject ];
  9819.  
  9820. return new fabric.Group(groupObjects, {
  9821. originX: 'center',
  9822. originY: 'center',
  9823. canvas: this
  9824. });
  9825. },
  9826.  
  9827. /**
  9828. * @private
  9829. * @param {Event} e mouse event
  9830. */
  9831. _groupSelectedObjects: function (e) {
  9832.  
  9833. var group = this._collectObjects();
  9834.  
  9835. // do not create group for 1 element only
  9836. if (group.length === 1) {
  9837. this.setActiveObject(group[0], e);
  9838. }
  9839. else if (group.length > 1) {
  9840. group = new fabric.Group(group.reverse(), {
  9841. originX: 'center',
  9842. originY: 'center',
  9843. canvas: this
  9844. });
  9845. group.addWithUpdate();
  9846. this.setActiveGroup(group, e);
  9847. group.saveCoords();
  9848. this.fire('selection:created', { target: group });
  9849. this.renderAll();
  9850. }
  9851. },
  9852.  
  9853. /**
  9854. * @private
  9855. */
  9856. _collectObjects: function() {
  9857. var group = [ ],
  9858. currentObject,
  9859. x1 = this._groupSelector.ex,
  9860. y1 = this._groupSelector.ey,
  9861. x2 = x1 + this._groupSelector.left,
  9862. y2 = y1 + this._groupSelector.top,
  9863. selectionX1Y1 = new fabric.Point(min(x1, x2), min(y1, y2)),
  9864. selectionX2Y2 = new fabric.Point(max(x1, x2), max(y1, y2)),
  9865. isClick = x1 === x2 && y1 === y2;
  9866.  
  9867. for (var i = this._objects.length; i--; ) {
  9868. currentObject = this._objects[i];
  9869.  
  9870. if (!currentObject || !currentObject.selectable || !currentObject.visible) {
  9871. continue;
  9872. }
  9873.  
  9874. if (currentObject.intersectsWithRect(selectionX1Y1, selectionX2Y2) ||
  9875. currentObject.isContainedWithinRect(selectionX1Y1, selectionX2Y2) ||
  9876. currentObject.containsPoint(selectionX1Y1) ||
  9877. currentObject.containsPoint(selectionX2Y2)
  9878. ) {
  9879. currentObject.set('active', true);
  9880. group.push(currentObject);
  9881.  
  9882. // only add one object if it's a click
  9883. if (isClick) {
  9884. break;
  9885. }
  9886. }
  9887. }
  9888.  
  9889. return group;
  9890. },
  9891.  
  9892. /**
  9893. * @private
  9894. */
  9895. _maybeGroupObjects: function(e) {
  9896. if (this.selection && this._groupSelector) {
  9897. this._groupSelectedObjects(e);
  9898. }
  9899.  
  9900. var activeGroup = this.getActiveGroup();
  9901. if (activeGroup) {
  9902. activeGroup.setObjectsCoords().setCoords();
  9903. activeGroup.isMoving = false;
  9904. this.setCursor(this.defaultCursor);
  9905. }
  9906.  
  9907. // clear selection and current transformation
  9908. this._groupSelector = null;
  9909. this._currentTransform = null;
  9910. }
  9911. });
  9912.  
  9913. })();
  9914.  
  9915.  
  9916. fabric.util.object.extend(fabric.StaticCanvas.prototype, /** @lends fabric.StaticCanvas.prototype */ {
  9917.  
  9918. /**
  9919. * Exports canvas element to a dataurl image. Note that when multiplier is used, cropping is scaled appropriately
  9920. * @param {Object} [options] Options object
  9921. * @param {String} [options.format=png] The format of the output image. Either "jpeg" or "png"
  9922. * @param {Number} [options.quality=1] Quality level (0..1). Only used for jpeg.
  9923. * @param {Number} [options.multiplier=1] Multiplier to scale by
  9924. * @param {Number} [options.left] Cropping left offset. Introduced in v1.2.14
  9925. * @param {Number} [options.top] Cropping top offset. Introduced in v1.2.14
  9926. * @param {Number} [options.width] Cropping width. Introduced in v1.2.14
  9927. * @param {Number} [options.height] Cropping height. Introduced in v1.2.14
  9928. * @return {String} Returns a data: URL containing a representation of the object in the format specified by options.format
  9929. * @see {@link http://jsfiddle.net/fabricjs/NfZVb/|jsFiddle demo}
  9930. * @example <caption>Generate jpeg dataURL with lower quality</caption>
  9931. * var dataURL = canvas.toDataURL({
  9932. * format: 'jpeg',
  9933. * quality: 0.8
  9934. * });
  9935. * @example <caption>Generate cropped png dataURL (clipping of canvas)</caption>
  9936. * var dataURL = canvas.toDataURL({
  9937. * format: 'png',
  9938. * left: 100,
  9939. * top: 100,
  9940. * width: 200,
  9941. * height: 200
  9942. * });
  9943. * @example <caption>Generate double scaled png dataURL</caption>
  9944. * var dataURL = canvas.toDataURL({
  9945. * format: 'png',
  9946. * multiplier: 2
  9947. * });
  9948. */
  9949. toDataURL: function (options) {
  9950. options || (options = { });
  9951.  
  9952. var format = options.format || 'png',
  9953. quality = options.quality || 1,
  9954. multiplier = options.multiplier || 1,
  9955. cropping = {
  9956. left: options.left,
  9957. top: options.top,
  9958. width: options.width,
  9959. height: options.height
  9960. };
  9961.  
  9962. if (multiplier !== 1) {
  9963. return this.__toDataURLWithMultiplier(format, quality, cropping, multiplier);
  9964. }
  9965. else {
  9966. return this.__toDataURL(format, quality, cropping);
  9967. }
  9968. },
  9969.  
  9970. /**
  9971. * @private
  9972. */
  9973. __toDataURL: function(format, quality, cropping) {
  9974.  
  9975. this.renderAll(true);
  9976.  
  9977. var canvasEl = this.upperCanvasEl || this.lowerCanvasEl,
  9978. croppedCanvasEl = this.__getCroppedCanvas(canvasEl, cropping);
  9979.  
  9980. // to avoid common confusion https://github.com/kangax/fabric.js/issues/806
  9981. if (format === 'jpg') {
  9982. format = 'jpeg';
  9983. }
  9984.  
  9985. var data = (fabric.StaticCanvas.supports('toDataURLWithQuality'))
  9986. ? (croppedCanvasEl || canvasEl).toDataURL('image/' + format, quality)
  9987. : (croppedCanvasEl || canvasEl).toDataURL('image/' + format);
  9988.  
  9989. this.contextTop && this.clearContext(this.contextTop);
  9990. this.renderAll();
  9991.  
  9992. if (croppedCanvasEl) {
  9993. croppedCanvasEl = null;
  9994. }
  9995.  
  9996. return data;
  9997. },
  9998.  
  9999. /**
  10000. * @private
  10001. */
  10002. __getCroppedCanvas: function(canvasEl, cropping) {
  10003.  
  10004. var croppedCanvasEl,
  10005. croppedCtx,
  10006. shouldCrop = 'left' in cropping ||
  10007. 'top' in cropping ||
  10008. 'width' in cropping ||
  10009. 'height' in cropping;
  10010.  
  10011. if (shouldCrop) {
  10012.  
  10013. croppedCanvasEl = fabric.util.createCanvasElement();
  10014. croppedCtx = croppedCanvasEl.getContext('2d');
  10015.  
  10016. croppedCanvasEl.width = cropping.width || this.width;
  10017. croppedCanvasEl.height = cropping.height || this.height;
  10018.  
  10019. croppedCtx.drawImage(canvasEl, -cropping.left || 0, -cropping.top || 0);
  10020. }
  10021.  
  10022. return croppedCanvasEl;
  10023. },
  10024.  
  10025. /**
  10026. * @private
  10027. */
  10028. __toDataURLWithMultiplier: function(format, quality, cropping, multiplier) {
  10029.  
  10030. var origWidth = this.getWidth(),
  10031. origHeight = this.getHeight(),
  10032. scaledWidth = origWidth * multiplier,
  10033. scaledHeight = origHeight * multiplier,
  10034. activeObject = this.getActiveObject(),
  10035. activeGroup = this.getActiveGroup(),
  10036.  
  10037. ctx = this.contextTop || this.contextContainer;
  10038.  
  10039. if (multiplier > 1) {
  10040. this.setWidth(scaledWidth).setHeight(scaledHeight);
  10041. }
  10042. ctx.scale(multiplier, multiplier);
  10043.  
  10044. if (cropping.left) {
  10045. cropping.left *= multiplier;
  10046. }
  10047. if (cropping.top) {
  10048. cropping.top *= multiplier;
  10049. }
  10050. if (cropping.width) {
  10051. cropping.width *= multiplier;
  10052. }
  10053. else if (multiplier < 1) {
  10054. cropping.width = scaledWidth;
  10055. }
  10056. if (cropping.height) {
  10057. cropping.height *= multiplier;
  10058. }
  10059. else if (multiplier < 1) {
  10060. cropping.height = scaledHeight;
  10061. }
  10062.  
  10063. if (activeGroup) {
  10064. // not removing group due to complications with restoring it with correct state afterwords
  10065. this._tempRemoveBordersControlsFromGroup(activeGroup);
  10066. }
  10067. else if (activeObject && this.deactivateAll) {
  10068. this.deactivateAll();
  10069. }
  10070.  
  10071. this.renderAll(true);
  10072.  
  10073. var data = this.__toDataURL(format, quality, cropping);
  10074.  
  10075. // restoring width, height for `renderAll` to draw
  10076. // background properly (while context is scaled)
  10077. this.width = origWidth;
  10078. this.height = origHeight;
  10079.  
  10080. ctx.scale(1 / multiplier, 1 / multiplier);
  10081. this.setWidth(origWidth).setHeight(origHeight);
  10082.  
  10083. if (activeGroup) {
  10084. this._restoreBordersControlsOnGroup(activeGroup);
  10085. }
  10086. else if (activeObject && this.setActiveObject) {
  10087. this.setActiveObject(activeObject);
  10088. }
  10089.  
  10090. this.contextTop && this.clearContext(this.contextTop);
  10091. this.renderAll();
  10092.  
  10093. return data;
  10094. },
  10095.  
  10096. /**
  10097. * Exports canvas element to a dataurl image (allowing to change image size via multiplier).
  10098. * @deprecated since 1.0.13
  10099. * @param {String} format (png|jpeg)
  10100. * @param {Number} multiplier
  10101. * @param {Number} quality (0..1)
  10102. * @return {String}
  10103. */
  10104. toDataURLWithMultiplier: function (format, multiplier, quality) {
  10105. return this.toDataURL({
  10106. format: format,
  10107. multiplier: multiplier,
  10108. quality: quality
  10109. });
  10110. },
  10111.  
  10112. /**
  10113. * @private
  10114. */
  10115. _tempRemoveBordersControlsFromGroup: function(group) {
  10116. group.origHasControls = group.hasControls;
  10117. group.origBorderColor = group.borderColor;
  10118.  
  10119. group.hasControls = true;
  10120. group.borderColor = 'rgba(0,0,0,0)';
  10121.  
  10122. group.forEachObject(function(o) {
  10123. o.origBorderColor = o.borderColor;
  10124. o.borderColor = 'rgba(0,0,0,0)';
  10125. });
  10126. },
  10127.  
  10128. /**
  10129. * @private
  10130. */
  10131. _restoreBordersControlsOnGroup: function(group) {
  10132. group.hideControls = group.origHideControls;
  10133. group.borderColor = group.origBorderColor;
  10134.  
  10135. group.forEachObject(function(o) {
  10136. o.borderColor = o.origBorderColor;
  10137. delete o.origBorderColor;
  10138. });
  10139. }
  10140. });
  10141.  
  10142.  
  10143. fabric.util.object.extend(fabric.StaticCanvas.prototype, /** @lends fabric.StaticCanvas.prototype */ {
  10144.  
  10145. /**
  10146. * Populates canvas with data from the specified dataless JSON.
  10147. * JSON format must conform to the one of {@link fabric.Canvas#toDatalessJSON}
  10148. * @deprecated since 1.2.2
  10149. * @param {String|Object} json JSON string or object
  10150. * @param {Function} callback Callback, invoked when json is parsed
  10151. * and corresponding objects (e.g: {@link fabric.Image})
  10152. * are initialized
  10153. * @param {Function} [reviver] Method for further parsing of JSON elements, called after each fabric object created.
  10154. * @return {fabric.Canvas} instance
  10155. * @chainable
  10156. * @tutorial {@link http://fabricjs.com/fabric-intro-part-3/#deserialization}
  10157. */
  10158. loadFromDatalessJSON: function (json, callback, reviver) {
  10159. return this.loadFromJSON(json, callback, reviver);
  10160. },
  10161.  
  10162. /**
  10163. * Populates canvas with data from the specified JSON.
  10164. * JSON format must conform to the one of {@link fabric.Canvas#toJSON}
  10165. * @param {String|Object} json JSON string or object
  10166. * @param {Function} callback Callback, invoked when json is parsed
  10167. * and corresponding objects (e.g: {@link fabric.Image})
  10168. * are initialized
  10169. * @param {Function} [reviver] Method for further parsing of JSON elements, called after each fabric object created.
  10170. * @return {fabric.Canvas} instance
  10171. * @chainable
  10172. * @tutorial {@link http://fabricjs.com/fabric-intro-part-3/#deserialization}
  10173. * @see {@link http://jsfiddle.net/fabricjs/fmgXt/|jsFiddle demo}
  10174. * @example <caption>loadFromJSON</caption>
  10175. * canvas.loadFromJSON(json, canvas.renderAll.bind(canvas));
  10176. * @example <caption>loadFromJSON with reviver</caption>
  10177. * canvas.loadFromJSON(json, canvas.renderAll.bind(canvas), function(o, object) {
  10178. * // `o` = json object
  10179. * // `object` = fabric.Object instance
  10180. * // ... do some stuff ...
  10181. * });
  10182. */
  10183. loadFromJSON: function (json, callback, reviver) {
  10184. if (!json) {
  10185. return;
  10186. }
  10187.  
  10188. // serialize if it wasn't already
  10189. var serialized = (typeof json === 'string')
  10190. ? JSON.parse(json)
  10191. : json;
  10192.  
  10193. this.clear();
  10194.  
  10195. var _this = this;
  10196. this._enlivenObjects(serialized.objects, function () {
  10197. _this._setBgOverlay(serialized, callback);
  10198. }, reviver);
  10199.  
  10200. return this;
  10201. },
  10202.  
  10203. /**
  10204. * @private
  10205. * @param {Object} serialized Object with background and overlay information
  10206. * @param {Function} callback Invoked after all background and overlay images/patterns loaded
  10207. */
  10208. _setBgOverlay: function(serialized, callback) {
  10209. var _this = this,
  10210. loaded = {
  10211. backgroundColor: false,
  10212. overlayColor: false,
  10213. backgroundImage: false,
  10214. overlayImage: false
  10215. };
  10216.  
  10217. if (!serialized.backgroundImage && !serialized.overlayImage && !serialized.background && !serialized.overlay) {
  10218. callback && callback();
  10219. return;
  10220. }
  10221.  
  10222. var cbIfLoaded = function () {
  10223. if (loaded.backgroundImage && loaded.overlayImage && loaded.backgroundColor && loaded.overlayColor) {
  10224. _this.renderAll();
  10225. callback && callback();
  10226. }
  10227. };
  10228.  
  10229. this.__setBgOverlay('backgroundImage', serialized.backgroundImage, loaded, cbIfLoaded);
  10230. this.__setBgOverlay('overlayImage', serialized.overlayImage, loaded, cbIfLoaded);
  10231. this.__setBgOverlay('backgroundColor', serialized.background, loaded, cbIfLoaded);
  10232. this.__setBgOverlay('overlayColor', serialized.overlay, loaded, cbIfLoaded);
  10233.  
  10234. cbIfLoaded();
  10235. },
  10236.  
  10237. /**
  10238. * @private
  10239. * @param {String} property Property to set (backgroundImage, overlayImage, backgroundColor, overlayColor)
  10240. * @param {(Object|String)} value Value to set
  10241. * @param {Object} loaded Set loaded property to true if property is set
  10242. * @param {Object} callback Callback function to invoke after property is set
  10243. */
  10244. __setBgOverlay: function(property, value, loaded, callback) {
  10245. var _this = this;
  10246.  
  10247. if (!value) {
  10248. loaded[property] = true;
  10249. return;
  10250. }
  10251.  
  10252. if (property === 'backgroundImage' || property === 'overlayImage') {
  10253. fabric.Image.fromObject(value, function(img) {
  10254. _this[property] = img;
  10255. loaded[property] = true;
  10256. callback && callback();
  10257. });
  10258. }
  10259. else {
  10260. this['set' + fabric.util.string.capitalize(property, true)](value, function() {
  10261. loaded[property] = true;
  10262. callback && callback();
  10263. });
  10264. }
  10265. },
  10266.  
  10267. /**
  10268. * @private
  10269. * @param {Array} objects
  10270. * @param {Function} callback
  10271. * @param {Function} [reviver]
  10272. */
  10273. _enlivenObjects: function (objects, callback, reviver) {
  10274. var _this = this;
  10275.  
  10276. if (!objects || objects.length === 0) {
  10277. callback && callback();
  10278. return;
  10279. }
  10280.  
  10281. var renderOnAddRemove = this.renderOnAddRemove;
  10282. this.renderOnAddRemove = false;
  10283.  
  10284. fabric.util.enlivenObjects(objects, function(enlivenedObjects) {
  10285. enlivenedObjects.forEach(function(obj, index) {
  10286. _this.insertAt(obj, index, true);
  10287. });
  10288.  
  10289. _this.renderOnAddRemove = renderOnAddRemove;
  10290. callback && callback();
  10291. }, null, reviver);
  10292. },
  10293.  
  10294. /**
  10295. * @private
  10296. * @param {String} format
  10297. * @param {Function} callback
  10298. */
  10299. _toDataURL: function (format, callback) {
  10300. this.clone(function (clone) {
  10301. callback(clone.toDataURL(format));
  10302. });
  10303. },
  10304.  
  10305. /**
  10306. * @private
  10307. * @param {String} format
  10308. * @param {Number} multiplier
  10309. * @param {Function} callback
  10310. */
  10311. _toDataURLWithMultiplier: function (format, multiplier, callback) {
  10312. this.clone(function (clone) {
  10313. callback(clone.toDataURLWithMultiplier(format, multiplier));
  10314. });
  10315. },
  10316.  
  10317. /**
  10318. * Clones canvas instance
  10319. * @param {Object} [callback] Receives cloned instance as a first argument
  10320. * @param {Array} [properties] Array of properties to include in the cloned canvas and children
  10321. */
  10322. clone: function (callback, properties) {
  10323. var data = JSON.stringify(this.toJSON(properties));
  10324. this.cloneWithoutData(function(clone) {
  10325. clone.loadFromJSON(data, function() {
  10326. callback && callback(clone);
  10327. });
  10328. });
  10329. },
  10330.  
  10331. /**
  10332. * Clones canvas instance without cloning existing data.
  10333. * This essentially copies canvas dimensions, clipping properties, etc.
  10334. * but leaves data empty (so that you can populate it with your own)
  10335. * @param {Object} [callback] Receives cloned instance as a first argument
  10336. */
  10337. cloneWithoutData: function(callback) {
  10338. var el = fabric.document.createElement('canvas');
  10339.  
  10340. el.width = this.getWidth();
  10341. el.height = this.getHeight();
  10342.  
  10343. var clone = new fabric.Canvas(el);
  10344. clone.clipTo = this.clipTo;
  10345. if (this.backgroundImage) {
  10346. clone.setBackgroundImage(this.backgroundImage.src, function() {
  10347. clone.renderAll();
  10348. callback && callback(clone);
  10349. });
  10350. clone.backgroundImageOpacity = this.backgroundImageOpacity;
  10351. clone.backgroundImageStretch = this.backgroundImageStretch;
  10352. }
  10353. else {
  10354. callback && callback(clone);
  10355. }
  10356. }
  10357. });
  10358.  
  10359.  
  10360. (function(global) {
  10361.  
  10362. 'use strict';
  10363.  
  10364. var fabric = global.fabric || (global.fabric = { }),
  10365. extend = fabric.util.object.extend,
  10366. toFixed = fabric.util.toFixed,
  10367. capitalize = fabric.util.string.capitalize,
  10368. degreesToRadians = fabric.util.degreesToRadians,
  10369. supportsLineDash = fabric.StaticCanvas.supports('setLineDash');
  10370.  
  10371. if (fabric.Object) {
  10372. return;
  10373. }
  10374.  
  10375. /**
  10376. * Root object class from which all 2d shape classes inherit from
  10377. * @class fabric.Object
  10378. * @tutorial {@link http://fabricjs.com/fabric-intro-part-1/#objects}
  10379. * @see {@link fabric.Object#initialize} for constructor definition
  10380. *
  10381. * @fires added
  10382. * @fires removed
  10383. *
  10384. * @fires selected
  10385. * @fires modified
  10386. * @fires rotating
  10387. * @fires scaling
  10388. * @fires moving
  10389. *
  10390. * @fires mousedown
  10391. * @fires mouseup
  10392. */
  10393. fabric.Object = fabric.util.createClass(/** @lends fabric.Object.prototype */ {
  10394.  
  10395. /**
  10396. * Retrieves object's {@link fabric.Object#clipTo|clipping function}
  10397. * @method getClipTo
  10398. * @memberOf fabric.Object.prototype
  10399. * @return {Function}
  10400. */
  10401.  
  10402. /**
  10403. * Sets object's {@link fabric.Object#clipTo|clipping function}
  10404. * @method setClipTo
  10405. * @memberOf fabric.Object.prototype
  10406. * @param {Function} clipTo Clipping function
  10407. * @return {fabric.Object} thisArg
  10408. * @chainable
  10409. */
  10410.  
  10411. /**
  10412. * Retrieves object's {@link fabric.Object#transformMatrix|transformMatrix}
  10413. * @method getTransformMatrix
  10414. * @memberOf fabric.Object.prototype
  10415. * @return {Array} transformMatrix
  10416. */
  10417.  
  10418. /**
  10419. * Sets object's {@link fabric.Object#transformMatrix|transformMatrix}
  10420. * @method setTransformMatrix
  10421. * @memberOf fabric.Object.prototype
  10422. * @param {Array} transformMatrix
  10423. * @return {fabric.Object} thisArg
  10424. * @chainable
  10425. */
  10426.  
  10427. /**
  10428. * Retrieves object's {@link fabric.Object#visible|visible} state
  10429. * @method getVisible
  10430. * @memberOf fabric.Object.prototype
  10431. * @return {Boolean} True if visible
  10432. */
  10433.  
  10434. /**
  10435. * Sets object's {@link fabric.Object#visible|visible} state
  10436. * @method setVisible
  10437. * @memberOf fabric.Object.prototype
  10438. * @param {Boolean} value visible value
  10439. * @return {fabric.Object} thisArg
  10440. * @chainable
  10441. */
  10442.  
  10443. /**
  10444. * Retrieves object's {@link fabric.Object#shadow|shadow}
  10445. * @method getShadow
  10446. * @memberOf fabric.Object.prototype
  10447. * @return {Object} Shadow instance
  10448. */
  10449.  
  10450. /**
  10451. * Retrieves object's {@link fabric.Object#stroke|stroke}
  10452. * @method getStroke
  10453. * @memberOf fabric.Object.prototype
  10454. * @return {String} stroke value
  10455. */
  10456.  
  10457. /**
  10458. * Sets object's {@link fabric.Object#stroke|stroke}
  10459. * @method setStroke
  10460. * @memberOf fabric.Object.prototype
  10461. * @param {String} value stroke value
  10462. * @return {fabric.Object} thisArg
  10463. * @chainable
  10464. */
  10465.  
  10466. /**
  10467. * Retrieves object's {@link fabric.Object#strokeWidth|strokeWidth}
  10468. * @method getStrokeWidth
  10469. * @memberOf fabric.Object.prototype
  10470. * @return {Number} strokeWidth value
  10471. */
  10472.  
  10473. /**
  10474. * Sets object's {@link fabric.Object#strokeWidth|strokeWidth}
  10475. * @method setStrokeWidth
  10476. * @memberOf fabric.Object.prototype
  10477. * @param {Number} value strokeWidth value
  10478. * @return {fabric.Object} thisArg
  10479. * @chainable
  10480. */
  10481.  
  10482. /**
  10483. * Retrieves object's {@link fabric.Object#originX|originX}
  10484. * @method getOriginX
  10485. * @memberOf fabric.Object.prototype
  10486. * @return {String} originX value
  10487. */
  10488.  
  10489. /**
  10490. * Sets object's {@link fabric.Object#originX|originX}
  10491. * @method setOriginX
  10492. * @memberOf fabric.Object.prototype
  10493. * @param {String} value originX value
  10494. * @return {fabric.Object} thisArg
  10495. * @chainable
  10496. */
  10497.  
  10498. /**
  10499. * Retrieves object's {@link fabric.Object#originY|originY}
  10500. * @method getOriginY
  10501. * @memberOf fabric.Object.prototype
  10502. * @return {String} originY value
  10503. */
  10504.  
  10505. /**
  10506. * Sets object's {@link fabric.Object#originY|originY}
  10507. * @method setOriginY
  10508. * @memberOf fabric.Object.prototype
  10509. * @param {String} value originY value
  10510. * @return {fabric.Object} thisArg
  10511. * @chainable
  10512. */
  10513.  
  10514. /**
  10515. * Retrieves object's {@link fabric.Object#fill|fill}
  10516. * @method getFill
  10517. * @memberOf fabric.Object.prototype
  10518. * @return {String} Fill value
  10519. */
  10520.  
  10521. /**
  10522. * Sets object's {@link fabric.Object#fill|fill}
  10523. * @method setFill
  10524. * @memberOf fabric.Object.prototype
  10525. * @param {String} value Fill value
  10526. * @return {fabric.Object} thisArg
  10527. * @chainable
  10528. */
  10529.  
  10530. /**
  10531. * Retrieves object's {@link fabric.Object#opacity|opacity}
  10532. * @method getOpacity
  10533. * @memberOf fabric.Object.prototype
  10534. * @return {Number} Opacity value (0-1)
  10535. */
  10536.  
  10537. /**
  10538. * Sets object's {@link fabric.Object#opacity|opacity}
  10539. * @method setOpacity
  10540. * @memberOf fabric.Object.prototype
  10541. * @param {Number} value Opacity value (0-1)
  10542. * @return {fabric.Object} thisArg
  10543. * @chainable
  10544. */
  10545.  
  10546. /**
  10547. * Retrieves object's {@link fabric.Object#angle|angle} (in degrees)
  10548. * @method getAngle
  10549. * @memberOf fabric.Object.prototype
  10550. * @return {Number}
  10551. */
  10552.  
  10553. /**
  10554. * Sets object's {@link fabric.Object#angle|angle}
  10555. * @method setAngle
  10556. * @memberOf fabric.Object.prototype
  10557. * @param {Number} value Angle value (in degrees)
  10558. * @return {fabric.Object} thisArg
  10559. * @chainable
  10560. */
  10561.  
  10562. /**
  10563. * Retrieves object's {@link fabric.Object#top|top position}
  10564. * @method getTop
  10565. * @memberOf fabric.Object.prototype
  10566. * @return {Number} Top value (in pixels)
  10567. */
  10568.  
  10569. /**
  10570. * Sets object's {@link fabric.Object#top|top position}
  10571. * @method setTop
  10572. * @memberOf fabric.Object.prototype
  10573. * @param {Number} value Top value (in pixels)
  10574. * @return {fabric.Object} thisArg
  10575. * @chainable
  10576. */
  10577.  
  10578. /**
  10579. * Retrieves object's {@link fabric.Object#left|left position}
  10580. * @method getLeft
  10581. * @memberOf fabric.Object.prototype
  10582. * @return {Number} Left value (in pixels)
  10583. */
  10584.  
  10585. /**
  10586. * Sets object's {@link fabric.Object#left|left position}
  10587. * @method setLeft
  10588. * @memberOf fabric.Object.prototype
  10589. * @param {Number} value Left value (in pixels)
  10590. * @return {fabric.Object} thisArg
  10591. * @chainable
  10592. */
  10593.  
  10594. /**
  10595. * Retrieves object's {@link fabric.Object#scaleX|scaleX} value
  10596. * @method getScaleX
  10597. * @memberOf fabric.Object.prototype
  10598. * @return {Number} scaleX value
  10599. */
  10600.  
  10601. /**
  10602. * Sets object's {@link fabric.Object#scaleX|scaleX} value
  10603. * @method setScaleX
  10604. * @memberOf fabric.Object.prototype
  10605. * @param {Number} value scaleX value
  10606. * @return {fabric.Object} thisArg
  10607. * @chainable
  10608. */
  10609.  
  10610. /**
  10611. * Retrieves object's {@link fabric.Object#scaleY|scaleY} value
  10612. * @method getScaleY
  10613. * @memberOf fabric.Object.prototype
  10614. * @return {Number} scaleY value
  10615. */
  10616.  
  10617. /**
  10618. * Sets object's {@link fabric.Object#scaleY|scaleY} value
  10619. * @method setScaleY
  10620. * @memberOf fabric.Object.prototype
  10621. * @param {Number} value scaleY value
  10622. * @return {fabric.Object} thisArg
  10623. * @chainable
  10624. */
  10625.  
  10626. /**
  10627. * Retrieves object's {@link fabric.Object#flipX|flipX} value
  10628. * @method getFlipX
  10629. * @memberOf fabric.Object.prototype
  10630. * @return {Boolean} flipX value
  10631. */
  10632.  
  10633. /**
  10634. * Sets object's {@link fabric.Object#flipX|flipX} value
  10635. * @method setFlipX
  10636. * @memberOf fabric.Object.prototype
  10637. * @param {Boolean} value flipX value
  10638. * @return {fabric.Object} thisArg
  10639. * @chainable
  10640. */
  10641.  
  10642. /**
  10643. * Retrieves object's {@link fabric.Object#flipY|flipY} value
  10644. * @method getFlipY
  10645. * @memberOf fabric.Object.prototype
  10646. * @return {Boolean} flipY value
  10647. */
  10648.  
  10649. /**
  10650. * Sets object's {@link fabric.Object#flipY|flipY} value
  10651. * @method setFlipY
  10652. * @memberOf fabric.Object.prototype
  10653. * @param {Boolean} value flipY value
  10654. * @return {fabric.Object} thisArg
  10655. * @chainable
  10656. */
  10657.  
  10658. /**
  10659. * Type of an object (rect, circle, path, etc.)
  10660. * @type String
  10661. * @default
  10662. */
  10663. type: 'object',
  10664.  
  10665. /**
  10666. * Horizontal origin of transformation of an object (one of "left", "right", "center")
  10667. * @type String
  10668. * @default
  10669. */
  10670. originX: 'left',
  10671.  
  10672. /**
  10673. * Vertical origin of transformation of an object (one of "top", "bottom", "center")
  10674. * @type String
  10675. * @default
  10676. */
  10677. originY: 'top',
  10678.  
  10679. /**
  10680. * Top position of an object. Note that by default it's relative to object center. You can change this by setting originY={top/center/bottom}
  10681. * @type Number
  10682. * @default
  10683. */
  10684. top: 0,
  10685.  
  10686. /**
  10687. * Left position of an object. Note that by default it's relative to object center. You can change this by setting originX={left/center/right}
  10688. * @type Number
  10689. * @default
  10690. */
  10691. left: 0,
  10692.  
  10693. /**
  10694. * Object width
  10695. * @type Number
  10696. * @default
  10697. */
  10698. width: 0,
  10699.  
  10700. /**
  10701. * Object height
  10702. * @type Number
  10703. * @default
  10704. */
  10705. height: 0,
  10706.  
  10707. /**
  10708. * Object scale factor (horizontal)
  10709. * @type Number
  10710. * @default
  10711. */
  10712. scaleX: 1,
  10713.  
  10714. /**
  10715. * Object scale factor (vertical)
  10716. * @type Number
  10717. * @default
  10718. */
  10719. scaleY: 1,
  10720.  
  10721. /**
  10722. * When true, an object is rendered as flipped horizontally
  10723. * @type Boolean
  10724. * @default
  10725. */
  10726. flipX: false,
  10727.  
  10728. /**
  10729. * When true, an object is rendered as flipped vertically
  10730. * @type Boolean
  10731. * @default
  10732. */
  10733. flipY: false,
  10734.  
  10735. /**
  10736. * Opacity of an object
  10737. * @type Number
  10738. * @default
  10739. */
  10740. opacity: 1,
  10741.  
  10742. /**
  10743. * Angle of rotation of an object (in degrees)
  10744. * @type Number
  10745. * @default
  10746. */
  10747. angle: 0,
  10748.  
  10749. /**
  10750. * Size of object's controlling corners (in pixels)
  10751. * @type Number
  10752. * @default
  10753. */
  10754. cornerSize: 12,
  10755.  
  10756. /**
  10757. * When true, object's controlling corners are rendered as transparent inside (i.e. stroke instead of fill)
  10758. * @type Boolean
  10759. * @default
  10760. */
  10761. transparentCorners: true,
  10762.  
  10763. /**
  10764. * Default cursor value used when hovering over this object on canvas
  10765. * @type String
  10766. * @default
  10767. */
  10768. hoverCursor: null,
  10769.  
  10770. /**
  10771. * Padding between object and its controlling borders (in pixels)
  10772. * @type Number
  10773. * @default
  10774. */
  10775. padding: 0,
  10776.  
  10777. /**
  10778. * Color of controlling borders of an object (when it's active)
  10779. * @type String
  10780. * @default
  10781. */
  10782. borderColor: 'rgba(102,153,255,0.75)',
  10783.  
  10784. /**
  10785. * Color of controlling corners of an object (when it's active)
  10786. * @type String
  10787. * @default
  10788. */
  10789. cornerColor: 'rgba(102,153,255,0.5)',
  10790.  
  10791. /**
  10792. * When true, this object will use center point as the origin of transformation
  10793. * when being scaled via the controls.
  10794. * <b>Backwards incompatibility note:</b> This property replaces "centerTransform" (Boolean).
  10795. * @since 1.3.4
  10796. * @type Boolean
  10797. * @default
  10798. */
  10799. centeredScaling: false,
  10800.  
  10801. /**
  10802. * When true, this object will use center point as the origin of transformation
  10803. * when being rotated via the controls.
  10804. * <b>Backwards incompatibility note:</b> This property replaces "centerTransform" (Boolean).
  10805. * @since 1.3.4
  10806. * @type Boolean
  10807. * @default
  10808. */
  10809. centeredRotation: true,
  10810.  
  10811. /**
  10812. * Color of object's fill
  10813. * @type String
  10814. * @default
  10815. */
  10816. fill: 'rgb(0,0,0)',
  10817.  
  10818. /**
  10819. * Fill rule used to fill an object
  10820. * accepted values are nonzero, evenodd
  10821. * <b>Backwards incompatibility note:</b> This property was used for setting globalCompositeOperation until v1.4.12 (use `fabric.Object#globalCompositeOperation` instead)
  10822. * @type String
  10823. * @default
  10824. */
  10825. fillRule: 'nonzero',
  10826.  
  10827. /**
  10828. * Composite rule used for canvas globalCompositeOperation
  10829. * @type String
  10830. * @default
  10831. */
  10832. globalCompositeOperation: 'source-over',
  10833.  
  10834. /**
  10835. * Background color of an object. Only works with text objects at the moment.
  10836. * @type String
  10837. * @default
  10838. */
  10839. backgroundColor: '',
  10840.  
  10841. /**
  10842. * When defined, an object is rendered via stroke and this property specifies its color
  10843. * @type String
  10844. * @default
  10845. */
  10846. stroke: null,
  10847.  
  10848. /**
  10849. * Width of a stroke used to render this object
  10850. * @type Number
  10851. * @default
  10852. */
  10853. strokeWidth: 1,
  10854.  
  10855. /**
  10856. * Array specifying dash pattern of an object's stroke (stroke must be defined)
  10857. * @type Array
  10858. */
  10859. strokeDashArray: null,
  10860.  
  10861. /**
  10862. * Line endings style of an object's stroke (one of "butt", "round", "square")
  10863. * @type String
  10864. * @default
  10865. */
  10866. strokeLineCap: 'butt',
  10867.  
  10868. /**
  10869. * Corner style of an object's stroke (one of "bevil", "round", "miter")
  10870. * @type String
  10871. * @default
  10872. */
  10873. strokeLineJoin: 'miter',
  10874.  
  10875. /**
  10876. * Maximum miter length (used for strokeLineJoin = "miter") of an object's stroke
  10877. * @type Number
  10878. * @default
  10879. */
  10880. strokeMiterLimit: 10,
  10881.  
  10882. /**
  10883. * Shadow object representing shadow of this shape
  10884. * @type fabric.Shadow
  10885. * @default
  10886. */
  10887. shadow: null,
  10888.  
  10889. /**
  10890. * Opacity of object's controlling borders when object is active and moving
  10891. * @type Number
  10892. * @default
  10893. */
  10894. borderOpacityWhenMoving: 0.4,
  10895.  
  10896. /**
  10897. * Scale factor of object's controlling borders
  10898. * @type Number
  10899. * @default
  10900. */
  10901. borderScaleFactor: 1,
  10902.  
  10903. /**
  10904. * Transform matrix (similar to SVG's transform matrix)
  10905. * @type Array
  10906. */
  10907. transformMatrix: null,
  10908.  
  10909. /**
  10910. * Minimum allowed scale value of an object
  10911. * @type Number
  10912. * @default
  10913. */
  10914. minScaleLimit: 0.01,
  10915.  
  10916. /**
  10917. * When set to `false`, an object can not be selected for modification (using either point-click-based or group-based selection).
  10918. * But events still fire on it.
  10919. * @type Boolean
  10920. * @default
  10921. */
  10922. selectable: true,
  10923.  
  10924. /**
  10925. * When set to `false`, an object can not be a target of events. All events propagate through it. Introduced in v1.3.4
  10926. * @type Boolean
  10927. * @default
  10928. */
  10929. evented: true,
  10930.  
  10931. /**
  10932. * When set to `false`, an object is not rendered on canvas
  10933. * @type Boolean
  10934. * @default
  10935. */
  10936. visible: true,
  10937.  
  10938. /**
  10939. * When set to `false`, object's controls are not displayed and can not be used to manipulate object
  10940. * @type Boolean
  10941. * @default
  10942. */
  10943. hasControls: true,
  10944.  
  10945. /**
  10946. * When set to `false`, object's controlling borders are not rendered
  10947. * @type Boolean
  10948. * @default
  10949. */
  10950. hasBorders: true,
  10951.  
  10952. /**
  10953. * When set to `false`, object's controlling rotating point will not be visible or selectable
  10954. * @type Boolean
  10955. * @default
  10956. */
  10957. hasRotatingPoint: true,
  10958.  
  10959. /**
  10960. * Offset for object's controlling rotating point (when enabled via `hasRotatingPoint`)
  10961. * @type Number
  10962. * @default
  10963. */
  10964. rotatingPointOffset: 40,
  10965.  
  10966. /**
  10967. * When set to `true`, objects are "found" on canvas on per-pixel basis rather than according to bounding box
  10968. * @type Boolean
  10969. * @default
  10970. */
  10971. perPixelTargetFind: false,
  10972.  
  10973. /**
  10974. * When `false`, default object's values are not included in its serialization
  10975. * @type Boolean
  10976. * @default
  10977. */
  10978. includeDefaultValues: true,
  10979.  
  10980. /**
  10981. * Function that determines clipping of an object (context is passed as a first argument)
  10982. * Note that context origin is at the object's center point (not left/top corner)
  10983. * @type Function
  10984. */
  10985. clipTo: null,
  10986.  
  10987. /**
  10988. * When `true`, object horizontal movement is locked
  10989. * @type Boolean
  10990. * @default
  10991. */
  10992. lockMovementX: false,
  10993.  
  10994. /**
  10995. * When `true`, object vertical movement is locked
  10996. * @type Boolean
  10997. * @default
  10998. */
  10999. lockMovementY: false,
  11000.  
  11001. /**
  11002. * When `true`, object rotation is locked
  11003. * @type Boolean
  11004. * @default
  11005. */
  11006. lockRotation: false,
  11007.  
  11008. /**
  11009. * When `true`, object horizontal scaling is locked
  11010. * @type Boolean
  11011. * @default
  11012. */
  11013. lockScalingX: false,
  11014.  
  11015. /**
  11016. * When `true`, object vertical scaling is locked
  11017. * @type Boolean
  11018. * @default
  11019. */
  11020. lockScalingY: false,
  11021.  
  11022. /**
  11023. * When `true`, object non-uniform scaling is locked
  11024. * @type Boolean
  11025. * @default
  11026. */
  11027. lockUniScaling: false,
  11028.  
  11029. /**
  11030. * When `true`, object cannot be flipped by scaling into negative values
  11031. * @type Boolean
  11032. * @default
  11033. */
  11034.  
  11035. lockScalingFlip: false,
  11036. /**
  11037. * List of properties to consider when checking if state
  11038. * of an object is changed (fabric.Object#hasStateChanged)
  11039. * as well as for history (undo/redo) purposes
  11040. * @type Array
  11041. */
  11042. stateProperties: (
  11043. 'top left width height scaleX scaleY flipX flipY originX originY transformMatrix ' +
  11044. 'stroke strokeWidth strokeDashArray strokeLineCap strokeLineJoin strokeMiterLimit ' +
  11045. 'angle opacity fill fillRule globalCompositeOperation shadow clipTo visible backgroundColor'
  11046. ).split(' '),
  11047.  
  11048. /**
  11049. * Constructor
  11050. * @param {Object} [options] Options object
  11051. */
  11052. initialize: function(options) {
  11053. if (options) {
  11054. this.setOptions(options);
  11055. }
  11056. },
  11057.  
  11058. /**
  11059. * @private
  11060. * @param {Object} [options] Options object
  11061. */
  11062. _initGradient: function(options) {
  11063. if (options.fill && options.fill.colorStops && !(options.fill instanceof fabric.Gradient)) {
  11064. this.set('fill', new fabric.Gradient(options.fill));
  11065. }
  11066. },
  11067.  
  11068. /**
  11069. * @private
  11070. * @param {Object} [options] Options object
  11071. */
  11072. _initPattern: function(options) {
  11073. if (options.fill && options.fill.source && !(options.fill instanceof fabric.Pattern)) {
  11074. this.set('fill', new fabric.Pattern(options.fill));
  11075. }
  11076. if (options.stroke && options.stroke.source && !(options.stroke instanceof fabric.Pattern)) {
  11077. this.set('stroke', new fabric.Pattern(options.stroke));
  11078. }
  11079. },
  11080.  
  11081. /**
  11082. * @private
  11083. * @param {Object} [options] Options object
  11084. */
  11085. _initClipping: function(options) {
  11086. if (!options.clipTo || typeof options.clipTo !== 'string') {
  11087. return;
  11088. }
  11089.  
  11090. var functionBody = fabric.util.getFunctionBody(options.clipTo);
  11091. if (typeof functionBody !== 'undefined') {
  11092. this.clipTo = new Function('ctx', functionBody);
  11093. }
  11094. },
  11095.  
  11096. /**
  11097. * Sets object's properties from options
  11098. * @param {Object} [options] Options object
  11099. */
  11100. setOptions: function(options) {
  11101. for (var prop in options) {
  11102. this.set(prop, options[prop]);
  11103. }
  11104. this._initGradient(options);
  11105. this._initPattern(options);
  11106. this._initClipping(options);
  11107. },
  11108.  
  11109. /**
  11110. * Transforms context when rendering an object
  11111. * @param {CanvasRenderingContext2D} ctx Context
  11112. * @param {Boolean} fromLeft When true, context is transformed to object's top/left corner. This is used when rendering text on Node
  11113. */
  11114. transform: function(ctx, fromLeft) {
  11115. if (this.group) {
  11116. this.group.transform(ctx, fromLeft);
  11117. }
  11118. var center = fromLeft ? this._getLeftTopCoords() : this.getCenterPoint();
  11119. ctx.translate(center.x, center.y);
  11120. ctx.rotate(degreesToRadians(this.angle));
  11121. ctx.scale(
  11122. this.scaleX * (this.flipX ? -1 : 1),
  11123. this.scaleY * (this.flipY ? -1 : 1)
  11124. );
  11125. },
  11126.  
  11127. /**
  11128. * Returns an object representation of an instance
  11129. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  11130. * @return {Object} Object representation of an instance
  11131. */
  11132. toObject: function(propertiesToInclude) {
  11133. var NUM_FRACTION_DIGITS = fabric.Object.NUM_FRACTION_DIGITS,
  11134.  
  11135. object = {
  11136. type: this.type,
  11137. originX: this.originX,
  11138. originY: this.originY,
  11139. left: toFixed(this.left, NUM_FRACTION_DIGITS),
  11140. top: toFixed(this.top, NUM_FRACTION_DIGITS),
  11141. width: toFixed(this.width, NUM_FRACTION_DIGITS),
  11142. height: toFixed(this.height, NUM_FRACTION_DIGITS),
  11143. fill: (this.fill && this.fill.toObject) ? this.fill.toObject() : this.fill,
  11144. stroke: (this.stroke && this.stroke.toObject) ? this.stroke.toObject() : this.stroke,
  11145. strokeWidth: toFixed(this.strokeWidth, NUM_FRACTION_DIGITS),
  11146. strokeDashArray: this.strokeDashArray,
  11147. strokeLineCap: this.strokeLineCap,
  11148. strokeLineJoin: this.strokeLineJoin,
  11149. strokeMiterLimit: toFixed(this.strokeMiterLimit, NUM_FRACTION_DIGITS),
  11150. scaleX: toFixed(this.scaleX, NUM_FRACTION_DIGITS),
  11151. scaleY: toFixed(this.scaleY, NUM_FRACTION_DIGITS),
  11152. angle: toFixed(this.getAngle(), NUM_FRACTION_DIGITS),
  11153. flipX: this.flipX,
  11154. flipY: this.flipY,
  11155. opacity: toFixed(this.opacity, NUM_FRACTION_DIGITS),
  11156. shadow: (this.shadow && this.shadow.toObject) ? this.shadow.toObject() : this.shadow,
  11157. visible: this.visible,
  11158. clipTo: this.clipTo && String(this.clipTo),
  11159. backgroundColor: this.backgroundColor,
  11160. fillRule: this.fillRule,
  11161. globalCompositeOperation: this.globalCompositeOperation
  11162. };
  11163.  
  11164. if (!this.includeDefaultValues) {
  11165. object = this._removeDefaultValues(object);
  11166. }
  11167.  
  11168. fabric.util.populateWithProperties(this, object, propertiesToInclude);
  11169.  
  11170. return object;
  11171. },
  11172.  
  11173. /**
  11174. * Returns (dataless) object representation of an instance
  11175. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  11176. * @return {Object} Object representation of an instance
  11177. */
  11178. toDatalessObject: function(propertiesToInclude) {
  11179. // will be overwritten by subclasses
  11180. return this.toObject(propertiesToInclude);
  11181. },
  11182.  
  11183. /**
  11184. * @private
  11185. * @param {Object} object
  11186. */
  11187. _removeDefaultValues: function(object) {
  11188. var prototype = fabric.util.getKlass(object.type).prototype,
  11189. stateProperties = prototype.stateProperties;
  11190.  
  11191. stateProperties.forEach(function(prop) {
  11192. if (object[prop] === prototype[prop]) {
  11193. delete object[prop];
  11194. }
  11195. });
  11196.  
  11197. return object;
  11198. },
  11199.  
  11200. /**
  11201. * Returns a string representation of an instance
  11202. * @return {String}
  11203. */
  11204. toString: function() {
  11205. return '#<fabric.' + capitalize(this.type) + '>';
  11206. },
  11207.  
  11208. /**
  11209. * Basic getter
  11210. * @param {String} property Property name
  11211. * @return {Any} value of a property
  11212. */
  11213. get: function(property) {
  11214. return this[property];
  11215. },
  11216.  
  11217. /**
  11218. * @private
  11219. */
  11220. _setObject: function(obj) {
  11221. for (var prop in obj) {
  11222. this._set(prop, obj[prop]);
  11223. }
  11224. },
  11225.  
  11226. /**
  11227. * Sets property to a given value. When changing position/dimension -related properties (left, top, scale, angle, etc.) `set` does not update position of object's borders/controls. If you need to update those, call `setCoords()`.
  11228. * @param {String|Object} key Property name or object (if object, iterate over the object properties)
  11229. * @param {Object|Function} value Property value (if function, the value is passed into it and its return value is used as a new one)
  11230. * @return {fabric.Object} thisArg
  11231. * @chainable
  11232. */
  11233. set: function(key, value) {
  11234. if (typeof key === 'object') {
  11235. this._setObject(key);
  11236. }
  11237. else {
  11238. if (typeof value === 'function' && key !== 'clipTo') {
  11239. this._set(key, value(this.get(key)));
  11240. }
  11241. else {
  11242. this._set(key, value);
  11243. }
  11244. }
  11245. return this;
  11246. },
  11247.  
  11248. /**
  11249. * @private
  11250. * @param {String} key
  11251. * @param {Any} value
  11252. * @return {fabric.Object} thisArg
  11253. */
  11254. _set: function(key, value) {
  11255. var shouldConstrainValue = (key === 'scaleX' || key === 'scaleY');
  11256.  
  11257. if (shouldConstrainValue) {
  11258. value = this._constrainScale(value);
  11259. }
  11260. if (key === 'scaleX' && value < 0) {
  11261. this.flipX = !this.flipX;
  11262. value *= -1;
  11263. }
  11264. else if (key === 'scaleY' && value < 0) {
  11265. this.flipY = !this.flipY;
  11266. value *= -1;
  11267. }
  11268. else if (key === 'width' || key === 'height') {
  11269. this.minScaleLimit = toFixed(Math.min(0.1, 1/Math.max(this.width, this.height)), 2);
  11270. }
  11271. else if (key === 'shadow' && value && !(value instanceof fabric.Shadow)) {
  11272. value = new fabric.Shadow(value);
  11273. }
  11274.  
  11275. this[key] = value;
  11276.  
  11277. return this;
  11278. },
  11279.  
  11280. /**
  11281. * Toggles specified property from `true` to `false` or from `false` to `true`
  11282. * @param {String} property Property to toggle
  11283. * @return {fabric.Object} thisArg
  11284. * @chainable
  11285. */
  11286. toggle: function(property) {
  11287. var value = this.get(property);
  11288. if (typeof value === 'boolean') {
  11289. this.set(property, !value);
  11290. }
  11291. return this;
  11292. },
  11293.  
  11294. /**
  11295. * Sets sourcePath of an object
  11296. * @param {String} value Value to set sourcePath to
  11297. * @return {fabric.Object} thisArg
  11298. * @chainable
  11299. */
  11300. setSourcePath: function(value) {
  11301. this.sourcePath = value;
  11302. return this;
  11303. },
  11304.  
  11305. /**
  11306. * Retrieves viewportTransform from Object's canvas if possible
  11307. * @method getViewportTransform
  11308. * @memberOf fabric.Object.prototype
  11309. * @return {Boolean} flipY value // TODO
  11310. */
  11311. getViewportTransform: function() {
  11312. if (this.canvas && this.canvas.viewportTransform) {
  11313. return this.canvas.viewportTransform;
  11314. }
  11315. return [1, 0, 0, 1, 0, 0];
  11316. },
  11317.  
  11318. /**
  11319. * Renders an object on a specified context
  11320. * @param {CanvasRenderingContext2D} ctx Context to render on
  11321. * @param {Boolean} [noTransform] When true, context is not transformed
  11322. */
  11323. render: function(ctx, noTransform) {
  11324. // do not render if width/height are zeros or object is not visible
  11325. if (this.width === 0 || this.height === 0 || !this.visible) {
  11326. return;
  11327. }
  11328.  
  11329. ctx.save();
  11330.  
  11331. //setup fill rule for current object
  11332. this._setupCompositeOperation(ctx);
  11333. if (!noTransform) {
  11334. this.transform(ctx);
  11335. }
  11336. this._setStrokeStyles(ctx);
  11337. this._setFillStyles(ctx);
  11338. if (this.group && this.group.type === 'path-group') {
  11339. ctx.translate(-this.group.width/2, -this.group.height/2);
  11340. }
  11341. if (this.transformMatrix) {
  11342. ctx.transform.apply(ctx, this.transformMatrix);
  11343. }
  11344. this._setOpacity(ctx);
  11345. this._setShadow(ctx);
  11346. this.clipTo && fabric.util.clipContext(this, ctx);
  11347. this._render(ctx, noTransform);
  11348. this.clipTo && ctx.restore();
  11349. this._removeShadow(ctx);
  11350. this._restoreCompositeOperation(ctx);
  11351.  
  11352. ctx.restore();
  11353. },
  11354.  
  11355. /* @private
  11356. * @param {CanvasRenderingContext2D} ctx Context to render on
  11357. */
  11358. _setOpacity: function(ctx) {
  11359. if (this.group) {
  11360. this.group._setOpacity(ctx);
  11361. }
  11362. ctx.globalAlpha *= this.opacity;
  11363. },
  11364.  
  11365. _setStrokeStyles: function(ctx) {
  11366. if (this.stroke) {
  11367. ctx.lineWidth = this.strokeWidth;
  11368. ctx.lineCap = this.strokeLineCap;
  11369. ctx.lineJoin = this.strokeLineJoin;
  11370. ctx.miterLimit = this.strokeMiterLimit;
  11371. ctx.strokeStyle = this.stroke.toLive
  11372. ? this.stroke.toLive(ctx, this)
  11373. : this.stroke;
  11374. }
  11375. },
  11376.  
  11377. _setFillStyles: function(ctx) {
  11378. if (this.fill) {
  11379. ctx.fillStyle = this.fill.toLive
  11380. ? this.fill.toLive(ctx, this)
  11381. : this.fill;
  11382. }
  11383. },
  11384.  
  11385. /**
  11386. * Renders controls and borders for the object
  11387. * @param {CanvasRenderingContext2D} ctx Context to render on
  11388. * @param {Boolean} [noTransform] When true, context is not transformed
  11389. */
  11390. _renderControls: function(ctx, noTransform) {
  11391. var vpt = this.getViewportTransform();
  11392.  
  11393. ctx.save();
  11394. if (this.active && !noTransform) {
  11395. var center;
  11396. if (this.group) {
  11397. center = fabric.util.transformPoint(this.group.getCenterPoint(), vpt);
  11398. ctx.translate(center.x, center.y);
  11399. ctx.rotate(degreesToRadians(this.group.angle));
  11400. }
  11401. center = fabric.util.transformPoint(this.getCenterPoint(), vpt, null != this.group);
  11402. if (this.group) {
  11403. center.x *= this.group.scaleX;
  11404. center.y *= this.group.scaleY;
  11405. }
  11406. ctx.translate(center.x, center.y);
  11407. ctx.rotate(degreesToRadians(this.angle));
  11408. this.drawBorders(ctx);
  11409. this.drawControls(ctx);
  11410. }
  11411. ctx.restore();
  11412. },
  11413.  
  11414. /**
  11415. * @private
  11416. * @param {CanvasRenderingContext2D} ctx Context to render on
  11417. */
  11418. _setShadow: function(ctx) {
  11419. if (!this.shadow) {
  11420. return;
  11421. }
  11422.  
  11423. ctx.shadowColor = this.shadow.color;
  11424. ctx.shadowBlur = this.shadow.blur;
  11425. ctx.shadowOffsetX = this.shadow.offsetX;
  11426. ctx.shadowOffsetY = this.shadow.offsetY;
  11427. },
  11428.  
  11429. /**
  11430. * @private
  11431. * @param {CanvasRenderingContext2D} ctx Context to render on
  11432. */
  11433. _removeShadow: function(ctx) {
  11434. if (!this.shadow) {
  11435. return;
  11436. }
  11437.  
  11438. ctx.shadowColor = '';
  11439. ctx.shadowBlur = ctx.shadowOffsetX = ctx.shadowOffsetY = 0;
  11440. },
  11441.  
  11442. /**
  11443. * @private
  11444. * @param {CanvasRenderingContext2D} ctx Context to render on
  11445. */
  11446. _renderFill: function(ctx) {
  11447. if (!this.fill) {
  11448. return;
  11449. }
  11450.  
  11451. ctx.save();
  11452. if (this.fill.gradientTransform) {
  11453. var g = this.fill.gradientTransform;
  11454. ctx.transform.apply(ctx, g);
  11455. }
  11456. if (this.fill.toLive) {
  11457. ctx.translate(
  11458. -this.width / 2 + this.fill.offsetX || 0,
  11459. -this.height / 2 + this.fill.offsetY || 0);
  11460. }
  11461. if (this.fillRule === 'evenodd') {
  11462. ctx.fill('evenodd');
  11463. }
  11464. else {
  11465. ctx.fill();
  11466. }
  11467. ctx.restore();
  11468. if (this.shadow && !this.shadow.affectStroke) {
  11469. this._removeShadow(ctx);
  11470. }
  11471. },
  11472.  
  11473. /**
  11474. * @private
  11475. * @param {CanvasRenderingContext2D} ctx Context to render on
  11476. */
  11477. _renderStroke: function(ctx) {
  11478. if (!this.stroke || this.strokeWidth === 0) {
  11479. return;
  11480. }
  11481.  
  11482. ctx.save();
  11483. if (this.strokeDashArray) {
  11484. // Spec requires the concatenation of two copies the dash list when the number of elements is odd
  11485. if (1 & this.strokeDashArray.length) {
  11486. this.strokeDashArray.push.apply(this.strokeDashArray, this.strokeDashArray);
  11487. }
  11488. if (supportsLineDash) {
  11489. ctx.setLineDash(this.strokeDashArray);
  11490. this._stroke && this._stroke(ctx);
  11491. }
  11492. else {
  11493. this._renderDashedStroke && this._renderDashedStroke(ctx);
  11494. }
  11495. ctx.stroke();
  11496. }
  11497. else {
  11498. if (this.stroke.gradientTransform) {
  11499. var g = this.stroke.gradientTransform;
  11500. ctx.transform.apply(ctx, g);
  11501. }
  11502. this._stroke ? this._stroke(ctx) : ctx.stroke();
  11503. }
  11504. this._removeShadow(ctx);
  11505. ctx.restore();
  11506. },
  11507.  
  11508. /**
  11509. * Clones an instance
  11510. * @param {Function} callback Callback is invoked with a clone as a first argument
  11511. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  11512. * @return {fabric.Object} clone of an instance
  11513. */
  11514. clone: function(callback, propertiesToInclude) {
  11515. if (this.constructor.fromObject) {
  11516. return this.constructor.fromObject(this.toObject(propertiesToInclude), callback);
  11517. }
  11518. return new fabric.Object(this.toObject(propertiesToInclude));
  11519. },
  11520.  
  11521. /**
  11522. * Creates an instance of fabric.Image out of an object
  11523. * @param {Function} callback callback, invoked with an instance as a first argument
  11524. * @return {fabric.Object} thisArg
  11525. */
  11526. cloneAsImage: function(callback) {
  11527. var dataUrl = this.toDataURL();
  11528. fabric.util.loadImage(dataUrl, function(img) {
  11529. if (callback) {
  11530. callback(new fabric.Image(img));
  11531. }
  11532. });
  11533. return this;
  11534. },
  11535.  
  11536. /**
  11537. * Converts an object into a data-url-like string
  11538. * @param {Object} options Options object
  11539. * @param {String} [options.format=png] The format of the output image. Either "jpeg" or "png"
  11540. * @param {Number} [options.quality=1] Quality level (0..1). Only used for jpeg.
  11541. * @param {Number} [options.multiplier=1] Multiplier to scale by
  11542. * @param {Number} [options.left] Cropping left offset. Introduced in v1.2.14
  11543. * @param {Number} [options.top] Cropping top offset. Introduced in v1.2.14
  11544. * @param {Number} [options.width] Cropping width. Introduced in v1.2.14
  11545. * @param {Number} [options.height] Cropping height. Introduced in v1.2.14
  11546. * @return {String} Returns a data: URL containing a representation of the object in the format specified by options.format
  11547. */
  11548. toDataURL: function(options) {
  11549. options || (options = { });
  11550.  
  11551. var el = fabric.util.createCanvasElement(),
  11552. boundingRect = this.getBoundingRect();
  11553.  
  11554. el.width = boundingRect.width;
  11555. el.height = boundingRect.height;
  11556.  
  11557. fabric.util.wrapElement(el, 'div');
  11558. var canvas = new fabric.Canvas(el);
  11559.  
  11560. // to avoid common confusion https://github.com/kangax/fabric.js/issues/806
  11561. if (options.format === 'jpg') {
  11562. options.format = 'jpeg';
  11563. }
  11564.  
  11565. if (options.format === 'jpeg') {
  11566. canvas.backgroundColor = '#fff';
  11567. }
  11568.  
  11569. var origParams = {
  11570. active: this.get('active'),
  11571. left: this.getLeft(),
  11572. top: this.getTop()
  11573. };
  11574.  
  11575. this.set('active', false);
  11576. this.setPositionByOrigin(new fabric.Point(el.width / 2, el.height / 2), 'center', 'center');
  11577.  
  11578. var originalCanvas = this.canvas;
  11579. canvas.add(this);
  11580. var data = canvas.toDataURL(options);
  11581.  
  11582. this.set(origParams).setCoords();
  11583. this.canvas = originalCanvas;
  11584.  
  11585. canvas.dispose();
  11586. canvas = null;
  11587.  
  11588. return data;
  11589. },
  11590.  
  11591. /**
  11592. * Returns true if specified type is identical to the type of an instance
  11593. * @param {String} type Type to check against
  11594. * @return {Boolean}
  11595. */
  11596. isType: function(type) {
  11597. return this.type === type;
  11598. },
  11599.  
  11600. /**
  11601. * Returns complexity of an instance
  11602. * @return {Number} complexity of this instance
  11603. */
  11604. complexity: function() {
  11605. return 0;
  11606. },
  11607.  
  11608. /**
  11609. * Returns a JSON representation of an instance
  11610. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  11611. * @return {Object} JSON
  11612. */
  11613. toJSON: function(propertiesToInclude) {
  11614. // delegate, not alias
  11615. return this.toObject(propertiesToInclude);
  11616. },
  11617.  
  11618. /**
  11619. * Sets gradient (fill or stroke) of an object
  11620. * <b>Backwards incompatibility note:</b> This method was named "setGradientFill" until v1.1.0
  11621. * @param {String} property Property name 'stroke' or 'fill'
  11622. * @param {Object} [options] Options object
  11623. * @param {String} [options.type] Type of gradient 'radial' or 'linear'
  11624. * @param {Number} [options.x1=0] x-coordinate of start point
  11625. * @param {Number} [options.y1=0] y-coordinate of start point
  11626. * @param {Number} [options.x2=0] x-coordinate of end point
  11627. * @param {Number} [options.y2=0] y-coordinate of end point
  11628. * @param {Number} [options.r1=0] Radius of start point (only for radial gradients)
  11629. * @param {Number} [options.r2=0] Radius of end point (only for radial gradients)
  11630. * @param {Object} [options.colorStops] Color stops object eg. {0: 'ff0000', 1: '000000'}
  11631. * @return {fabric.Object} thisArg
  11632. * @chainable
  11633. * @see {@link http://jsfiddle.net/fabricjs/58y8b/|jsFiddle demo}
  11634. * @example <caption>Set linear gradient</caption>
  11635. * object.setGradient('fill', {
  11636. * type: 'linear',
  11637. * x1: -object.width / 2,
  11638. * y1: 0,
  11639. * x2: object.width / 2,
  11640. * y2: 0,
  11641. * colorStops: {
  11642. * 0: 'red',
  11643. * 0.5: '#005555',
  11644. * 1: 'rgba(0,0,255,0.5)'
  11645. * }
  11646. * });
  11647. * canvas.renderAll();
  11648. * @example <caption>Set radial gradient</caption>
  11649. * object.setGradient('fill', {
  11650. * type: 'radial',
  11651. * x1: 0,
  11652. * y1: 0,
  11653. * x2: 0,
  11654. * y2: 0,
  11655. * r1: object.width / 2,
  11656. * r2: 10,
  11657. * colorStops: {
  11658. * 0: 'red',
  11659. * 0.5: '#005555',
  11660. * 1: 'rgba(0,0,255,0.5)'
  11661. * }
  11662. * });
  11663. * canvas.renderAll();
  11664. */
  11665. setGradient: function(property, options) {
  11666. options || (options = { });
  11667.  
  11668. var gradient = { colorStops: [] };
  11669.  
  11670. gradient.type = options.type || (options.r1 || options.r2 ? 'radial' : 'linear');
  11671. gradient.coords = {
  11672. x1: options.x1,
  11673. y1: options.y1,
  11674. x2: options.x2,
  11675. y2: options.y2
  11676. };
  11677.  
  11678. if (options.r1 || options.r2) {
  11679. gradient.coords.r1 = options.r1;
  11680. gradient.coords.r2 = options.r2;
  11681. }
  11682.  
  11683. for (var position in options.colorStops) {
  11684. var color = new fabric.Color(options.colorStops[position]);
  11685. gradient.colorStops.push({
  11686. offset: position,
  11687. color: color.toRgb(),
  11688. opacity: color.getAlpha()
  11689. });
  11690. }
  11691.  
  11692. return this.set(property, fabric.Gradient.forObject(this, gradient));
  11693. },
  11694.  
  11695. /**
  11696. * Sets pattern fill of an object
  11697. * @param {Object} options Options object
  11698. * @param {(String|HTMLImageElement)} options.source Pattern source
  11699. * @param {String} [options.repeat=repeat] Repeat property of a pattern (one of repeat, repeat-x, repeat-y or no-repeat)
  11700. * @param {Number} [options.offsetX=0] Pattern horizontal offset from object's left/top corner
  11701. * @param {Number} [options.offsetY=0] Pattern vertical offset from object's left/top corner
  11702. * @return {fabric.Object} thisArg
  11703. * @chainable
  11704. * @see {@link http://jsfiddle.net/fabricjs/QT3pa/|jsFiddle demo}
  11705. * @example <caption>Set pattern</caption>
  11706. * fabric.util.loadImage('http://fabricjs.com/assets/escheresque_ste.png', function(img) {
  11707. * object.setPatternFill({
  11708. * source: img,
  11709. * repeat: 'repeat'
  11710. * });
  11711. * canvas.renderAll();
  11712. * });
  11713. */
  11714. setPatternFill: function(options) {
  11715. return this.set('fill', new fabric.Pattern(options));
  11716. },
  11717.  
  11718. /**
  11719. * Sets {@link fabric.Object#shadow|shadow} of an object
  11720. * @param {Object|String} [options] Options object or string (e.g. "2px 2px 10px rgba(0,0,0,0.2)")
  11721. * @param {String} [options.color=rgb(0,0,0)] Shadow color
  11722. * @param {Number} [options.blur=0] Shadow blur
  11723. * @param {Number} [options.offsetX=0] Shadow horizontal offset
  11724. * @param {Number} [options.offsetY=0] Shadow vertical offset
  11725. * @return {fabric.Object} thisArg
  11726. * @chainable
  11727. * @see {@link http://jsfiddle.net/fabricjs/7gvJG/|jsFiddle demo}
  11728. * @example <caption>Set shadow with string notation</caption>
  11729. * object.setShadow('2px 2px 10px rgba(0,0,0,0.2)');
  11730. * canvas.renderAll();
  11731. * @example <caption>Set shadow with object notation</caption>
  11732. * object.setShadow({
  11733. * color: 'red',
  11734. * blur: 10,
  11735. * offsetX: 20,
  11736. * offsetY: 20
  11737. * });
  11738. * canvas.renderAll();
  11739. */
  11740. setShadow: function(options) {
  11741. return this.set('shadow', options ? new fabric.Shadow(options) : null);
  11742. },
  11743.  
  11744. /**
  11745. * Sets "color" of an instance (alias of `set('fill', &hellip;)`)
  11746. * @param {String} color Color value
  11747. * @return {fabric.Object} thisArg
  11748. * @chainable
  11749. */
  11750. setColor: function(color) {
  11751. this.set('fill', color);
  11752. return this;
  11753. },
  11754.  
  11755. /**
  11756. * Sets "angle" of an instance
  11757. * @param {Number} angle Angle value
  11758. * @return {fabric.Object} thisArg
  11759. * @chainable
  11760. */
  11761. setAngle: function(angle) {
  11762. var shouldCenterOrigin = (this.originX !== 'center' || this.originY !== 'center') && this.centeredRotation;
  11763.  
  11764. if (shouldCenterOrigin) {
  11765. this._setOriginToCenter();
  11766. }
  11767.  
  11768. this.set('angle', angle);
  11769.  
  11770. if (shouldCenterOrigin) {
  11771. this._resetOrigin();
  11772. }
  11773.  
  11774. return this;
  11775. },
  11776.  
  11777. /**
  11778. * Centers object horizontally on canvas to which it was added last.
  11779. * You might need to call `setCoords` on an object after centering, to update controls area.
  11780. * @return {fabric.Object} thisArg
  11781. * @chainable
  11782. */
  11783. centerH: function () {
  11784. this.canvas.centerObjectH(this);
  11785. return this;
  11786. },
  11787.  
  11788. /**
  11789. * Centers object vertically on canvas to which it was added last.
  11790. * You might need to call `setCoords` on an object after centering, to update controls area.
  11791. * @return {fabric.Object} thisArg
  11792. * @chainable
  11793. */
  11794. centerV: function () {
  11795. this.canvas.centerObjectV(this);
  11796. return this;
  11797. },
  11798.  
  11799. /**
  11800. * Centers object vertically and horizontally on canvas to which is was added last
  11801. * You might need to call `setCoords` on an object after centering, to update controls area.
  11802. * @return {fabric.Object} thisArg
  11803. * @chainable
  11804. */
  11805. center: function () {
  11806. this.canvas.centerObject(this);
  11807. return this;
  11808. },
  11809.  
  11810. /**
  11811. * Removes object from canvas to which it was added last
  11812. * @return {fabric.Object} thisArg
  11813. * @chainable
  11814. */
  11815. remove: function() {
  11816. this.canvas.remove(this);
  11817. return this;
  11818. },
  11819.  
  11820. /**
  11821. * Returns coordinates of a pointer relative to an object
  11822. * @param {Event} e Event to operate upon
  11823. * @param {Object} [pointer] Pointer to operate upon (instead of event)
  11824. * @return {Object} Coordinates of a pointer (x, y)
  11825. */
  11826. getLocalPointer: function(e, pointer) {
  11827. pointer = pointer || this.canvas.getPointer(e);
  11828. var objectLeftTop = this.translateToOriginPoint(this.getCenterPoint(), 'left', 'top');
  11829. return {
  11830. x: pointer.x - objectLeftTop.x,
  11831. y: pointer.y - objectLeftTop.y
  11832. };
  11833. },
  11834.  
  11835. /**
  11836. * Sets canvas globalCompositeOperation for specific object
  11837. * custom composition operation for the particular object can be specifed using globalCompositeOperation property
  11838. * @param {CanvasRenderingContext2D} ctx Rendering canvas context
  11839. */
  11840. _setupCompositeOperation: function (ctx) {
  11841. if (this.globalCompositeOperation) {
  11842. this._prevGlobalCompositeOperation = ctx.globalCompositeOperation;
  11843. ctx.globalCompositeOperation = this.globalCompositeOperation;
  11844. }
  11845. },
  11846.  
  11847. /**
  11848. * Restores previously saved canvas globalCompositeOperation after obeject rendering
  11849. * @param {CanvasRenderingContext2D} ctx Rendering canvas context
  11850. */
  11851. _restoreCompositeOperation: function (ctx) {
  11852. if (this.globalCompositeOperation && this._prevGlobalCompositeOperation) {
  11853. ctx.globalCompositeOperation = this._prevGlobalCompositeOperation;
  11854. }
  11855. }
  11856. });
  11857.  
  11858. fabric.util.createAccessors(fabric.Object);
  11859.  
  11860. /**
  11861. * Alias for {@link fabric.Object.prototype.setAngle}
  11862. * @alias rotate -> setAngle
  11863. * @memberof fabric.Object
  11864. */
  11865. fabric.Object.prototype.rotate = fabric.Object.prototype.setAngle;
  11866.  
  11867. extend(fabric.Object.prototype, fabric.Observable);
  11868.  
  11869. /**
  11870. * Defines the number of fraction digits to use when serializing object values.
  11871. * You can use it to increase/decrease precision of such values like left, top, scaleX, scaleY, etc.
  11872. * @static
  11873. * @memberof fabric.Object
  11874. * @constant
  11875. * @type Number
  11876. */
  11877. fabric.Object.NUM_FRACTION_DIGITS = 2;
  11878.  
  11879. /**
  11880. * Unique id used internally when creating SVG elements
  11881. * @static
  11882. * @memberof fabric.Object
  11883. * @type Number
  11884. */
  11885. fabric.Object.__uid = 0;
  11886.  
  11887. })(typeof exports !== 'undefined' ? exports : this);
  11888.  
  11889.  
  11890. (function() {
  11891.  
  11892. var degreesToRadians = fabric.util.degreesToRadians;
  11893.  
  11894. fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {
  11895.  
  11896. /**
  11897. * Translates the coordinates from origin to center coordinates (based on the object's dimensions)
  11898. * @param {fabric.Point} point The point which corresponds to the originX and originY params
  11899. * @param {String} originX Horizontal origin: 'left', 'center' or 'right'
  11900. * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'
  11901. * @return {fabric.Point}
  11902. */
  11903. translateToCenterPoint: function(point, originX, originY) {
  11904. var cx = point.x,
  11905. cy = point.y,
  11906. strokeWidth = this.stroke ? this.strokeWidth : 0;
  11907.  
  11908. if (originX === 'left') {
  11909. cx = point.x + (this.getWidth() + strokeWidth * this.scaleX) / 2;
  11910. }
  11911. else if (originX === 'right') {
  11912. cx = point.x - (this.getWidth() + strokeWidth * this.scaleX) / 2;
  11913. }
  11914.  
  11915. if (originY === 'top') {
  11916. cy = point.y + (this.getHeight() + strokeWidth * this.scaleY) / 2;
  11917. }
  11918. else if (originY === 'bottom') {
  11919. cy = point.y - (this.getHeight() + strokeWidth * this.scaleY) / 2;
  11920. }
  11921.  
  11922. // Apply the reverse rotation to the point (it's already scaled properly)
  11923. return fabric.util.rotatePoint(new fabric.Point(cx, cy), point, degreesToRadians(this.angle));
  11924. },
  11925.  
  11926. /**
  11927. * Translates the coordinates from center to origin coordinates (based on the object's dimensions)
  11928. * @param {fabric.Point} center The point which corresponds to center of the object
  11929. * @param {String} originX Horizontal origin: 'left', 'center' or 'right'
  11930. * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'
  11931. * @return {fabric.Point}
  11932. */
  11933. translateToOriginPoint: function(center, originX, originY) {
  11934. var x = center.x,
  11935. y = center.y,
  11936. strokeWidth = this.stroke ? this.strokeWidth : 0;
  11937.  
  11938. // Get the point coordinates
  11939. if (originX === 'left') {
  11940. x = center.x - (this.getWidth() + strokeWidth * this.scaleX) / 2;
  11941. }
  11942. else if (originX === 'right') {
  11943. x = center.x + (this.getWidth() + strokeWidth * this.scaleX) / 2;
  11944. }
  11945. if (originY === 'top') {
  11946. y = center.y - (this.getHeight() + strokeWidth * this.scaleY) / 2;
  11947. }
  11948. else if (originY === 'bottom') {
  11949. y = center.y + (this.getHeight() + strokeWidth * this.scaleY) / 2;
  11950. }
  11951.  
  11952. // Apply the rotation to the point (it's already scaled properly)
  11953. return fabric.util.rotatePoint(new fabric.Point(x, y), center, degreesToRadians(this.angle));
  11954. },
  11955.  
  11956. /**
  11957. * Returns the real center coordinates of the object
  11958. * @return {fabric.Point}
  11959. */
  11960. getCenterPoint: function() {
  11961. var leftTop = new fabric.Point(this.left, this.top);
  11962. return this.translateToCenterPoint(leftTop, this.originX, this.originY);
  11963. },
  11964.  
  11965. /**
  11966. * Returns the coordinates of the object based on center coordinates
  11967. * @param {fabric.Point} point The point which corresponds to the originX and originY params
  11968. * @return {fabric.Point}
  11969. */
  11970. // getOriginPoint: function(center) {
  11971. // return this.translateToOriginPoint(center, this.originX, this.originY);
  11972. // },
  11973.  
  11974. /**
  11975. * Returns the coordinates of the object as if it has a different origin
  11976. * @param {String} originX Horizontal origin: 'left', 'center' or 'right'
  11977. * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'
  11978. * @return {fabric.Point}
  11979. */
  11980. getPointByOrigin: function(originX, originY) {
  11981. var center = this.getCenterPoint();
  11982. return this.translateToOriginPoint(center, originX, originY);
  11983. },
  11984.  
  11985. /**
  11986. * Returns the point in local coordinates
  11987. * @param {fabric.Point} point The point relative to the global coordinate system
  11988. * @param {String} originX Horizontal origin: 'left', 'center' or 'right'
  11989. * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'
  11990. * @return {fabric.Point}
  11991. */
  11992. toLocalPoint: function(point, originX, originY) {
  11993. var center = this.getCenterPoint(),
  11994. strokeWidth = this.stroke ? this.strokeWidth : 0,
  11995. x, y;
  11996.  
  11997. if (originX && originY) {
  11998. if (originX === 'left') {
  11999. x = center.x - (this.getWidth() + strokeWidth * this.scaleX) / 2;
  12000. }
  12001. else if (originX === 'right') {
  12002. x = center.x + (this.getWidth() + strokeWidth * this.scaleX) / 2;
  12003. }
  12004. else {
  12005. x = center.x;
  12006. }
  12007.  
  12008. if (originY === 'top') {
  12009. y = center.y - (this.getHeight() + strokeWidth * this.scaleY) / 2;
  12010. }
  12011. else if (originY === 'bottom') {
  12012. y = center.y + (this.getHeight() + strokeWidth * this.scaleY) / 2;
  12013. }
  12014. else {
  12015. y = center.y;
  12016. }
  12017. }
  12018. else {
  12019. x = this.left;
  12020. y = this.top;
  12021. }
  12022.  
  12023. return fabric.util.rotatePoint(new fabric.Point(point.x, point.y), center, -degreesToRadians(this.angle))
  12024. .subtractEquals(new fabric.Point(x, y));
  12025. },
  12026.  
  12027. /**
  12028. * Returns the point in global coordinates
  12029. * @param {fabric.Point} The point relative to the local coordinate system
  12030. * @return {fabric.Point}
  12031. */
  12032. // toGlobalPoint: function(point) {
  12033. // return fabric.util.rotatePoint(point, this.getCenterPoint(), degreesToRadians(this.angle)).addEquals(new fabric.Point(this.left, this.top));
  12034. // },
  12035.  
  12036. /**
  12037. * Sets the position of the object taking into consideration the object's origin
  12038. * @param {fabric.Point} pos The new position of the object
  12039. * @param {String} originX Horizontal origin: 'left', 'center' or 'right'
  12040. * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'
  12041. * @return {void}
  12042. */
  12043. setPositionByOrigin: function(pos, originX, originY) {
  12044. var center = this.translateToCenterPoint(pos, originX, originY),
  12045. position = this.translateToOriginPoint(center, this.originX, this.originY);
  12046.  
  12047. this.set('left', position.x);
  12048. this.set('top', position.y);
  12049. },
  12050.  
  12051. /**
  12052. * @param {String} to One of 'left', 'center', 'right'
  12053. */
  12054. adjustPosition: function(to) {
  12055. var angle = degreesToRadians(this.angle),
  12056. hypotHalf = this.getWidth() / 2,
  12057. xHalf = Math.cos(angle) * hypotHalf,
  12058. yHalf = Math.sin(angle) * hypotHalf,
  12059. hypotFull = this.getWidth(),
  12060. xFull = Math.cos(angle) * hypotFull,
  12061. yFull = Math.sin(angle) * hypotFull;
  12062.  
  12063. if (this.originX === 'center' && to === 'left' ||
  12064. this.originX === 'right' && to === 'center') {
  12065. // move half left
  12066. this.left -= xHalf;
  12067. this.top -= yHalf;
  12068. }
  12069. else if (this.originX === 'left' && to === 'center' ||
  12070. this.originX === 'center' && to === 'right') {
  12071. // move half right
  12072. this.left += xHalf;
  12073. this.top += yHalf;
  12074. }
  12075. else if (this.originX === 'left' && to === 'right') {
  12076. // move full right
  12077. this.left += xFull;
  12078. this.top += yFull;
  12079. }
  12080. else if (this.originX === 'right' && to === 'left') {
  12081. // move full left
  12082. this.left -= xFull;
  12083. this.top -= yFull;
  12084. }
  12085.  
  12086. this.setCoords();
  12087. this.originX = to;
  12088. },
  12089.  
  12090. /**
  12091. * Sets the origin/position of the object to it's center point
  12092. * @private
  12093. * @return {void}
  12094. */
  12095. _setOriginToCenter: function() {
  12096. this._originalOriginX = this.originX;
  12097. this._originalOriginY = this.originY;
  12098.  
  12099. var center = this.getCenterPoint();
  12100.  
  12101. this.originX = 'center';
  12102. this.originY = 'center';
  12103.  
  12104. this.left = center.x;
  12105. this.top = center.y;
  12106. },
  12107.  
  12108. /**
  12109. * Resets the origin/position of the object to it's original origin
  12110. * @private
  12111. * @return {void}
  12112. */
  12113. _resetOrigin: function() {
  12114. var originPoint = this.translateToOriginPoint(
  12115. this.getCenterPoint(),
  12116. this._originalOriginX,
  12117. this._originalOriginY);
  12118.  
  12119. this.originX = this._originalOriginX;
  12120. this.originY = this._originalOriginY;
  12121.  
  12122. this.left = originPoint.x;
  12123. this.top = originPoint.y;
  12124.  
  12125. this._originalOriginX = null;
  12126. this._originalOriginY = null;
  12127. },
  12128.  
  12129. /**
  12130. * @private
  12131. */
  12132. _getLeftTopCoords: function() {
  12133. return this.translateToOriginPoint(this.getCenterPoint(), 'left', 'center');
  12134. }
  12135. });
  12136.  
  12137. })();
  12138.  
  12139.  
  12140. (function() {
  12141.  
  12142. var degreesToRadians = fabric.util.degreesToRadians;
  12143.  
  12144. fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {
  12145.  
  12146. /**
  12147. * Object containing coordinates of object's controls
  12148. * @type Object
  12149. * @default
  12150. */
  12151. oCoords: null,
  12152.  
  12153. /**
  12154. * Checks if object intersects with an area formed by 2 points
  12155. * @param {Object} pointTL top-left point of area
  12156. * @param {Object} pointBR bottom-right point of area
  12157. * @return {Boolean} true if object intersects with an area formed by 2 points
  12158. */
  12159. intersectsWithRect: function(pointTL, pointBR) {
  12160. var oCoords = this.oCoords,
  12161. tl = new fabric.Point(oCoords.tl.x, oCoords.tl.y),
  12162. tr = new fabric.Point(oCoords.tr.x, oCoords.tr.y),
  12163. bl = new fabric.Point(oCoords.bl.x, oCoords.bl.y),
  12164. br = new fabric.Point(oCoords.br.x, oCoords.br.y),
  12165. intersection = fabric.Intersection.intersectPolygonRectangle(
  12166. [tl, tr, br, bl],
  12167. pointTL,
  12168. pointBR
  12169. );
  12170. return intersection.status === 'Intersection';
  12171. },
  12172.  
  12173. /**
  12174. * Checks if object intersects with another object
  12175. * @param {Object} other Object to test
  12176. * @return {Boolean} true if object intersects with another object
  12177. */
  12178. intersectsWithObject: function(other) {
  12179. // extracts coords
  12180. function getCoords(oCoords) {
  12181. return {
  12182. tl: new fabric.Point(oCoords.tl.x, oCoords.tl.y),
  12183. tr: new fabric.Point(oCoords.tr.x, oCoords.tr.y),
  12184. bl: new fabric.Point(oCoords.bl.x, oCoords.bl.y),
  12185. br: new fabric.Point(oCoords.br.x, oCoords.br.y)
  12186. };
  12187. }
  12188. var thisCoords = getCoords(this.oCoords),
  12189. otherCoords = getCoords(other.oCoords),
  12190. intersection = fabric.Intersection.intersectPolygonPolygon(
  12191. [thisCoords.tl, thisCoords.tr, thisCoords.br, thisCoords.bl],
  12192. [otherCoords.tl, otherCoords.tr, otherCoords.br, otherCoords.bl]
  12193. );
  12194.  
  12195. return intersection.status === 'Intersection';
  12196. },
  12197.  
  12198. /**
  12199. * Checks if object is fully contained within area of another object
  12200. * @param {Object} other Object to test
  12201. * @return {Boolean} true if object is fully contained within area of another object
  12202. */
  12203. isContainedWithinObject: function(other) {
  12204. var boundingRect = other.getBoundingRect(),
  12205. point1 = new fabric.Point(boundingRect.left, boundingRect.top),
  12206. point2 = new fabric.Point(boundingRect.left + boundingRect.width, boundingRect.top + boundingRect.height);
  12207.  
  12208. return this.isContainedWithinRect(point1, point2);
  12209. },
  12210.  
  12211. /**
  12212. * Checks if object is fully contained within area formed by 2 points
  12213. * @param {Object} pointTL top-left point of area
  12214. * @param {Object} pointBR bottom-right point of area
  12215. * @return {Boolean} true if object is fully contained within area formed by 2 points
  12216. */
  12217. isContainedWithinRect: function(pointTL, pointBR) {
  12218. var boundingRect = this.getBoundingRect();
  12219.  
  12220. return (
  12221. boundingRect.left >= pointTL.x &&
  12222. boundingRect.left + boundingRect.width <= pointBR.x &&
  12223. boundingRect.top >= pointTL.y &&
  12224. boundingRect.top + boundingRect.height <= pointBR.y
  12225. );
  12226. },
  12227.  
  12228. /**
  12229. * Checks if point is inside the object
  12230. * @param {fabric.Point} point Point to check against
  12231. * @return {Boolean} true if point is inside the object
  12232. */
  12233. containsPoint: function(point) {
  12234. var lines = this._getImageLines(this.oCoords),
  12235. xPoints = this._findCrossPoints(point, lines);
  12236.  
  12237. // if xPoints is odd then point is inside the object
  12238. return (xPoints !== 0 && xPoints % 2 === 1);
  12239. },
  12240.  
  12241. /**
  12242. * Method that returns an object with the object edges in it, given the coordinates of the corners
  12243. * @private
  12244. * @param {Object} oCoords Coordinates of the object corners
  12245. */
  12246. _getImageLines: function(oCoords) {
  12247. return {
  12248. topline: {
  12249. o: oCoords.tl,
  12250. d: oCoords.tr
  12251. },
  12252. rightline: {
  12253. o: oCoords.tr,
  12254. d: oCoords.br
  12255. },
  12256. bottomline: {
  12257. o: oCoords.br,
  12258. d: oCoords.bl
  12259. },
  12260. leftline: {
  12261. o: oCoords.bl,
  12262. d: oCoords.tl
  12263. }
  12264. };
  12265. },
  12266.  
  12267. /**
  12268. * Helper method to determine how many cross points are between the 4 object edges
  12269. * and the horizontal line determined by a point on canvas
  12270. * @private
  12271. * @param {fabric.Point} point Point to check
  12272. * @param {Object} oCoords Coordinates of the object being evaluated
  12273. */
  12274. _findCrossPoints: function(point, oCoords) {
  12275. var b1, b2, a1, a2, xi, yi,
  12276. xcount = 0,
  12277. iLine;
  12278.  
  12279. for (var lineKey in oCoords) {
  12280. iLine = oCoords[lineKey];
  12281. // optimisation 1: line below point. no cross
  12282. if ((iLine.o.y < point.y) && (iLine.d.y < point.y)) {
  12283. continue;
  12284. }
  12285. // optimisation 2: line above point. no cross
  12286. if ((iLine.o.y >= point.y) && (iLine.d.y >= point.y)) {
  12287. continue;
  12288. }
  12289. // optimisation 3: vertical line case
  12290. if ((iLine.o.x === iLine.d.x) && (iLine.o.x >= point.x)) {
  12291. xi = iLine.o.x;
  12292. yi = point.y;
  12293. }
  12294. // calculate the intersection point
  12295. else {
  12296. b1 = 0;
  12297. b2 = (iLine.d.y - iLine.o.y) / (iLine.d.x - iLine.o.x);
  12298. a1 = point.y - b1 * point.x;
  12299. a2 = iLine.o.y - b2 * iLine.o.x;
  12300.  
  12301. xi = - (a1 - a2) / (b1 - b2);
  12302. yi = a1 + b1 * xi;
  12303. }
  12304. // dont count xi < point.x cases
  12305. if (xi >= point.x) {
  12306. xcount += 1;
  12307. }
  12308. // optimisation 4: specific for square images
  12309. if (xcount === 2) {
  12310. break;
  12311. }
  12312. }
  12313. return xcount;
  12314. },
  12315.  
  12316. /**
  12317. * Returns width of an object's bounding rectangle
  12318. * @deprecated since 1.0.4
  12319. * @return {Number} width value
  12320. */
  12321. getBoundingRectWidth: function() {
  12322. return this.getBoundingRect().width;
  12323. },
  12324.  
  12325. /**
  12326. * Returns height of an object's bounding rectangle
  12327. * @deprecated since 1.0.4
  12328. * @return {Number} height value
  12329. */
  12330. getBoundingRectHeight: function() {
  12331. return this.getBoundingRect().height;
  12332. },
  12333.  
  12334. /**
  12335. * Returns coordinates of object's bounding rectangle (left, top, width, height)
  12336. * @return {Object} Object with left, top, width, height properties
  12337. */
  12338. getBoundingRect: function() {
  12339. this.oCoords || this.setCoords();
  12340.  
  12341. var xCoords = [this.oCoords.tl.x, this.oCoords.tr.x, this.oCoords.br.x, this.oCoords.bl.x],
  12342. minX = fabric.util.array.min(xCoords),
  12343. maxX = fabric.util.array.max(xCoords),
  12344. width = Math.abs(minX - maxX),
  12345.  
  12346. yCoords = [this.oCoords.tl.y, this.oCoords.tr.y, this.oCoords.br.y, this.oCoords.bl.y],
  12347. minY = fabric.util.array.min(yCoords),
  12348. maxY = fabric.util.array.max(yCoords),
  12349. height = Math.abs(minY - maxY);
  12350.  
  12351. return {
  12352. left: minX,
  12353. top: minY,
  12354. width: width,
  12355. height: height
  12356. };
  12357. },
  12358.  
  12359. /**
  12360. * Returns width of an object
  12361. * @return {Number} width value
  12362. */
  12363. getWidth: function() {
  12364. return this.width * this.scaleX;
  12365. },
  12366.  
  12367. /**
  12368. * Returns height of an object
  12369. * @return {Number} height value
  12370. */
  12371. getHeight: function() {
  12372. return this.height * this.scaleY;
  12373. },
  12374.  
  12375. /**
  12376. * Makes sure the scale is valid and modifies it if necessary
  12377. * @private
  12378. * @param {Number} value
  12379. * @return {Number}
  12380. */
  12381. _constrainScale: function(value) {
  12382. if (Math.abs(value) < this.minScaleLimit) {
  12383. if (value < 0) {
  12384. return -this.minScaleLimit;
  12385. }
  12386. else {
  12387. return this.minScaleLimit;
  12388. }
  12389. }
  12390. return value;
  12391. },
  12392.  
  12393. /**
  12394. * Scales an object (equally by x and y)
  12395. * @param {Number} value Scale factor
  12396. * @return {fabric.Object} thisArg
  12397. * @chainable
  12398. */
  12399. scale: function(value) {
  12400. value = this._constrainScale(value);
  12401.  
  12402. if (value < 0) {
  12403. this.flipX = !this.flipX;
  12404. this.flipY = !this.flipY;
  12405. value *= -1;
  12406. }
  12407.  
  12408. this.scaleX = value;
  12409. this.scaleY = value;
  12410. this.setCoords();
  12411. return this;
  12412. },
  12413.  
  12414. /**
  12415. * Scales an object to a given width, with respect to bounding box (scaling by x/y equally)
  12416. * @param {Number} value New width value
  12417. * @return {fabric.Object} thisArg
  12418. * @chainable
  12419. */
  12420. scaleToWidth: function(value) {
  12421. // adjust to bounding rect factor so that rotated shapes would fit as well
  12422. var boundingRectFactor = this.getBoundingRectWidth() / this.getWidth();
  12423. return this.scale(value / this.width / boundingRectFactor);
  12424. },
  12425.  
  12426. /**
  12427. * Scales an object to a given height, with respect to bounding box (scaling by x/y equally)
  12428. * @param {Number} value New height value
  12429. * @return {fabric.Object} thisArg
  12430. * @chainable
  12431. */
  12432. scaleToHeight: function(value) {
  12433. // adjust to bounding rect factor so that rotated shapes would fit as well
  12434. var boundingRectFactor = this.getBoundingRectHeight() / this.getHeight();
  12435. return this.scale(value / this.height / boundingRectFactor);
  12436. },
  12437.  
  12438. /**
  12439. * Sets corner position coordinates based on current angle, width and height
  12440. * @return {fabric.Object} thisArg
  12441. * @chainable
  12442. */
  12443. setCoords: function() {
  12444. var strokeWidth = this.strokeWidth > 1 ? this.strokeWidth : 0,
  12445. theta = degreesToRadians(this.angle),
  12446. vpt = this.getViewportTransform(),
  12447. f = function (p) {
  12448. return fabric.util.transformPoint(p, vpt);
  12449. },
  12450. w = this.width,
  12451. h = this.height,
  12452. capped = this.strokeLineCap === 'round' || this.strokeLineCap === 'square',
  12453. vLine = this.type === 'line' && this.width === 1,
  12454. hLine = this.type === 'line' && this.height === 1,
  12455. strokeW = (capped && hLine) || this.type !== 'line',
  12456. strokeH = (capped && vLine) || this.type !== 'line';
  12457.  
  12458. if (vLine) {
  12459. w = strokeWidth;
  12460. }
  12461. else if (hLine) {
  12462. h = strokeWidth;
  12463. }
  12464. if (strokeW) {
  12465. w += strokeWidth;
  12466. }
  12467. if (strokeH) {
  12468. h += strokeWidth;
  12469. }
  12470. this.currentWidth = w * this.scaleX;
  12471. this.currentHeight = h * this.scaleY;
  12472.  
  12473. // If width is negative, make postive. Fixes path selection issue
  12474. if (this.currentWidth < 0) {
  12475. this.currentWidth = Math.abs(this.currentWidth);
  12476. }
  12477.  
  12478. var _hypotenuse = Math.sqrt(
  12479. Math.pow(this.currentWidth / 2, 2) +
  12480. Math.pow(this.currentHeight / 2, 2)),
  12481.  
  12482. _angle = Math.atan(
  12483. isFinite(this.currentHeight / this.currentWidth)
  12484. ? this.currentHeight / this.currentWidth
  12485. : 0),
  12486.  
  12487. // offset added for rotate and scale actions
  12488. offsetX = Math.cos(_angle + theta) * _hypotenuse,
  12489. offsetY = Math.sin(_angle + theta) * _hypotenuse,
  12490. sinTh = Math.sin(theta),
  12491. cosTh = Math.cos(theta),
  12492. coords = this.getCenterPoint(),
  12493. wh = new fabric.Point(this.currentWidth, this.currentHeight),
  12494. _tl = new fabric.Point(coords.x - offsetX, coords.y - offsetY),
  12495. _tr = new fabric.Point(_tl.x + (wh.x * cosTh), _tl.y + (wh.x * sinTh)),
  12496. _bl = new fabric.Point(_tl.x - (wh.y * sinTh), _tl.y + (wh.y * cosTh)),
  12497. _mt = new fabric.Point(_tl.x + (wh.x/2 * cosTh), _tl.y + (wh.x/2 * sinTh)),
  12498. tl = f(_tl),
  12499. tr = f(_tr),
  12500. br = f(new fabric.Point(_tr.x - (wh.y * sinTh), _tr.y + (wh.y * cosTh))),
  12501. bl = f(_bl),
  12502. ml = f(new fabric.Point(_tl.x - (wh.y/2 * sinTh), _tl.y + (wh.y/2 * cosTh))),
  12503. mt = f(_mt),
  12504. mr = f(new fabric.Point(_tr.x - (wh.y/2 * sinTh), _tr.y + (wh.y/2 * cosTh))),
  12505. mb = f(new fabric.Point(_bl.x + (wh.x/2 * cosTh), _bl.y + (wh.x/2 * sinTh))),
  12506. mtr = f(new fabric.Point(_mt.x, _mt.y)),
  12507.  
  12508. // padding
  12509. padX = Math.cos(_angle + theta) * this.padding * Math.sqrt(2),
  12510. padY = Math.sin(_angle + theta) * this.padding * Math.sqrt(2);
  12511.  
  12512. tl = tl.add(new fabric.Point(-padX, -padY));
  12513. tr = tr.add(new fabric.Point(padY, -padX));
  12514. br = br.add(new fabric.Point(padX, padY));
  12515. bl = bl.add(new fabric.Point(-padY, padX));
  12516. ml = ml.add(new fabric.Point((-padX - padY) / 2, (-padY + padX) / 2));
  12517. mt = mt.add(new fabric.Point((padY - padX) / 2, -(padY + padX) / 2));
  12518. mr = mr.add(new fabric.Point((padY + padX) / 2, (padY - padX) / 2));
  12519. mb = mb.add(new fabric.Point((padX - padY) / 2, (padX + padY) / 2));
  12520. mtr = mtr.add(new fabric.Point((padY - padX) / 2, -(padY + padX) / 2));
  12521.  
  12522. // debugging
  12523.  
  12524. // setTimeout(function() {
  12525. // canvas.contextTop.fillStyle = 'green';
  12526. // canvas.contextTop.fillRect(mb.x, mb.y, 3, 3);
  12527. // canvas.contextTop.fillRect(bl.x, bl.y, 3, 3);
  12528. // canvas.contextTop.fillRect(br.x, br.y, 3, 3);
  12529. // canvas.contextTop.fillRect(tl.x, tl.y, 3, 3);
  12530. // canvas.contextTop.fillRect(tr.x, tr.y, 3, 3);
  12531. // canvas.contextTop.fillRect(ml.x, ml.y, 3, 3);
  12532. // canvas.contextTop.fillRect(mr.x, mr.y, 3, 3);
  12533. // canvas.contextTop.fillRect(mt.x, mt.y, 3, 3);
  12534. // }, 50);
  12535.  
  12536. this.oCoords = {
  12537. // corners
  12538. tl: tl, tr: tr, br: br, bl: bl,
  12539. // middle
  12540. ml: ml, mt: mt, mr: mr, mb: mb,
  12541. // rotating point
  12542. mtr: mtr
  12543. };
  12544.  
  12545. // set coordinates of the draggable boxes in the corners used to scale/rotate the image
  12546. this._setCornerCoords && this._setCornerCoords();
  12547.  
  12548. return this;
  12549. }
  12550. });
  12551. })();
  12552.  
  12553.  
  12554. fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {
  12555.  
  12556. /**
  12557. * Moves an object to the bottom of the stack of drawn objects
  12558. * @return {fabric.Object} thisArg
  12559. * @chainable
  12560. */
  12561. sendToBack: function() {
  12562. if (this.group) {
  12563. fabric.StaticCanvas.prototype.sendToBack.call(this.group, this);
  12564. }
  12565. else {
  12566. this.canvas.sendToBack(this);
  12567. }
  12568. return this;
  12569. },
  12570.  
  12571. /**
  12572. * Moves an object to the top of the stack of drawn objects
  12573. * @return {fabric.Object} thisArg
  12574. * @chainable
  12575. */
  12576. bringToFront: function() {
  12577. if (this.group) {
  12578. fabric.StaticCanvas.prototype.bringToFront.call(this.group, this);
  12579. }
  12580. else {
  12581. this.canvas.bringToFront(this);
  12582. }
  12583. return this;
  12584. },
  12585.  
  12586. /**
  12587. * Moves an object down in stack of drawn objects
  12588. * @param {Boolean} [intersecting] If `true`, send object behind next lower intersecting object
  12589. * @return {fabric.Object} thisArg
  12590. * @chainable
  12591. */
  12592. sendBackwards: function(intersecting) {
  12593. if (this.group) {
  12594. fabric.StaticCanvas.prototype.sendBackwards.call(this.group, this, intersecting);
  12595. }
  12596. else {
  12597. this.canvas.sendBackwards(this, intersecting);
  12598. }
  12599. return this;
  12600. },
  12601.  
  12602. /**
  12603. * Moves an object up in stack of drawn objects
  12604. * @param {Boolean} [intersecting] If `true`, send object in front of next upper intersecting object
  12605. * @return {fabric.Object} thisArg
  12606. * @chainable
  12607. */
  12608. bringForward: function(intersecting) {
  12609. if (this.group) {
  12610. fabric.StaticCanvas.prototype.bringForward.call(this.group, this, intersecting);
  12611. }
  12612. else {
  12613. this.canvas.bringForward(this, intersecting);
  12614. }
  12615. return this;
  12616. },
  12617.  
  12618. /**
  12619. * Moves an object to specified level in stack of drawn objects
  12620. * @param {Number} index New position of object
  12621. * @return {fabric.Object} thisArg
  12622. * @chainable
  12623. */
  12624. moveTo: function(index) {
  12625. if (this.group) {
  12626. fabric.StaticCanvas.prototype.moveTo.call(this.group, this, index);
  12627. }
  12628. else {
  12629. this.canvas.moveTo(this, index);
  12630. }
  12631. return this;
  12632. }
  12633. });
  12634.  
  12635.  
  12636. /* _TO_SVG_START_ */
  12637. fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {
  12638.  
  12639. /**
  12640. * Returns styles-string for svg-export
  12641. * @return {String}
  12642. */
  12643. getSvgStyles: function() {
  12644.  
  12645. var fill = this.fill
  12646. ? (this.fill.toLive ? 'url(#SVGID_' + this.fill.id + ')' : this.fill)
  12647. : 'none',
  12648. fillRule = this.fillRule,
  12649. stroke = this.stroke
  12650. ? (this.stroke.toLive ? 'url(#SVGID_' + this.stroke.id + ')' : this.stroke)
  12651. : 'none',
  12652.  
  12653. strokeWidth = this.strokeWidth ? this.strokeWidth : '0',
  12654. strokeDashArray = this.strokeDashArray ? this.strokeDashArray.join(' ') : '',
  12655. strokeLineCap = this.strokeLineCap ? this.strokeLineCap : 'butt',
  12656. strokeLineJoin = this.strokeLineJoin ? this.strokeLineJoin : 'miter',
  12657. strokeMiterLimit = this.strokeMiterLimit ? this.strokeMiterLimit : '4',
  12658. opacity = typeof this.opacity !== 'undefined' ? this.opacity : '1',
  12659.  
  12660. visibility = this.visible ? '' : ' visibility: hidden;',
  12661. filter = this.shadow && this.type !== 'text' ? 'filter: url(#SVGID_' + this.shadow.id + ');' : '';
  12662.  
  12663. return [
  12664. 'stroke: ', stroke, '; ',
  12665. 'stroke-width: ', strokeWidth, '; ',
  12666. 'stroke-dasharray: ', strokeDashArray, '; ',
  12667. 'stroke-linecap: ', strokeLineCap, '; ',
  12668. 'stroke-linejoin: ', strokeLineJoin, '; ',
  12669. 'stroke-miterlimit: ', strokeMiterLimit, '; ',
  12670. 'fill: ', fill, '; ',
  12671. 'fill-rule: ', fillRule, '; ',
  12672. 'opacity: ', opacity, ';',
  12673. filter,
  12674. visibility
  12675. ].join('');
  12676. },
  12677.  
  12678. /**
  12679. * Returns transform-string for svg-export
  12680. * @return {String}
  12681. */
  12682. getSvgTransform: function() {
  12683. if (this.group && this.group.type === 'path-group') {
  12684. return '';
  12685. }
  12686. var toFixed = fabric.util.toFixed,
  12687. angle = this.getAngle(),
  12688. vpt = !this.canvas || this.canvas.svgViewportTransformation ? this.getViewportTransform() : [1, 0, 0, 1, 0, 0],
  12689. center = fabric.util.transformPoint(this.getCenterPoint(), vpt),
  12690.  
  12691. NUM_FRACTION_DIGITS = fabric.Object.NUM_FRACTION_DIGITS,
  12692.  
  12693. translatePart = this.type === 'path-group' ? '' : 'translate(' +
  12694. toFixed(center.x, NUM_FRACTION_DIGITS) +
  12695. ' ' +
  12696. toFixed(center.y, NUM_FRACTION_DIGITS) +
  12697. ')',
  12698.  
  12699. anglePart = angle !== 0
  12700. ? (' rotate(' + toFixed(angle, NUM_FRACTION_DIGITS) + ')')
  12701. : '',
  12702.  
  12703. scalePart = (this.scaleX === 1 && this.scaleY === 1 && vpt[0] === 1 && vpt[3] === 1)
  12704. ? '' :
  12705. (' scale(' +
  12706. toFixed(this.scaleX * vpt[0], NUM_FRACTION_DIGITS) +
  12707. ' ' +
  12708. toFixed(this.scaleY * vpt[3], NUM_FRACTION_DIGITS) +
  12709. ')'),
  12710.  
  12711. addTranslateX = this.type === 'path-group' ? this.width * vpt[0] : 0,
  12712.  
  12713. flipXPart = this.flipX ? ' matrix(-1 0 0 1 ' + addTranslateX + ' 0) ' : '',
  12714.  
  12715. addTranslateY = this.type === 'path-group' ? this.height * vpt[3] : 0,
  12716.  
  12717. flipYPart = this.flipY ? ' matrix(1 0 0 -1 0 ' + addTranslateY + ')' : '';
  12718.  
  12719. return [
  12720. translatePart, anglePart, scalePart, flipXPart, flipYPart
  12721. ].join('');
  12722. },
  12723.  
  12724. /**
  12725. * Returns transform-string for svg-export from the transform matrix of single elements
  12726. * @return {String}
  12727. */
  12728. getSvgTransformMatrix: function() {
  12729. return this.transformMatrix ? ' matrix(' + this.transformMatrix.join(' ') + ')' : '';
  12730. },
  12731.  
  12732. /**
  12733. * @private
  12734. */
  12735. _createBaseSVGMarkup: function() {
  12736. var markup = [ ];
  12737.  
  12738. if (this.fill && this.fill.toLive) {
  12739. markup.push(this.fill.toSVG(this, false));
  12740. }
  12741. if (this.stroke && this.stroke.toLive) {
  12742. markup.push(this.stroke.toSVG(this, false));
  12743. }
  12744. if (this.shadow) {
  12745. markup.push(this.shadow.toSVG(this));
  12746. }
  12747. return markup;
  12748. }
  12749. });
  12750. /* _TO_SVG_END_ */
  12751.  
  12752.  
  12753. /*
  12754. Depends on `stateProperties`
  12755. */
  12756. fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {
  12757.  
  12758. /**
  12759. * Returns true if object state (one of its state properties) was changed
  12760. * @return {Boolean} true if instance' state has changed since `{@link fabric.Object#saveState}` was called
  12761. */
  12762. hasStateChanged: function() {
  12763. return this.stateProperties.some(function(prop) {
  12764. return this.get(prop) !== this.originalState[prop];
  12765. }, this);
  12766. },
  12767.  
  12768. /**
  12769. * Saves state of an object
  12770. * @param {Object} [options] Object with additional `stateProperties` array to include when saving state
  12771. * @return {fabric.Object} thisArg
  12772. */
  12773. saveState: function(options) {
  12774. this.stateProperties.forEach(function(prop) {
  12775. this.originalState[prop] = this.get(prop);
  12776. }, this);
  12777.  
  12778. if (options && options.stateProperties) {
  12779. options.stateProperties.forEach(function(prop) {
  12780. this.originalState[prop] = this.get(prop);
  12781. }, this);
  12782. }
  12783.  
  12784. return this;
  12785. },
  12786.  
  12787. /**
  12788. * Setups state of an object
  12789. * @return {fabric.Object} thisArg
  12790. */
  12791. setupState: function() {
  12792. this.originalState = { };
  12793. this.saveState();
  12794.  
  12795. return this;
  12796. }
  12797. });
  12798.  
  12799.  
  12800. (function() {
  12801.  
  12802. var degreesToRadians = fabric.util.degreesToRadians,
  12803. //jscs:disable requireCamelCaseOrUpperCaseIdentifiers
  12804. isVML = function() { return typeof G_vmlCanvasManager !== 'undefined'; };
  12805. //jscs:enable requireCamelCaseOrUpperCaseIdentifiers
  12806.  
  12807. fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {
  12808.  
  12809. /**
  12810. * The object interactivity controls.
  12811. * @private
  12812. */
  12813. _controlsVisibility: null,
  12814.  
  12815. /**
  12816. * Determines which corner has been clicked
  12817. * @private
  12818. * @param {Object} pointer The pointer indicating the mouse position
  12819. * @return {String|Boolean} corner code (tl, tr, bl, br, etc.), or false if nothing is found
  12820. */
  12821. _findTargetCorner: function(pointer) {
  12822. if (!this.hasControls || !this.active) {
  12823. return false;
  12824. }
  12825.  
  12826. var ex = pointer.x,
  12827. ey = pointer.y,
  12828. xPoints,
  12829. lines;
  12830.  
  12831. for (var i in this.oCoords) {
  12832.  
  12833. if (!this.isControlVisible(i)) {
  12834. continue;
  12835. }
  12836.  
  12837. if (i === 'mtr' && !this.hasRotatingPoint) {
  12838. continue;
  12839. }
  12840.  
  12841. if (this.get('lockUniScaling') &&
  12842. (i === 'mt' || i === 'mr' || i === 'mb' || i === 'ml')) {
  12843. continue;
  12844. }
  12845.  
  12846. lines = this._getImageLines(this.oCoords[i].corner);
  12847.  
  12848. // debugging
  12849.  
  12850. // canvas.contextTop.fillRect(lines.bottomline.d.x, lines.bottomline.d.y, 2, 2);
  12851. // canvas.contextTop.fillRect(lines.bottomline.o.x, lines.bottomline.o.y, 2, 2);
  12852.  
  12853. // canvas.contextTop.fillRect(lines.leftline.d.x, lines.leftline.d.y, 2, 2);
  12854. // canvas.contextTop.fillRect(lines.leftline.o.x, lines.leftline.o.y, 2, 2);
  12855.  
  12856. // canvas.contextTop.fillRect(lines.topline.d.x, lines.topline.d.y, 2, 2);
  12857. // canvas.contextTop.fillRect(lines.topline.o.x, lines.topline.o.y, 2, 2);
  12858.  
  12859. // canvas.contextTop.fillRect(lines.rightline.d.x, lines.rightline.d.y, 2, 2);
  12860. // canvas.contextTop.fillRect(lines.rightline.o.x, lines.rightline.o.y, 2, 2);
  12861.  
  12862. xPoints = this._findCrossPoints({ x: ex, y: ey }, lines);
  12863. if (xPoints !== 0 && xPoints % 2 === 1) {
  12864. this.__corner = i;
  12865. return i;
  12866. }
  12867. }
  12868. return false;
  12869. },
  12870.  
  12871. /**
  12872. * Sets the coordinates of the draggable boxes in the corners of
  12873. * the image used to scale/rotate it.
  12874. * @private
  12875. */
  12876. _setCornerCoords: function() {
  12877. var coords = this.oCoords,
  12878. theta = degreesToRadians(this.angle),
  12879. newTheta = degreesToRadians(45 - this.angle),
  12880. cornerHypotenuse = Math.sqrt(2 * Math.pow(this.cornerSize, 2)) / 2,
  12881. cosHalfOffset = cornerHypotenuse * Math.cos(newTheta),
  12882. sinHalfOffset = cornerHypotenuse * Math.sin(newTheta),
  12883. sinTh = Math.sin(theta),
  12884. cosTh = Math.cos(theta);
  12885.  
  12886. coords.tl.corner = {
  12887. tl: {
  12888. x: coords.tl.x - sinHalfOffset,
  12889. y: coords.tl.y - cosHalfOffset
  12890. },
  12891. tr: {
  12892. x: coords.tl.x + cosHalfOffset,
  12893. y: coords.tl.y - sinHalfOffset
  12894. },
  12895. bl: {
  12896. x: coords.tl.x - cosHalfOffset,
  12897. y: coords.tl.y + sinHalfOffset
  12898. },
  12899. br: {
  12900. x: coords.tl.x + sinHalfOffset,
  12901. y: coords.tl.y + cosHalfOffset
  12902. }
  12903. };
  12904.  
  12905. coords.tr.corner = {
  12906. tl: {
  12907. x: coords.tr.x - sinHalfOffset,
  12908. y: coords.tr.y - cosHalfOffset
  12909. },
  12910. tr: {
  12911. x: coords.tr.x + cosHalfOffset,
  12912. y: coords.tr.y - sinHalfOffset
  12913. },
  12914. br: {
  12915. x: coords.tr.x + sinHalfOffset,
  12916. y: coords.tr.y + cosHalfOffset
  12917. },
  12918. bl: {
  12919. x: coords.tr.x - cosHalfOffset,
  12920. y: coords.tr.y + sinHalfOffset
  12921. }
  12922. };
  12923.  
  12924. coords.bl.corner = {
  12925. tl: {
  12926. x: coords.bl.x - sinHalfOffset,
  12927. y: coords.bl.y - cosHalfOffset
  12928. },
  12929. bl: {
  12930. x: coords.bl.x - cosHalfOffset,
  12931. y: coords.bl.y + sinHalfOffset
  12932. },
  12933. br: {
  12934. x: coords.bl.x + sinHalfOffset,
  12935. y: coords.bl.y + cosHalfOffset
  12936. },
  12937. tr: {
  12938. x: coords.bl.x + cosHalfOffset,
  12939. y: coords.bl.y - sinHalfOffset
  12940. }
  12941. };
  12942.  
  12943. coords.br.corner = {
  12944. tr: {
  12945. x: coords.br.x + cosHalfOffset,
  12946. y: coords.br.y - sinHalfOffset
  12947. },
  12948. bl: {
  12949. x: coords.br.x - cosHalfOffset,
  12950. y: coords.br.y + sinHalfOffset
  12951. },
  12952. br: {
  12953. x: coords.br.x + sinHalfOffset,
  12954. y: coords.br.y + cosHalfOffset
  12955. },
  12956. tl: {
  12957. x: coords.br.x - sinHalfOffset,
  12958. y: coords.br.y - cosHalfOffset
  12959. }
  12960. };
  12961.  
  12962. coords.ml.corner = {
  12963. tl: {
  12964. x: coords.ml.x - sinHalfOffset,
  12965. y: coords.ml.y - cosHalfOffset
  12966. },
  12967. tr: {
  12968. x: coords.ml.x + cosHalfOffset,
  12969. y: coords.ml.y - sinHalfOffset
  12970. },
  12971. bl: {
  12972. x: coords.ml.x - cosHalfOffset,
  12973. y: coords.ml.y + sinHalfOffset
  12974. },
  12975. br: {
  12976. x: coords.ml.x + sinHalfOffset,
  12977. y: coords.ml.y + cosHalfOffset
  12978. }
  12979. };
  12980.  
  12981. coords.mt.corner = {
  12982. tl: {
  12983. x: coords.mt.x - sinHalfOffset,
  12984. y: coords.mt.y - cosHalfOffset
  12985. },
  12986. tr: {
  12987. x: coords.mt.x + cosHalfOffset,
  12988. y: coords.mt.y - sinHalfOffset
  12989. },
  12990. bl: {
  12991. x: coords.mt.x - cosHalfOffset,
  12992. y: coords.mt.y + sinHalfOffset
  12993. },
  12994. br: {
  12995. x: coords.mt.x + sinHalfOffset,
  12996. y: coords.mt.y + cosHalfOffset
  12997. }
  12998. };
  12999.  
  13000. coords.mr.corner = {
  13001. tl: {
  13002. x: coords.mr.x - sinHalfOffset,
  13003. y: coords.mr.y - cosHalfOffset
  13004. },
  13005. tr: {
  13006. x: coords.mr.x + cosHalfOffset,
  13007. y: coords.mr.y - sinHalfOffset
  13008. },
  13009. bl: {
  13010. x: coords.mr.x - cosHalfOffset,
  13011. y: coords.mr.y + sinHalfOffset
  13012. },
  13013. br: {
  13014. x: coords.mr.x + sinHalfOffset,
  13015. y: coords.mr.y + cosHalfOffset
  13016. }
  13017. };
  13018.  
  13019. coords.mb.corner = {
  13020. tl: {
  13021. x: coords.mb.x - sinHalfOffset,
  13022. y: coords.mb.y - cosHalfOffset
  13023. },
  13024. tr: {
  13025. x: coords.mb.x + cosHalfOffset,
  13026. y: coords.mb.y - sinHalfOffset
  13027. },
  13028. bl: {
  13029. x: coords.mb.x - cosHalfOffset,
  13030. y: coords.mb.y + sinHalfOffset
  13031. },
  13032. br: {
  13033. x: coords.mb.x + sinHalfOffset,
  13034. y: coords.mb.y + cosHalfOffset
  13035. }
  13036. };
  13037.  
  13038. coords.mtr.corner = {
  13039. tl: {
  13040. x: coords.mtr.x - sinHalfOffset + (sinTh * this.rotatingPointOffset),
  13041. y: coords.mtr.y - cosHalfOffset - (cosTh * this.rotatingPointOffset)
  13042. },
  13043. tr: {
  13044. x: coords.mtr.x + cosHalfOffset + (sinTh * this.rotatingPointOffset),
  13045. y: coords.mtr.y - sinHalfOffset - (cosTh * this.rotatingPointOffset)
  13046. },
  13047. bl: {
  13048. x: coords.mtr.x - cosHalfOffset + (sinTh * this.rotatingPointOffset),
  13049. y: coords.mtr.y + sinHalfOffset - (cosTh * this.rotatingPointOffset)
  13050. },
  13051. br: {
  13052. x: coords.mtr.x + sinHalfOffset + (sinTh * this.rotatingPointOffset),
  13053. y: coords.mtr.y + cosHalfOffset - (cosTh * this.rotatingPointOffset)
  13054. }
  13055. };
  13056. },
  13057. /**
  13058. * Draws borders of an object's bounding box.
  13059. * Requires public properties: width, height
  13060. * Requires public options: padding, borderColor
  13061. * @param {CanvasRenderingContext2D} ctx Context to draw on
  13062. * @return {fabric.Object} thisArg
  13063. * @chainable
  13064. */
  13065. drawBorders: function(ctx) {
  13066. if (!this.hasBorders) {
  13067. return this;
  13068. }
  13069.  
  13070. var padding = this.padding,
  13071. padding2 = padding * 2,
  13072. vpt = this.getViewportTransform();
  13073.  
  13074. ctx.save();
  13075.  
  13076. ctx.globalAlpha = this.isMoving ? this.borderOpacityWhenMoving : 1;
  13077. ctx.strokeStyle = this.borderColor;
  13078.  
  13079. var scaleX = 1 / this._constrainScale(this.scaleX),
  13080. scaleY = 1 / this._constrainScale(this.scaleY);
  13081.  
  13082. ctx.lineWidth = 1 / this.borderScaleFactor;
  13083.  
  13084. var w = this.getWidth(),
  13085. h = this.getHeight(),
  13086. strokeWidth = this.strokeWidth > 1 ? this.strokeWidth : 0,
  13087. capped = this.strokeLineCap === 'round' || this.strokeLineCap === 'square',
  13088. vLine = this.type === 'line' && this.width === 1,
  13089. hLine = this.type === 'line' && this.height === 1,
  13090. strokeW = (capped && hLine) || this.type !== 'line',
  13091. strokeH = (capped && vLine) || this.type !== 'line';
  13092. if (vLine) {
  13093. w = strokeWidth / scaleX;
  13094. }
  13095. else if (hLine) {
  13096. h = strokeWidth / scaleY;
  13097. }
  13098. if (strokeW) {
  13099. w += strokeWidth / scaleX;
  13100. }
  13101. if (strokeH) {
  13102. h += strokeWidth / scaleY;
  13103. }
  13104. var wh = fabric.util.transformPoint(new fabric.Point(w, h), vpt, true),
  13105. width = wh.x,
  13106. height = wh.y;
  13107. if (this.group) {
  13108. width = width * this.group.scaleX;
  13109. height = height * this.group.scaleY;
  13110. }
  13111.  
  13112. ctx.strokeRect(
  13113. ~~(-(width / 2) - padding) - 0.5, // offset needed to make lines look sharper
  13114. ~~(-(height / 2) - padding) - 0.5,
  13115. ~~(width + padding2) + 1, // double offset needed to make lines look sharper
  13116. ~~(height + padding2) + 1
  13117. );
  13118.  
  13119. if (this.hasRotatingPoint && this.isControlVisible('mtr') && !this.get('lockRotation') && this.hasControls) {
  13120.  
  13121. var rotateHeight = ( -height - (padding * 2)) / 2;
  13122.  
  13123. ctx.beginPath();
  13124. ctx.moveTo(0, rotateHeight);
  13125. ctx.lineTo(0, rotateHeight - this.rotatingPointOffset);
  13126. ctx.closePath();
  13127. ctx.stroke();
  13128. }
  13129.  
  13130. ctx.restore();
  13131. return this;
  13132. },
  13133.  
  13134. /**
  13135. * Draws corners of an object's bounding box.
  13136. * Requires public properties: width, height
  13137. * Requires public options: cornerSize, padding
  13138. * @param {CanvasRenderingContext2D} ctx Context to draw on
  13139. * @return {fabric.Object} thisArg
  13140. * @chainable
  13141. */
  13142. drawControls: function(ctx) {
  13143. if (!this.hasControls) {
  13144. return this;
  13145. }
  13146.  
  13147. var size = this.cornerSize,
  13148. size2 = size / 2,
  13149. vpt = this.getViewportTransform(),
  13150. strokeWidth = this.strokeWidth > 1 ? this.strokeWidth : 0,
  13151. w = this.width,
  13152. h = this.height,
  13153. capped = this.strokeLineCap === 'round' || this.strokeLineCap === 'square',
  13154. vLine = this.type === 'line' && this.width === 1,
  13155. hLine = this.type === 'line' && this.height === 1,
  13156. strokeW = (capped && hLine) || this.type !== 'line',
  13157. strokeH = (capped && vLine) || this.type !== 'line';
  13158.  
  13159. if (vLine) {
  13160. w = strokeWidth;
  13161. }
  13162. else if (hLine) {
  13163. h = strokeWidth;
  13164. }
  13165. if (strokeW) {
  13166. w += strokeWidth;
  13167. }
  13168. if (strokeH) {
  13169. h += strokeWidth;
  13170. }
  13171. w *= this.scaleX;
  13172. h *= this.scaleY;
  13173.  
  13174. var wh = fabric.util.transformPoint(new fabric.Point(w, h), vpt, true),
  13175. width = wh.x,
  13176. height = wh.y,
  13177. left = -(width / 2),
  13178. top = -(height / 2),
  13179. padding = this.padding,
  13180. scaleOffset = size2,
  13181. scaleOffsetSize = size2 - size,
  13182. methodName = this.transparentCorners ? 'strokeRect' : 'fillRect';
  13183.  
  13184. ctx.save();
  13185.  
  13186. ctx.lineWidth = 1;
  13187.  
  13188. ctx.globalAlpha = this.isMoving ? this.borderOpacityWhenMoving : 1;
  13189. ctx.strokeStyle = ctx.fillStyle = this.cornerColor;
  13190.  
  13191. // top-left
  13192. this._drawControl('tl', ctx, methodName,
  13193. left - scaleOffset - padding,
  13194. top - scaleOffset - padding);
  13195.  
  13196. // top-right
  13197. this._drawControl('tr', ctx, methodName,
  13198. left + width - scaleOffset + padding,
  13199. top - scaleOffset - padding);
  13200.  
  13201. // bottom-left
  13202. this._drawControl('bl', ctx, methodName,
  13203. left - scaleOffset - padding,
  13204. top + height + scaleOffsetSize + padding);
  13205.  
  13206. // bottom-right
  13207. this._drawControl('br', ctx, methodName,
  13208. left + width + scaleOffsetSize + padding,
  13209. top + height + scaleOffsetSize + padding);
  13210.  
  13211. if (!this.get('lockUniScaling')) {
  13212.  
  13213. // middle-top
  13214. this._drawControl('mt', ctx, methodName,
  13215. left + width/2 - scaleOffset,
  13216. top - scaleOffset - padding);
  13217.  
  13218. // middle-bottom
  13219. this._drawControl('mb', ctx, methodName,
  13220. left + width/2 - scaleOffset,
  13221. top + height + scaleOffsetSize + padding);
  13222.  
  13223. // middle-right
  13224. this._drawControl('mr', ctx, methodName,
  13225. left + width + scaleOffsetSize + padding,
  13226. top + height/2 - scaleOffset);
  13227.  
  13228. // middle-left
  13229. this._drawControl('ml', ctx, methodName,
  13230. left - scaleOffset - padding,
  13231. top + height/2 - scaleOffset);
  13232. }
  13233.  
  13234. // middle-top-rotate
  13235. if (this.hasRotatingPoint) {
  13236. this._drawControl('mtr', ctx, methodName,
  13237. left + width/2 - scaleOffset,
  13238. top - this.rotatingPointOffset - this.cornerSize/2 - padding);
  13239. }
  13240.  
  13241. ctx.restore();
  13242.  
  13243. return this;
  13244. },
  13245.  
  13246. /**
  13247. * @private
  13248. */
  13249. _drawControl: function(control, ctx, methodName, left, top) {
  13250. var size = this.cornerSize;
  13251.  
  13252. if (this.isControlVisible(control)) {
  13253. isVML() || this.transparentCorners || ctx.clearRect(left, top, size, size);
  13254. ctx[methodName](left, top, size, size);
  13255. }
  13256. },
  13257.  
  13258. /**
  13259. * Returns true if the specified control is visible, false otherwise.
  13260. * @param {String} controlName The name of the control. Possible values are 'tl', 'tr', 'br', 'bl', 'ml', 'mt', 'mr', 'mb', 'mtr'.
  13261. * @returns {Boolean} true if the specified control is visible, false otherwise
  13262. */
  13263. isControlVisible: function(controlName) {
  13264. return this._getControlsVisibility()[controlName];
  13265. },
  13266.  
  13267. /**
  13268. * Sets the visibility of the specified control.
  13269. * @param {String} controlName The name of the control. Possible values are 'tl', 'tr', 'br', 'bl', 'ml', 'mt', 'mr', 'mb', 'mtr'.
  13270. * @param {Boolean} visible true to set the specified control visible, false otherwise
  13271. * @return {fabric.Object} thisArg
  13272. * @chainable
  13273. */
  13274. setControlVisible: function(controlName, visible) {
  13275. this._getControlsVisibility()[controlName] = visible;
  13276. return this;
  13277. },
  13278.  
  13279. /**
  13280. * Sets the visibility state of object controls.
  13281. * @param {Object} [options] Options object
  13282. * @param {Boolean} [options.bl] true to enable the bottom-left control, false to disable it
  13283. * @param {Boolean} [options.br] true to enable the bottom-right control, false to disable it
  13284. * @param {Boolean} [options.mb] true to enable the middle-bottom control, false to disable it
  13285. * @param {Boolean} [options.ml] true to enable the middle-left control, false to disable it
  13286. * @param {Boolean} [options.mr] true to enable the middle-right control, false to disable it
  13287. * @param {Boolean} [options.mt] true to enable the middle-top control, false to disable it
  13288. * @param {Boolean} [options.tl] true to enable the top-left control, false to disable it
  13289. * @param {Boolean} [options.tr] true to enable the top-right control, false to disable it
  13290. * @param {Boolean} [options.mtr] true to enable the middle-top-rotate control, false to disable it
  13291. * @return {fabric.Object} thisArg
  13292. * @chainable
  13293. */
  13294. setControlsVisibility: function(options) {
  13295. options || (options = { });
  13296.  
  13297. for (var p in options) {
  13298. this.setControlVisible(p, options[p]);
  13299. }
  13300. return this;
  13301. },
  13302.  
  13303. /**
  13304. * Returns the instance of the control visibility set for this object.
  13305. * @private
  13306. * @returns {Object}
  13307. */
  13308. _getControlsVisibility: function() {
  13309. if (!this._controlsVisibility) {
  13310. this._controlsVisibility = {
  13311. tl: true,
  13312. tr: true,
  13313. br: true,
  13314. bl: true,
  13315. ml: true,
  13316. mt: true,
  13317. mr: true,
  13318. mb: true,
  13319. mtr: true
  13320. };
  13321. }
  13322. return this._controlsVisibility;
  13323. }
  13324. });
  13325. })();
  13326.  
  13327.  
  13328. fabric.util.object.extend(fabric.StaticCanvas.prototype, /** @lends fabric.StaticCanvas.prototype */ {
  13329.  
  13330. /**
  13331. * Animation duration (in ms) for fx* methods
  13332. * @type Number
  13333. * @default
  13334. */
  13335. FX_DURATION: 500,
  13336.  
  13337. /**
  13338. * Centers object horizontally with animation.
  13339. * @param {fabric.Object} object Object to center
  13340. * @param {Object} [callbacks] Callbacks object with optional "onComplete" and/or "onChange" properties
  13341. * @param {Function} [callbacks.onComplete] Invoked on completion
  13342. * @param {Function} [callbacks.onChange] Invoked on every step of animation
  13343. * @return {fabric.Canvas} thisArg
  13344. * @chainable
  13345. */
  13346. fxCenterObjectH: function (object, callbacks) {
  13347. callbacks = callbacks || { };
  13348.  
  13349. var empty = function() { },
  13350. onComplete = callbacks.onComplete || empty,
  13351. onChange = callbacks.onChange || empty,
  13352. _this = this;
  13353.  
  13354. fabric.util.animate({
  13355. startValue: object.get('left'),
  13356. endValue: this.getCenter().left,
  13357. duration: this.FX_DURATION,
  13358. onChange: function(value) {
  13359. object.set('left', value);
  13360. _this.renderAll();
  13361. onChange();
  13362. },
  13363. onComplete: function() {
  13364. object.setCoords();
  13365. onComplete();
  13366. }
  13367. });
  13368.  
  13369. return this;
  13370. },
  13371.  
  13372. /**
  13373. * Centers object vertically with animation.
  13374. * @param {fabric.Object} object Object to center
  13375. * @param {Object} [callbacks] Callbacks object with optional "onComplete" and/or "onChange" properties
  13376. * @param {Function} [callbacks.onComplete] Invoked on completion
  13377. * @param {Function} [callbacks.onChange] Invoked on every step of animation
  13378. * @return {fabric.Canvas} thisArg
  13379. * @chainable
  13380. */
  13381. fxCenterObjectV: function (object, callbacks) {
  13382. callbacks = callbacks || { };
  13383.  
  13384. var empty = function() { },
  13385. onComplete = callbacks.onComplete || empty,
  13386. onChange = callbacks.onChange || empty,
  13387. _this = this;
  13388.  
  13389. fabric.util.animate({
  13390. startValue: object.get('top'),
  13391. endValue: this.getCenter().top,
  13392. duration: this.FX_DURATION,
  13393. onChange: function(value) {
  13394. object.set('top', value);
  13395. _this.renderAll();
  13396. onChange();
  13397. },
  13398. onComplete: function() {
  13399. object.setCoords();
  13400. onComplete();
  13401. }
  13402. });
  13403.  
  13404. return this;
  13405. },
  13406.  
  13407. /**
  13408. * Same as `fabric.Canvas#remove` but animated
  13409. * @param {fabric.Object} object Object to remove
  13410. * @param {Object} [callbacks] Callbacks object with optional "onComplete" and/or "onChange" properties
  13411. * @param {Function} [callbacks.onComplete] Invoked on completion
  13412. * @param {Function} [callbacks.onChange] Invoked on every step of animation
  13413. * @return {fabric.Canvas} thisArg
  13414. * @chainable
  13415. */
  13416. fxRemove: function (object, callbacks) {
  13417. callbacks = callbacks || { };
  13418.  
  13419. var empty = function() { },
  13420. onComplete = callbacks.onComplete || empty,
  13421. onChange = callbacks.onChange || empty,
  13422. _this = this;
  13423.  
  13424. fabric.util.animate({
  13425. startValue: object.get('opacity'),
  13426. endValue: 0,
  13427. duration: this.FX_DURATION,
  13428. onStart: function() {
  13429. object.set('active', false);
  13430. },
  13431. onChange: function(value) {
  13432. object.set('opacity', value);
  13433. _this.renderAll();
  13434. onChange();
  13435. },
  13436. onComplete: function () {
  13437. _this.remove(object);
  13438. onComplete();
  13439. }
  13440. });
  13441.  
  13442. return this;
  13443. }
  13444. });
  13445.  
  13446. fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {
  13447. /**
  13448. * Animates object's properties
  13449. * @param {String|Object} property Property to animate (if string) or properties to animate (if object)
  13450. * @param {Number|Object} value Value to animate property to (if string was given first) or options object
  13451. * @return {fabric.Object} thisArg
  13452. * @tutorial {@link http://fabricjs.com/fabric-intro-part-2/#animation}
  13453. * @chainable
  13454. *
  13455. * As object — multiple properties
  13456. *
  13457. * object.animate({ left: ..., top: ... });
  13458. * object.animate({ left: ..., top: ... }, { duration: ... });
  13459. *
  13460. * As string — one property
  13461. *
  13462. * object.animate('left', ...);
  13463. * object.animate('left', { duration: ... });
  13464. *
  13465. */
  13466. animate: function() {
  13467. if (arguments[0] && typeof arguments[0] === 'object') {
  13468. var propsToAnimate = [ ], prop, skipCallbacks;
  13469. for (prop in arguments[0]) {
  13470. propsToAnimate.push(prop);
  13471. }
  13472. for (var i = 0, len = propsToAnimate.length; i < len; i++) {
  13473. prop = propsToAnimate[i];
  13474. skipCallbacks = i !== len - 1;
  13475. this._animate(prop, arguments[0][prop], arguments[1], skipCallbacks);
  13476. }
  13477. }
  13478. else {
  13479. this._animate.apply(this, arguments);
  13480. }
  13481. return this;
  13482. },
  13483.  
  13484. /**
  13485. * @private
  13486. * @param {String} property Property to animate
  13487. * @param {String} to Value to animate to
  13488. * @param {Object} [options] Options object
  13489. * @param {Boolean} [skipCallbacks] When true, callbacks like onchange and oncomplete are not invoked
  13490. */
  13491. _animate: function(property, to, options, skipCallbacks) {
  13492. var _this = this, propPair;
  13493.  
  13494. to = to.toString();
  13495.  
  13496. if (!options) {
  13497. options = { };
  13498. }
  13499. else {
  13500. options = fabric.util.object.clone(options);
  13501. }
  13502.  
  13503. if (~property.indexOf('.')) {
  13504. propPair = property.split('.');
  13505. }
  13506.  
  13507. var currentValue = propPair
  13508. ? this.get(propPair[0])[propPair[1]]
  13509. : this.get(property);
  13510.  
  13511. if (!('from' in options)) {
  13512. options.from = currentValue;
  13513. }
  13514.  
  13515. if (~to.indexOf('=')) {
  13516. to = currentValue + parseFloat(to.replace('=', ''));
  13517. }
  13518. else {
  13519. to = parseFloat(to);
  13520. }
  13521.  
  13522. fabric.util.animate({
  13523. startValue: options.from,
  13524. endValue: to,
  13525. byValue: options.by,
  13526. easing: options.easing,
  13527. duration: options.duration,
  13528. abort: options.abort && function() {
  13529. return options.abort.call(_this);
  13530. },
  13531. onChange: function(value) {
  13532. if (propPair) {
  13533. _this[propPair[0]][propPair[1]] = value;
  13534. }
  13535. else {
  13536. _this.set(property, value);
  13537. }
  13538. if (skipCallbacks) {
  13539. return;
  13540. }
  13541. options.onChange && options.onChange();
  13542. },
  13543. onComplete: function() {
  13544. if (skipCallbacks) {
  13545. return;
  13546. }
  13547.  
  13548. _this.setCoords();
  13549. options.onComplete && options.onComplete();
  13550. }
  13551. });
  13552. }
  13553. });
  13554.  
  13555.  
  13556. (function(global) {
  13557.  
  13558. 'use strict';
  13559.  
  13560. var fabric = global.fabric || (global.fabric = { }),
  13561. extend = fabric.util.object.extend,
  13562. coordProps = { x1: 1, x2: 1, y1: 1, y2: 1 },
  13563. supportsLineDash = fabric.StaticCanvas.supports('setLineDash');
  13564.  
  13565. if (fabric.Line) {
  13566. fabric.warn('fabric.Line is already defined');
  13567. return;
  13568. }
  13569.  
  13570. /**
  13571. * Line class
  13572. * @class fabric.Line
  13573. * @extends fabric.Object
  13574. * @see {@link fabric.Line#initialize} for constructor definition
  13575. */
  13576. fabric.Line = fabric.util.createClass(fabric.Object, /** @lends fabric.Line.prototype */ {
  13577.  
  13578. /**
  13579. * Type of an object
  13580. * @type String
  13581. * @default
  13582. */
  13583. type: 'line',
  13584.  
  13585. /**
  13586. * x value or first line edge
  13587. * @type Number
  13588. * @default
  13589. */
  13590. x1: 0,
  13591.  
  13592. /**
  13593. * y value or first line edge
  13594. * @type Number
  13595. * @default
  13596. */
  13597. y1: 0,
  13598.  
  13599. /**
  13600. * x value or second line edge
  13601. * @type Number
  13602. * @default
  13603. */
  13604. x2: 0,
  13605.  
  13606. /**
  13607. * y value or second line edge
  13608. * @type Number
  13609. * @default
  13610. */
  13611. y2: 0,
  13612.  
  13613. /**
  13614. * Constructor
  13615. * @param {Array} [points] Array of points
  13616. * @param {Object} [options] Options object
  13617. * @return {fabric.Line} thisArg
  13618. */
  13619. initialize: function(points, options) {
  13620. options = options || { };
  13621.  
  13622. if (!points) {
  13623. points = [0, 0, 0, 0];
  13624. }
  13625.  
  13626. this.callSuper('initialize', options);
  13627.  
  13628. this.set('x1', points[0]);
  13629. this.set('y1', points[1]);
  13630. this.set('x2', points[2]);
  13631. this.set('y2', points[3]);
  13632.  
  13633. this._setWidthHeight(options);
  13634. },
  13635.  
  13636. /**
  13637. * @private
  13638. * @param {Object} [options] Options
  13639. */
  13640. _setWidthHeight: function(options) {
  13641. options || (options = { });
  13642.  
  13643. this.width = Math.abs(this.x2 - this.x1) || 1;
  13644. this.height = Math.abs(this.y2 - this.y1) || 1;
  13645.  
  13646. this.left = 'left' in options
  13647. ? options.left
  13648. : this._getLeftToOriginX();
  13649.  
  13650. this.top = 'top' in options
  13651. ? options.top
  13652. : this._getTopToOriginY();
  13653. },
  13654.  
  13655. /**
  13656. * @private
  13657. * @param {String} key
  13658. * @param {Any} value
  13659. */
  13660. _set: function(key, value) {
  13661. this.callSuper('_set', key, value);
  13662. if (typeof coordProps[key] !== 'undefined') {
  13663. this._setWidthHeight();
  13664. }
  13665. return this;
  13666. },
  13667.  
  13668. /**
  13669. * @private
  13670. * @return {Number} leftToOriginX Distance from left edge of canvas to originX of Line.
  13671. */
  13672. _getLeftToOriginX: makeEdgeToOriginGetter(
  13673. { // property names
  13674. origin: 'originX',
  13675. axis1: 'x1',
  13676. axis2: 'x2',
  13677. dimension: 'width'
  13678. },
  13679. { // possible values of origin
  13680. nearest: 'left',
  13681. center: 'center',
  13682. farthest: 'right'
  13683. }
  13684. ),
  13685.  
  13686. /**
  13687. * @private
  13688. * @return {Number} topToOriginY Distance from top edge of canvas to originY of Line.
  13689. */
  13690. _getTopToOriginY: makeEdgeToOriginGetter(
  13691. { // property names
  13692. origin: 'originY',
  13693. axis1: 'y1',
  13694. axis2: 'y2',
  13695. dimension: 'height'
  13696. },
  13697. { // possible values of origin
  13698. nearest: 'top',
  13699. center: 'center',
  13700. farthest: 'bottom'
  13701. }
  13702. ),
  13703.  
  13704. /**
  13705. * @private
  13706. * @param {CanvasRenderingContext2D} ctx Context to render on
  13707. */
  13708. _render: function(ctx, noTransform) {
  13709. ctx.beginPath();
  13710.  
  13711. if (noTransform) {
  13712. // Line coords are distances from left-top of canvas to origin of line.
  13713. //
  13714. // To render line in a path-group, we need to translate them to
  13715. // distances from center of path-group to center of line.
  13716. var cp = this.getCenterPoint();
  13717. ctx.translate(
  13718. cp.x,
  13719. cp.y
  13720. );
  13721. }
  13722.  
  13723. if (!this.strokeDashArray || this.strokeDashArray && supportsLineDash) {
  13724.  
  13725. // move from center (of virtual box) to its left/top corner
  13726. // we can't assume x1, y1 is top left and x2, y2 is bottom right
  13727. var xMult = this.x1 <= this.x2 ? -1 : 1,
  13728. yMult = this.y1 <= this.y2 ? -1 : 1;
  13729.  
  13730. ctx.moveTo(
  13731. this.width === 1 ? 0 : (xMult * this.width / 2),
  13732. this.height === 1 ? 0 : (yMult * this.height / 2));
  13733.  
  13734. ctx.lineTo(
  13735. this.width === 1 ? 0 : (xMult * -1 * this.width / 2),
  13736. this.height === 1 ? 0 : (yMult * -1 * this.height / 2));
  13737. }
  13738.  
  13739. ctx.lineWidth = this.strokeWidth;
  13740.  
  13741. // TODO: test this
  13742. // make sure setting "fill" changes color of a line
  13743. // (by copying fillStyle to strokeStyle, since line is stroked, not filled)
  13744. var origStrokeStyle = ctx.strokeStyle;
  13745. ctx.strokeStyle = this.stroke || ctx.fillStyle;
  13746. this.stroke && this._renderStroke(ctx);
  13747. ctx.strokeStyle = origStrokeStyle;
  13748. },
  13749.  
  13750. /**
  13751. * @private
  13752. * @param {CanvasRenderingContext2D} ctx Context to render on
  13753. */
  13754. _renderDashedStroke: function(ctx) {
  13755. var
  13756. xMult = this.x1 <= this.x2 ? -1 : 1,
  13757. yMult = this.y1 <= this.y2 ? -1 : 1,
  13758. x = this.width === 1 ? 0 : xMult * this.width / 2,
  13759. y = this.height === 1 ? 0 : yMult * this.height / 2;
  13760.  
  13761. ctx.beginPath();
  13762. fabric.util.drawDashedLine(ctx, x, y, -x, -y, this.strokeDashArray);
  13763. ctx.closePath();
  13764. },
  13765.  
  13766. /**
  13767. * Returns object representation of an instance
  13768. * @methd toObject
  13769. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  13770. * @return {Object} object representation of an instance
  13771. */
  13772. toObject: function(propertiesToInclude) {
  13773. return extend(this.callSuper('toObject', propertiesToInclude), this.calcLinePoints());
  13774. },
  13775.  
  13776. /**
  13777. * @private
  13778. * Recalculate line points from width and height.
  13779. */
  13780. calcLinePoints: function() {
  13781. var xMult = this.x1 <= this.x2 ? -1 : 1,
  13782. yMult = this.y1 <= this.y2 ? -1 : 1,
  13783. x1 = (xMult * this.width / 2),
  13784. y1 = (yMult * this.height / 2),
  13785. x2 = (xMult * -1 * this.width / 2),
  13786. y2 = (yMult * -1 * this.height / 2);
  13787.  
  13788. return {
  13789. x1: x1,
  13790. x2: x2,
  13791. y1: y1,
  13792. y2: y2
  13793. };
  13794. },
  13795.  
  13796. /* _TO_SVG_START_ */
  13797. /**
  13798. * Returns SVG representation of an instance
  13799. * @param {Function} [reviver] Method for further parsing of svg representation.
  13800. * @return {String} svg representation of an instance
  13801. */
  13802. toSVG: function(reviver) {
  13803. var markup = this._createBaseSVGMarkup(),
  13804. p = { x1: this.x1, x2: this.x2, y1: this.y1, y2: this.y2 };
  13805.  
  13806. if (!(this.group && this.group.type === 'path-group')) {
  13807. p = this.calcLinePoints();
  13808. }
  13809. markup.push(
  13810. '<line ',
  13811. 'x1="', p.x1,
  13812. '" y1="', p.y1,
  13813. '" x2="', p.x2,
  13814. '" y2="', p.y2,
  13815. '" style="', this.getSvgStyles(),
  13816. '" transform="', this.getSvgTransform(),
  13817. this.getSvgTransformMatrix(),
  13818. '"/>\n'
  13819. );
  13820.  
  13821. return reviver ? reviver(markup.join('')) : markup.join('');
  13822. },
  13823. /* _TO_SVG_END_ */
  13824.  
  13825. /**
  13826. * Returns complexity of an instance
  13827. * @return {Number} complexity
  13828. */
  13829. complexity: function() {
  13830. return 1;
  13831. }
  13832. });
  13833.  
  13834. /* _FROM_SVG_START_ */
  13835. /**
  13836. * List of attribute names to account for when parsing SVG element (used by {@link fabric.Line.fromElement})
  13837. * @static
  13838. * @memberOf fabric.Line
  13839. * @see http://www.w3.org/TR/SVG/shapes.html#LineElement
  13840. */
  13841. fabric.Line.ATTRIBUTE_NAMES = fabric.SHARED_ATTRIBUTES.concat('x1 y1 x2 y2'.split(' '));
  13842.  
  13843. /**
  13844. * Returns fabric.Line instance from an SVG element
  13845. * @static
  13846. * @memberOf fabric.Line
  13847. * @param {SVGElement} element Element to parse
  13848. * @param {Object} [options] Options object
  13849. * @return {fabric.Line} instance of fabric.Line
  13850. */
  13851. fabric.Line.fromElement = function(element, options) {
  13852. var parsedAttributes = fabric.parseAttributes(element, fabric.Line.ATTRIBUTE_NAMES),
  13853. points = [
  13854. parsedAttributes.x1 || 0,
  13855. parsedAttributes.y1 || 0,
  13856. parsedAttributes.x2 || 0,
  13857. parsedAttributes.y2 || 0
  13858. ];
  13859. return new fabric.Line(points, extend(parsedAttributes, options));
  13860. };
  13861. /* _FROM_SVG_END_ */
  13862.  
  13863. /**
  13864. * Returns fabric.Line instance from an object representation
  13865. * @static
  13866. * @memberOf fabric.Line
  13867. * @param {Object} object Object to create an instance from
  13868. * @return {fabric.Line} instance of fabric.Line
  13869. */
  13870. fabric.Line.fromObject = function(object) {
  13871. var points = [object.x1, object.y1, object.x2, object.y2];
  13872. return new fabric.Line(points, object);
  13873. };
  13874.  
  13875. /**
  13876. * Produces a function that calculates distance from canvas edge to Line origin.
  13877. */
  13878. function makeEdgeToOriginGetter(propertyNames, originValues) {
  13879. var origin = propertyNames.origin,
  13880. axis1 = propertyNames.axis1,
  13881. axis2 = propertyNames.axis2,
  13882. dimension = propertyNames.dimension,
  13883. nearest = originValues.nearest,
  13884. center = originValues.center,
  13885. farthest = originValues.farthest;
  13886.  
  13887. return function() {
  13888. switch (this.get(origin)) {
  13889. case nearest:
  13890. return Math.min(this.get(axis1), this.get(axis2));
  13891. case center:
  13892. return Math.min(this.get(axis1), this.get(axis2)) + (0.5 * this.get(dimension));
  13893. case farthest:
  13894. return Math.max(this.get(axis1), this.get(axis2));
  13895. }
  13896. };
  13897.  
  13898. }
  13899.  
  13900. })(typeof exports !== 'undefined' ? exports : this);
  13901.  
  13902.  
  13903. (function(global) {
  13904.  
  13905. 'use strict';
  13906.  
  13907. var fabric = global.fabric || (global.fabric = { }),
  13908. pi = Math.PI,
  13909. extend = fabric.util.object.extend;
  13910.  
  13911. if (fabric.Circle) {
  13912. fabric.warn('fabric.Circle is already defined.');
  13913. return;
  13914. }
  13915.  
  13916. /**
  13917. * Circle class
  13918. * @class fabric.Circle
  13919. * @extends fabric.Object
  13920. * @see {@link fabric.Circle#initialize} for constructor definition
  13921. */
  13922. fabric.Circle = fabric.util.createClass(fabric.Object, /** @lends fabric.Circle.prototype */ {
  13923.  
  13924. /**
  13925. * Type of an object
  13926. * @type String
  13927. * @default
  13928. */
  13929. type: 'circle',
  13930.  
  13931. /**
  13932. * Radius of this circle
  13933. * @type Number
  13934. * @default
  13935. */
  13936. radius: 0,
  13937.  
  13938. /**
  13939. * Start angle of the circle, moving clockwise
  13940. * @type Number
  13941. * @default 0
  13942. */
  13943. startAngle: 0,
  13944.  
  13945. /**
  13946. * End angle of the circle
  13947. * @type Number
  13948. * @default 2Pi
  13949. */
  13950. endAngle: pi * 2,
  13951.  
  13952. /**
  13953. * Constructor
  13954. * @param {Object} [options] Options object
  13955. * @return {fabric.Circle} thisArg
  13956. */
  13957. initialize: function(options) {
  13958. options = options || { };
  13959.  
  13960. this.callSuper('initialize', options);
  13961. this.set('radius', options.radius || 0);
  13962. this.startAngle = options.startAngle || this.startAngle;
  13963. this.endAngle = options.endAngle || this.endAngle;
  13964. },
  13965.  
  13966. /**
  13967. * @private
  13968. * @param {String} key
  13969. * @param {Any} value
  13970. * @return {fabric.Circle} thisArg
  13971. */
  13972. _set: function(key, value) {
  13973. this.callSuper('_set', key, value);
  13974.  
  13975. if (key === 'radius') {
  13976. this.setRadius(value);
  13977. }
  13978.  
  13979. return this;
  13980. },
  13981.  
  13982. /**
  13983. * Returns object representation of an instance
  13984. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  13985. * @return {Object} object representation of an instance
  13986. */
  13987. toObject: function(propertiesToInclude) {
  13988. return extend(this.callSuper('toObject', propertiesToInclude), {
  13989. radius: this.get('radius'),
  13990. startAngle: this.startAngle,
  13991. endAngle: this.endAngle
  13992. });
  13993. },
  13994.  
  13995. /* _TO_SVG_START_ */
  13996. /**
  13997. * Returns svg representation of an instance
  13998. * @param {Function} [reviver] Method for further parsing of svg representation.
  13999. * @return {String} svg representation of an instance
  14000. */
  14001. toSVG: function(reviver) {
  14002. var markup = this._createBaseSVGMarkup(), x = 0, y = 0,
  14003. angle = (this.endAngle - this.startAngle) % ( 2 * pi);
  14004.  
  14005. if (angle === 0) {
  14006. if (this.group && this.group.type === 'path-group') {
  14007. x = this.left + this.radius;
  14008. y = this.top + this.radius;
  14009. }
  14010. markup.push(
  14011. '<circle ',
  14012. 'cx="' + x + '" cy="' + y + '" ',
  14013. 'r="', this.radius,
  14014. '" style="', this.getSvgStyles(),
  14015. '" transform="', this.getSvgTransform(),
  14016. ' ', this.getSvgTransformMatrix(),
  14017. '"/>\n'
  14018. );
  14019. }
  14020. else {
  14021. var startX = Math.cos(this.startAngle) * this.radius,
  14022. startY = Math.sin(this.startAngle) * this.radius,
  14023. endX = Math.cos(this.endAngle) * this.radius,
  14024. endY = Math.sin(this.endAngle) * this.radius,
  14025. largeFlag = angle > pi ? '1' : '0';
  14026.  
  14027. markup.push(
  14028. '<path d="M ' + startX + ' ' + startY,
  14029. ' A ' + this.radius + ' ' + this.radius,
  14030. ' 0 ', + largeFlag + ' 1', ' ' + endX + ' ' + endY,
  14031. '" style="', this.getSvgStyles(),
  14032. '" transform="', this.getSvgTransform(),
  14033. ' ', this.getSvgTransformMatrix(),
  14034. '"/>\n'
  14035. );
  14036. }
  14037.  
  14038. return reviver ? reviver(markup.join('')) : markup.join('');
  14039. },
  14040. /* _TO_SVG_END_ */
  14041.  
  14042. /**
  14043. * @private
  14044. * @param {CanvasRenderingContext2D} ctx context to render on
  14045. * @param {Boolean} [noTransform] When true, context is not transformed
  14046. */
  14047. _render: function(ctx, noTransform) {
  14048. ctx.beginPath();
  14049. ctx.arc(noTransform ? this.left + this.radius : 0,
  14050. noTransform ? this.top + this.radius : 0,
  14051. this.radius,
  14052. this.startAngle,
  14053. this.endAngle, false);
  14054. this._renderFill(ctx);
  14055. this._renderStroke(ctx);
  14056. },
  14057.  
  14058. /**
  14059. * Returns horizontal radius of an object (according to how an object is scaled)
  14060. * @return {Number}
  14061. */
  14062. getRadiusX: function() {
  14063. return this.get('radius') * this.get('scaleX');
  14064. },
  14065.  
  14066. /**
  14067. * Returns vertical radius of an object (according to how an object is scaled)
  14068. * @return {Number}
  14069. */
  14070. getRadiusY: function() {
  14071. return this.get('radius') * this.get('scaleY');
  14072. },
  14073.  
  14074. /**
  14075. * Sets radius of an object (and updates width accordingly)
  14076. * @return {Number}
  14077. */
  14078. setRadius: function(value) {
  14079. this.radius = value;
  14080. this.set('width', value * 2).set('height', value * 2);
  14081. },
  14082.  
  14083. /**
  14084. * Returns complexity of an instance
  14085. * @return {Number} complexity of this instance
  14086. */
  14087. complexity: function() {
  14088. return 1;
  14089. }
  14090. });
  14091.  
  14092. /* _FROM_SVG_START_ */
  14093. /**
  14094. * List of attribute names to account for when parsing SVG element (used by {@link fabric.Circle.fromElement})
  14095. * @static
  14096. * @memberOf fabric.Circle
  14097. * @see: http://www.w3.org/TR/SVG/shapes.html#CircleElement
  14098. */
  14099. fabric.Circle.ATTRIBUTE_NAMES = fabric.SHARED_ATTRIBUTES.concat('cx cy r'.split(' '));
  14100.  
  14101. /**
  14102. * Returns {@link fabric.Circle} instance from an SVG element
  14103. * @static
  14104. * @memberOf fabric.Circle
  14105. * @param {SVGElement} element Element to parse
  14106. * @param {Object} [options] Options object
  14107. * @throws {Error} If value of `r` attribute is missing or invalid
  14108. * @return {fabric.Circle} Instance of fabric.Circle
  14109. */
  14110. fabric.Circle.fromElement = function(element, options) {
  14111. options || (options = { });
  14112.  
  14113. var parsedAttributes = fabric.parseAttributes(element, fabric.Circle.ATTRIBUTE_NAMES);
  14114.  
  14115. if (!isValidRadius(parsedAttributes)) {
  14116. throw new Error('value of `r` attribute is required and can not be negative');
  14117. }
  14118.  
  14119. parsedAttributes.left = parsedAttributes.left || 0;
  14120. parsedAttributes.top = parsedAttributes.top || 0;
  14121.  
  14122. var obj = new fabric.Circle(extend(parsedAttributes, options));
  14123.  
  14124. obj.left -= obj.radius;
  14125. obj.top -= obj.radius;
  14126. return obj;
  14127. };
  14128.  
  14129. /**
  14130. * @private
  14131. */
  14132. function isValidRadius(attributes) {
  14133. return (('radius' in attributes) && (attributes.radius > 0));
  14134. }
  14135. /* _FROM_SVG_END_ */
  14136.  
  14137. /**
  14138. * Returns {@link fabric.Circle} instance from an object representation
  14139. * @static
  14140. * @memberOf fabric.Circle
  14141. * @param {Object} object Object to create an instance from
  14142. * @return {Object} Instance of fabric.Circle
  14143. */
  14144. fabric.Circle.fromObject = function(object) {
  14145. return new fabric.Circle(object);
  14146. };
  14147.  
  14148. })(typeof exports !== 'undefined' ? exports : this);
  14149.  
  14150.  
  14151. (function(global) {
  14152.  
  14153. 'use strict';
  14154.  
  14155. var fabric = global.fabric || (global.fabric = { });
  14156.  
  14157. if (fabric.Triangle) {
  14158. fabric.warn('fabric.Triangle is already defined');
  14159. return;
  14160. }
  14161.  
  14162. /**
  14163. * Triangle class
  14164. * @class fabric.Triangle
  14165. * @extends fabric.Object
  14166. * @return {fabric.Triangle} thisArg
  14167. * @see {@link fabric.Triangle#initialize} for constructor definition
  14168. */
  14169. fabric.Triangle = fabric.util.createClass(fabric.Object, /** @lends fabric.Triangle.prototype */ {
  14170.  
  14171. /**
  14172. * Type of an object
  14173. * @type String
  14174. * @default
  14175. */
  14176. type: 'triangle',
  14177.  
  14178. /**
  14179. * Constructor
  14180. * @param {Object} [options] Options object
  14181. * @return {Object} thisArg
  14182. */
  14183. initialize: function(options) {
  14184. options = options || { };
  14185.  
  14186. this.callSuper('initialize', options);
  14187.  
  14188. this.set('width', options.width || 100)
  14189. .set('height', options.height || 100);
  14190. },
  14191.  
  14192. /**
  14193. * @private
  14194. * @param {CanvasRenderingContext2D} ctx Context to render on
  14195. */
  14196. _render: function(ctx) {
  14197. var widthBy2 = this.width / 2,
  14198. heightBy2 = this.height / 2;
  14199.  
  14200. ctx.beginPath();
  14201. ctx.moveTo(-widthBy2, heightBy2);
  14202. ctx.lineTo(0, -heightBy2);
  14203. ctx.lineTo(widthBy2, heightBy2);
  14204. ctx.closePath();
  14205.  
  14206. this._renderFill(ctx);
  14207. this._renderStroke(ctx);
  14208. },
  14209.  
  14210. /**
  14211. * @private
  14212. * @param {CanvasRenderingContext2D} ctx Context to render on
  14213. */
  14214. _renderDashedStroke: function(ctx) {
  14215. var widthBy2 = this.width / 2,
  14216. heightBy2 = this.height / 2;
  14217.  
  14218. ctx.beginPath();
  14219. fabric.util.drawDashedLine(ctx, -widthBy2, heightBy2, 0, -heightBy2, this.strokeDashArray);
  14220. fabric.util.drawDashedLine(ctx, 0, -heightBy2, widthBy2, heightBy2, this.strokeDashArray);
  14221. fabric.util.drawDashedLine(ctx, widthBy2, heightBy2, -widthBy2, heightBy2, this.strokeDashArray);
  14222. ctx.closePath();
  14223. },
  14224.  
  14225. /* _TO_SVG_START_ */
  14226. /**
  14227. * Returns SVG representation of an instance
  14228. * @param {Function} [reviver] Method for further parsing of svg representation.
  14229. * @return {String} svg representation of an instance
  14230. */
  14231. toSVG: function(reviver) {
  14232. var markup = this._createBaseSVGMarkup(),
  14233. widthBy2 = this.width / 2,
  14234. heightBy2 = this.height / 2,
  14235. points = [
  14236. -widthBy2 + ' ' + heightBy2,
  14237. '0 ' + -heightBy2,
  14238. widthBy2 + ' ' + heightBy2
  14239. ]
  14240. .join(',');
  14241.  
  14242. markup.push(
  14243. '<polygon ',
  14244. 'points="', points,
  14245. '" style="', this.getSvgStyles(),
  14246. '" transform="', this.getSvgTransform(),
  14247. '"/>'
  14248. );
  14249.  
  14250. return reviver ? reviver(markup.join('')) : markup.join('');
  14251. },
  14252. /* _TO_SVG_END_ */
  14253.  
  14254. /**
  14255. * Returns complexity of an instance
  14256. * @return {Number} complexity of this instance
  14257. */
  14258. complexity: function() {
  14259. return 1;
  14260. }
  14261. });
  14262.  
  14263. /**
  14264. * Returns fabric.Triangle instance from an object representation
  14265. * @static
  14266. * @memberOf fabric.Triangle
  14267. * @param {Object} object Object to create an instance from
  14268. * @return {Object} instance of Canvas.Triangle
  14269. */
  14270. fabric.Triangle.fromObject = function(object) {
  14271. return new fabric.Triangle(object);
  14272. };
  14273.  
  14274. })(typeof exports !== 'undefined' ? exports : this);
  14275.  
  14276.  
  14277. (function(global) {
  14278.  
  14279. 'use strict';
  14280.  
  14281. var fabric = global.fabric || (global.fabric = { }),
  14282. piBy2 = Math.PI * 2,
  14283. extend = fabric.util.object.extend;
  14284.  
  14285. if (fabric.Ellipse) {
  14286. fabric.warn('fabric.Ellipse is already defined.');
  14287. return;
  14288. }
  14289.  
  14290. /**
  14291. * Ellipse class
  14292. * @class fabric.Ellipse
  14293. * @extends fabric.Object
  14294. * @return {fabric.Ellipse} thisArg
  14295. * @see {@link fabric.Ellipse#initialize} for constructor definition
  14296. */
  14297. fabric.Ellipse = fabric.util.createClass(fabric.Object, /** @lends fabric.Ellipse.prototype */ {
  14298.  
  14299. /**
  14300. * Type of an object
  14301. * @type String
  14302. * @default
  14303. */
  14304. type: 'ellipse',
  14305.  
  14306. /**
  14307. * Horizontal radius
  14308. * @type Number
  14309. * @default
  14310. */
  14311. rx: 0,
  14312.  
  14313. /**
  14314. * Vertical radius
  14315. * @type Number
  14316. * @default
  14317. */
  14318. ry: 0,
  14319.  
  14320. /**
  14321. * Constructor
  14322. * @param {Object} [options] Options object
  14323. * @return {fabric.Ellipse} thisArg
  14324. */
  14325. initialize: function(options) {
  14326. options = options || { };
  14327.  
  14328. this.callSuper('initialize', options);
  14329.  
  14330. this.set('rx', options.rx || 0);
  14331. this.set('ry', options.ry || 0);
  14332. },
  14333.  
  14334. /**
  14335. * @private
  14336. * @param {String} key
  14337. * @param {Any} value
  14338. * @return {fabric.Ellipse} thisArg
  14339. */
  14340. _set: function(key, value) {
  14341. this.callSuper('_set', key, value);
  14342. switch (key) {
  14343.  
  14344. case 'rx':
  14345. this.rx = value;
  14346. this.set('width', value * 2);
  14347. break;
  14348.  
  14349. case 'ry':
  14350. this.ry = value;
  14351. this.set('height', value * 2);
  14352. break;
  14353.  
  14354. }
  14355. return this;
  14356. },
  14357.  
  14358. /**
  14359. * Returns horizontal radius of an object (according to how an object is scaled)
  14360. * @return {Number}
  14361. */
  14362. getRx: function() {
  14363. return this.get('rx') * this.get('scaleX');
  14364. },
  14365.  
  14366. /**
  14367. * Returns Vertical radius of an object (according to how an object is scaled)
  14368. * @return {Number}
  14369. */
  14370. getRy: function() {
  14371. return this.get('ry') * this.get('scaleY');
  14372. },
  14373.  
  14374. /**
  14375. * Returns object representation of an instance
  14376. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  14377. * @return {Object} object representation of an instance
  14378. */
  14379. toObject: function(propertiesToInclude) {
  14380. return extend(this.callSuper('toObject', propertiesToInclude), {
  14381. rx: this.get('rx'),
  14382. ry: this.get('ry')
  14383. });
  14384. },
  14385.  
  14386. /* _TO_SVG_START_ */
  14387. /**
  14388. * Returns svg representation of an instance
  14389. * @param {Function} [reviver] Method for further parsing of svg representation.
  14390. * @return {String} svg representation of an instance
  14391. */
  14392. toSVG: function(reviver) {
  14393. var markup = this._createBaseSVGMarkup(), x = 0, y = 0;
  14394. if (this.group && this.group.type === 'path-group') {
  14395. x = this.left + this.rx;
  14396. y = this.top + this.ry;
  14397. }
  14398. markup.push(
  14399. '<ellipse ',
  14400. 'cx="', x, '" cy="', y, '" ',
  14401. 'rx="', this.rx,
  14402. '" ry="', this.ry,
  14403. '" style="', this.getSvgStyles(),
  14404. '" transform="', this.getSvgTransform(),
  14405. this.getSvgTransformMatrix(),
  14406. '"/>\n'
  14407. );
  14408.  
  14409. return reviver ? reviver(markup.join('')) : markup.join('');
  14410. },
  14411. /* _TO_SVG_END_ */
  14412.  
  14413. /**
  14414. * @private
  14415. * @param {CanvasRenderingContext2D} ctx context to render on
  14416. * @param {Boolean} [noTransform] When true, context is not transformed
  14417. */
  14418. _render: function(ctx, noTransform) {
  14419. ctx.beginPath();
  14420. ctx.save();
  14421. ctx.transform(1, 0, 0, this.ry/this.rx, 0, 0);
  14422. ctx.arc(
  14423. noTransform ? this.left + this.rx : 0,
  14424. noTransform ? (this.top + this.ry) * this.rx/this.ry : 0,
  14425. this.rx,
  14426. 0,
  14427. piBy2,
  14428. false);
  14429. ctx.restore();
  14430. this._renderFill(ctx);
  14431. this._renderStroke(ctx);
  14432. },
  14433.  
  14434. /**
  14435. * Returns complexity of an instance
  14436. * @return {Number} complexity
  14437. */
  14438. complexity: function() {
  14439. return 1;
  14440. }
  14441. });
  14442.  
  14443. /* _FROM_SVG_START_ */
  14444. /**
  14445. * List of attribute names to account for when parsing SVG element (used by {@link fabric.Ellipse.fromElement})
  14446. * @static
  14447. * @memberOf fabric.Ellipse
  14448. * @see http://www.w3.org/TR/SVG/shapes.html#EllipseElement
  14449. */
  14450. fabric.Ellipse.ATTRIBUTE_NAMES = fabric.SHARED_ATTRIBUTES.concat('cx cy rx ry'.split(' '));
  14451.  
  14452. /**
  14453. * Returns {@link fabric.Ellipse} instance from an SVG element
  14454. * @static
  14455. * @memberOf fabric.Ellipse
  14456. * @param {SVGElement} element Element to parse
  14457. * @param {Object} [options] Options object
  14458. * @return {fabric.Ellipse}
  14459. */
  14460. fabric.Ellipse.fromElement = function(element, options) {
  14461. options || (options = { });
  14462.  
  14463. var parsedAttributes = fabric.parseAttributes(element, fabric.Ellipse.ATTRIBUTE_NAMES);
  14464.  
  14465. parsedAttributes.left = parsedAttributes.left || 0;
  14466. parsedAttributes.top = parsedAttributes.top || 0;
  14467.  
  14468. var ellipse = new fabric.Ellipse(extend(parsedAttributes, options));
  14469.  
  14470. ellipse.top -= ellipse.ry;
  14471. ellipse.left -= ellipse.rx;
  14472. return ellipse;
  14473. };
  14474. /* _FROM_SVG_END_ */
  14475.  
  14476. /**
  14477. * Returns {@link fabric.Ellipse} instance from an object representation
  14478. * @static
  14479. * @memberOf fabric.Ellipse
  14480. * @param {Object} object Object to create an instance from
  14481. * @return {fabric.Ellipse}
  14482. */
  14483. fabric.Ellipse.fromObject = function(object) {
  14484. return new fabric.Ellipse(object);
  14485. };
  14486.  
  14487. })(typeof exports !== 'undefined' ? exports : this);
  14488.  
  14489.  
  14490. (function(global) {
  14491.  
  14492. 'use strict';
  14493.  
  14494. var fabric = global.fabric || (global.fabric = { }),
  14495. extend = fabric.util.object.extend;
  14496.  
  14497. if (fabric.Rect) {
  14498. console.warn('fabric.Rect is already defined');
  14499. return;
  14500. }
  14501.  
  14502. var stateProperties = fabric.Object.prototype.stateProperties.concat();
  14503. stateProperties.push('rx', 'ry', 'x', 'y');
  14504.  
  14505. /**
  14506. * Rectangle class
  14507. * @class fabric.Rect
  14508. * @extends fabric.Object
  14509. * @return {fabric.Rect} thisArg
  14510. * @see {@link fabric.Rect#initialize} for constructor definition
  14511. */
  14512. fabric.Rect = fabric.util.createClass(fabric.Object, /** @lends fabric.Rect.prototype */ {
  14513.  
  14514. /**
  14515. * List of properties to consider when checking if state of an object is changed ({@link fabric.Object#hasStateChanged})
  14516. * as well as for history (undo/redo) purposes
  14517. * @type Array
  14518. */
  14519. stateProperties: stateProperties,
  14520.  
  14521. /**
  14522. * Type of an object
  14523. * @type String
  14524. * @default
  14525. */
  14526. type: 'rect',
  14527.  
  14528. /**
  14529. * Horizontal border radius
  14530. * @type Number
  14531. * @default
  14532. */
  14533. rx: 0,
  14534.  
  14535. /**
  14536. * Vertical border radius
  14537. * @type Number
  14538. * @default
  14539. */
  14540. ry: 0,
  14541.  
  14542. /**
  14543. * Used to specify dash pattern for stroke on this object
  14544. * @type Array
  14545. */
  14546. strokeDashArray: null,
  14547.  
  14548. /**
  14549. * Constructor
  14550. * @param {Object} [options] Options object
  14551. * @return {Object} thisArg
  14552. */
  14553. initialize: function(options) {
  14554. options = options || { };
  14555.  
  14556. this.callSuper('initialize', options);
  14557. this._initRxRy();
  14558.  
  14559. },
  14560.  
  14561. /**
  14562. * Initializes rx/ry attributes
  14563. * @private
  14564. */
  14565. _initRxRy: function() {
  14566. if (this.rx && !this.ry) {
  14567. this.ry = this.rx;
  14568. }
  14569. else if (this.ry && !this.rx) {
  14570. this.rx = this.ry;
  14571. }
  14572. },
  14573.  
  14574. /**
  14575. * @private
  14576. * @param {CanvasRenderingContext2D} ctx Context to render on
  14577. */
  14578. _render: function(ctx, noTransform) {
  14579.  
  14580. // optimize 1x1 case (used in spray brush)
  14581. if (this.width === 1 && this.height === 1) {
  14582. ctx.fillRect(0, 0, 1, 1);
  14583. return;
  14584. }
  14585.  
  14586. var rx = this.rx ? Math.min(this.rx, this.width / 2) : 0,
  14587. ry = this.ry ? Math.min(this.ry, this.height / 2) : 0,
  14588. w = this.width,
  14589. h = this.height,
  14590. x = noTransform ? this.left : -this.width / 2,
  14591. y = noTransform ? this.top : -this.height / 2,
  14592. isRounded = rx !== 0 || ry !== 0,
  14593. k = 1 - 0.5522847498 /* "magic number" for bezier approximations of arcs (http://itc.ktu.lt/itc354/Riskus354.pdf) */;
  14594.  
  14595. ctx.beginPath();
  14596.  
  14597. ctx.moveTo(x + rx, y);
  14598.  
  14599. ctx.lineTo(x + w - rx, y);
  14600. isRounded && ctx.bezierCurveTo(x + w - k * rx, y, x + w, y + k * ry, x + w, y + ry);
  14601.  
  14602. ctx.lineTo(x + w, y + h - ry);
  14603. isRounded && ctx.bezierCurveTo(x + w, y + h - k * ry, x + w - k * rx, y + h, x + w - rx, y + h);
  14604.  
  14605. ctx.lineTo(x + rx, y + h);
  14606. isRounded && ctx.bezierCurveTo(x + k * rx, y + h, x, y + h - k * ry, x, y + h - ry);
  14607.  
  14608. ctx.lineTo(x, y + ry);
  14609. isRounded && ctx.bezierCurveTo(x, y + k * ry, x + k * rx, y, x + rx, y);
  14610.  
  14611. ctx.closePath();
  14612.  
  14613. this._renderFill(ctx);
  14614. this._renderStroke(ctx);
  14615. },
  14616.  
  14617. /**
  14618. * @private
  14619. * @param {CanvasRenderingContext2D} ctx Context to render on
  14620. */
  14621. _renderDashedStroke: function(ctx) {
  14622. var x = -this.width / 2,
  14623. y = -this.height / 2,
  14624. w = this.width,
  14625. h = this.height;
  14626.  
  14627. ctx.beginPath();
  14628. fabric.util.drawDashedLine(ctx, x, y, x + w, y, this.strokeDashArray);
  14629. fabric.util.drawDashedLine(ctx, x + w, y, x + w, y + h, this.strokeDashArray);
  14630. fabric.util.drawDashedLine(ctx, x + w, y + h, x, y + h, this.strokeDashArray);
  14631. fabric.util.drawDashedLine(ctx, x, y + h, x, y, this.strokeDashArray);
  14632. ctx.closePath();
  14633. },
  14634.  
  14635. /**
  14636. * Returns object representation of an instance
  14637. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  14638. * @return {Object} object representation of an instance
  14639. */
  14640. toObject: function(propertiesToInclude) {
  14641. var object = extend(this.callSuper('toObject', propertiesToInclude), {
  14642. rx: this.get('rx') || 0,
  14643. ry: this.get('ry') || 0
  14644. });
  14645. if (!this.includeDefaultValues) {
  14646. this._removeDefaultValues(object);
  14647. }
  14648. return object;
  14649. },
  14650.  
  14651. /* _TO_SVG_START_ */
  14652. /**
  14653. * Returns svg representation of an instance
  14654. * @param {Function} [reviver] Method for further parsing of svg representation.
  14655. * @return {String} svg representation of an instance
  14656. */
  14657. toSVG: function(reviver) {
  14658. var markup = this._createBaseSVGMarkup(), x = this.left, y = this.top;
  14659. if (!(this.group && this.group.type === 'path-group')) {
  14660. x = -this.width / 2;
  14661. y = -this.height / 2;
  14662. }
  14663. markup.push(
  14664. '<rect ',
  14665. 'x="', x, '" y="', y,
  14666. '" rx="', this.get('rx'), '" ry="', this.get('ry'),
  14667. '" width="', this.width, '" height="', this.height,
  14668. '" style="', this.getSvgStyles(),
  14669. '" transform="', this.getSvgTransform(),
  14670. this.getSvgTransformMatrix(),
  14671. '"/>\n');
  14672.  
  14673. return reviver ? reviver(markup.join('')) : markup.join('');
  14674. },
  14675. /* _TO_SVG_END_ */
  14676.  
  14677. /**
  14678. * Returns complexity of an instance
  14679. * @return {Number} complexity
  14680. */
  14681. complexity: function() {
  14682. return 1;
  14683. }
  14684. });
  14685.  
  14686. /* _FROM_SVG_START_ */
  14687. /**
  14688. * List of attribute names to account for when parsing SVG element (used by `fabric.Rect.fromElement`)
  14689. * @static
  14690. * @memberOf fabric.Rect
  14691. * @see: http://www.w3.org/TR/SVG/shapes.html#RectElement
  14692. */
  14693. fabric.Rect.ATTRIBUTE_NAMES = fabric.SHARED_ATTRIBUTES.concat('x y rx ry width height'.split(' '));
  14694.  
  14695. /**
  14696. * Returns {@link fabric.Rect} instance from an SVG element
  14697. * @static
  14698. * @memberOf fabric.Rect
  14699. * @param {SVGElement} element Element to parse
  14700. * @param {Object} [options] Options object
  14701. * @return {fabric.Rect} Instance of fabric.Rect
  14702. */
  14703. fabric.Rect.fromElement = function(element, options) {
  14704. if (!element) {
  14705. return null;
  14706. }
  14707. options = options || { };
  14708.  
  14709. var parsedAttributes = fabric.parseAttributes(element, fabric.Rect.ATTRIBUTE_NAMES);
  14710.  
  14711. parsedAttributes.left = parsedAttributes.left || 0;
  14712. parsedAttributes.top = parsedAttributes.top || 0;
  14713.  
  14714. return new fabric.Rect(extend((options ? fabric.util.object.clone(options) : { }), parsedAttributes));
  14715. };
  14716. /* _FROM_SVG_END_ */
  14717.  
  14718. /**
  14719. * Returns {@link fabric.Rect} instance from an object representation
  14720. * @static
  14721. * @memberOf fabric.Rect
  14722. * @param {Object} object Object to create an instance from
  14723. * @return {Object} instance of fabric.Rect
  14724. */
  14725. fabric.Rect.fromObject = function(object) {
  14726. return new fabric.Rect(object);
  14727. };
  14728.  
  14729. })(typeof exports !== 'undefined' ? exports : this);
  14730.  
  14731.  
  14732. (function(global) {
  14733.  
  14734. 'use strict';
  14735.  
  14736. var fabric = global.fabric || (global.fabric = { });
  14737.  
  14738. if (fabric.Polyline) {
  14739. fabric.warn('fabric.Polyline is already defined');
  14740. return;
  14741. }
  14742.  
  14743. /**
  14744. * Polyline class
  14745. * @class fabric.Polyline
  14746. * @extends fabric.Object
  14747. * @see {@link fabric.Polyline#initialize} for constructor definition
  14748. */
  14749. fabric.Polyline = fabric.util.createClass(fabric.Object, /** @lends fabric.Polyline.prototype */ {
  14750.  
  14751. /**
  14752. * Type of an object
  14753. * @type String
  14754. * @default
  14755. */
  14756. type: 'polyline',
  14757.  
  14758. /**
  14759. * Points array
  14760. * @type Array
  14761. * @default
  14762. */
  14763. points: null,
  14764.  
  14765. /**
  14766. * Minimum X from points values, necessary to offset points
  14767. * @type Number
  14768. * @default
  14769. */
  14770. minX: 0,
  14771.  
  14772. /**
  14773. * Minimum Y from points values, necessary to offset points
  14774. * @type Number
  14775. * @default
  14776. */
  14777. minY: 0,
  14778.  
  14779. /**
  14780. * Constructor
  14781. * @param {Array} points Array of points (where each point is an object with x and y)
  14782. * @param {Object} [options] Options object
  14783. * @param {Boolean} [skipOffset] Whether points offsetting should be skipped
  14784. * @return {fabric.Polyline} thisArg
  14785. * @example
  14786. * var poly = new fabric.Polyline([
  14787. * { x: 10, y: 10 },
  14788. * { x: 50, y: 30 },
  14789. * { x: 40, y: 70 },
  14790. * { x: 60, y: 50 },
  14791. * { x: 100, y: 150 },
  14792. * { x: 40, y: 100 }
  14793. * ], {
  14794. * stroke: 'red',
  14795. * left: 100,
  14796. * top: 100
  14797. * });
  14798. */
  14799. initialize: function(points, options) {
  14800. return fabric.Polygon.prototype.initialize.call(this, points, options);
  14801. },
  14802.  
  14803. /**
  14804. * @private
  14805. */
  14806. _calcDimensions: function() {
  14807. return fabric.Polygon.prototype._calcDimensions.call(this);
  14808. },
  14809.  
  14810. /**
  14811. * @private
  14812. */
  14813. _applyPointOffset: function() {
  14814. return fabric.Polygon.prototype._applyPointOffset.call(this);
  14815. },
  14816.  
  14817. /**
  14818. * Returns object representation of an instance
  14819. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  14820. * @return {Object} Object representation of an instance
  14821. */
  14822. toObject: function(propertiesToInclude) {
  14823. return fabric.Polygon.prototype.toObject.call(this, propertiesToInclude);
  14824. },
  14825.  
  14826. /* _TO_SVG_START_ */
  14827. /**
  14828. * Returns SVG representation of an instance
  14829. * @param {Function} [reviver] Method for further parsing of svg representation.
  14830. * @return {String} svg representation of an instance
  14831. */
  14832. toSVG: function(reviver) {
  14833. return fabric.Polygon.prototype.toSVG.call(this, reviver);
  14834. },
  14835. /* _TO_SVG_END_ */
  14836.  
  14837. /**
  14838. * @private
  14839. * @param {CanvasRenderingContext2D} ctx Context to render on
  14840. */
  14841. _render: function(ctx) {
  14842. fabric.Polygon.prototype.commonRender.call(this, ctx);
  14843. this._renderFill(ctx);
  14844. this._renderStroke(ctx);
  14845. },
  14846.  
  14847. /**
  14848. * @private
  14849. * @param {CanvasRenderingContext2D} ctx Context to render on
  14850. */
  14851. _renderDashedStroke: function(ctx) {
  14852. var p1, p2;
  14853.  
  14854. ctx.beginPath();
  14855. for (var i = 0, len = this.points.length; i < len; i++) {
  14856. p1 = this.points[i];
  14857. p2 = this.points[i + 1] || p1;
  14858. fabric.util.drawDashedLine(ctx, p1.x, p1.y, p2.x, p2.y, this.strokeDashArray);
  14859. }
  14860. },
  14861.  
  14862. /**
  14863. * Returns complexity of an instance
  14864. * @return {Number} complexity of this instance
  14865. */
  14866. complexity: function() {
  14867. return this.get('points').length;
  14868. }
  14869. });
  14870.  
  14871. /* _FROM_SVG_START_ */
  14872. /**
  14873. * List of attribute names to account for when parsing SVG element (used by {@link fabric.Polyline.fromElement})
  14874. * @static
  14875. * @memberOf fabric.Polyline
  14876. * @see: http://www.w3.org/TR/SVG/shapes.html#PolylineElement
  14877. */
  14878. fabric.Polyline.ATTRIBUTE_NAMES = fabric.SHARED_ATTRIBUTES.concat();
  14879.  
  14880. /**
  14881. * Returns fabric.Polyline instance from an SVG element
  14882. * @static
  14883. * @memberOf fabric.Polyline
  14884. * @param {SVGElement} element Element to parse
  14885. * @param {Object} [options] Options object
  14886. * @return {fabric.Polyline} Instance of fabric.Polyline
  14887. */
  14888. fabric.Polyline.fromElement = function(element, options) {
  14889. if (!element) {
  14890. return null;
  14891. }
  14892. options || (options = { });
  14893.  
  14894. var points = fabric.parsePointsAttribute(element.getAttribute('points')),
  14895. parsedAttributes = fabric.parseAttributes(element, fabric.Polyline.ATTRIBUTE_NAMES);
  14896.  
  14897. if (points === null) {
  14898. return null;
  14899. }
  14900.  
  14901. return new fabric.Polyline(points, fabric.util.object.extend(parsedAttributes, options));
  14902. };
  14903. /* _FROM_SVG_END_ */
  14904.  
  14905. /**
  14906. * Returns fabric.Polyline instance from an object representation
  14907. * @static
  14908. * @memberOf fabric.Polyline
  14909. * @param {Object} object Object to create an instance from
  14910. * @return {fabric.Polyline} Instance of fabric.Polyline
  14911. */
  14912. fabric.Polyline.fromObject = function(object) {
  14913. var points = object.points;
  14914. return new fabric.Polyline(points, object, true);
  14915. };
  14916.  
  14917. })(typeof exports !== 'undefined' ? exports : this);
  14918.  
  14919.  
  14920. (function(global) {
  14921.  
  14922. 'use strict';
  14923.  
  14924. var fabric = global.fabric || (global.fabric = { }),
  14925. extend = fabric.util.object.extend,
  14926. min = fabric.util.array.min,
  14927. max = fabric.util.array.max,
  14928. toFixed = fabric.util.toFixed;
  14929.  
  14930. if (fabric.Polygon) {
  14931. fabric.warn('fabric.Polygon is already defined');
  14932. return;
  14933. }
  14934.  
  14935. /**
  14936. * Polygon class
  14937. * @class fabric.Polygon
  14938. * @extends fabric.Object
  14939. * @see {@link fabric.Polygon#initialize} for constructor definition
  14940. */
  14941. fabric.Polygon = fabric.util.createClass(fabric.Object, /** @lends fabric.Polygon.prototype */ {
  14942.  
  14943. /**
  14944. * Type of an object
  14945. * @type String
  14946. * @default
  14947. */
  14948. type: 'polygon',
  14949.  
  14950. /**
  14951. * Points array
  14952. * @type Array
  14953. * @default
  14954. */
  14955. points: null,
  14956.  
  14957. /**
  14958. * Minimum X from points values, necessary to offset points
  14959. * @type Number
  14960. * @default
  14961. */
  14962. minX: 0,
  14963.  
  14964. /**
  14965. * Minimum Y from points values, necessary to offset points
  14966. * @type Number
  14967. * @default
  14968. */
  14969. minY: 0,
  14970.  
  14971. /**
  14972. * Constructor
  14973. * @param {Array} points Array of points
  14974. * @param {Object} [options] Options object
  14975. * @return {fabric.Polygon} thisArg
  14976. */
  14977. initialize: function(points, options) {
  14978. options = options || { };
  14979. this.points = points;
  14980. this.callSuper('initialize', options);
  14981. this._calcDimensions();
  14982. if (!('top' in options)) {
  14983. this.top = this.minY;
  14984. }
  14985. if (!('left' in options)) {
  14986. this.left = this.minX;
  14987. }
  14988. },
  14989.  
  14990. /**
  14991. * @private
  14992. */
  14993. _calcDimensions: function() {
  14994.  
  14995. var points = this.points,
  14996. minX = min(points, 'x'),
  14997. minY = min(points, 'y'),
  14998. maxX = max(points, 'x'),
  14999. maxY = max(points, 'y');
  15000.  
  15001. this.width = (maxX - minX) || 1;
  15002. this.height = (maxY - minY) || 1;
  15003.  
  15004. this.minX = minX,
  15005. this.minY = minY;
  15006. },
  15007.  
  15008. /**
  15009. * @private
  15010. */
  15011. _applyPointOffset: function() {
  15012. // change points to offset polygon into a bounding box
  15013. // executed one time
  15014. this.points.forEach(function(p) {
  15015. p.x -= (this.minX + this.width / 2);
  15016. p.y -= (this.minY + this.height / 2);
  15017. }, this);
  15018. },
  15019.  
  15020. /**
  15021. * Returns object representation of an instance
  15022. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  15023. * @return {Object} Object representation of an instance
  15024. */
  15025. toObject: function(propertiesToInclude) {
  15026. return extend(this.callSuper('toObject', propertiesToInclude), {
  15027. points: this.points.concat()
  15028. });
  15029. },
  15030.  
  15031. /* _TO_SVG_START_ */
  15032. /**
  15033. * Returns svg representation of an instance
  15034. * @param {Function} [reviver] Method for further parsing of svg representation.
  15035. * @return {String} svg representation of an instance
  15036. */
  15037. toSVG: function(reviver) {
  15038. var points = [],
  15039. markup = this._createBaseSVGMarkup();
  15040.  
  15041. for (var i = 0, len = this.points.length; i < len; i++) {
  15042. points.push(toFixed(this.points[i].x, 2), ',', toFixed(this.points[i].y, 2), ' ');
  15043. }
  15044.  
  15045. markup.push(
  15046. '<', this.type, ' ',
  15047. 'points="', points.join(''),
  15048. '" style="', this.getSvgStyles(),
  15049. '" transform="', this.getSvgTransform(),
  15050. ' ', this.getSvgTransformMatrix(),
  15051. '"/>\n'
  15052. );
  15053.  
  15054. return reviver ? reviver(markup.join('')) : markup.join('');
  15055. },
  15056. /* _TO_SVG_END_ */
  15057.  
  15058. /**
  15059. * @private
  15060. * @param {CanvasRenderingContext2D} ctx Context to render on
  15061. */
  15062. _render: function(ctx) {
  15063. this.commonRender(ctx);
  15064. this._renderFill(ctx);
  15065. if (this.stroke || this.strokeDashArray) {
  15066. ctx.closePath();
  15067. this._renderStroke(ctx);
  15068. }
  15069. },
  15070.  
  15071. /**
  15072. * @private
  15073. * @param {CanvasRenderingContext2D} ctx Context to render on
  15074. */
  15075. commonRender: function(ctx) {
  15076. var point;
  15077. ctx.beginPath();
  15078.  
  15079. if (this._applyPointOffset) {
  15080. if (!(this.group && this.group.type === 'path-group')) {
  15081. this._applyPointOffset();
  15082. }
  15083. this._applyPointOffset = null;
  15084. }
  15085.  
  15086. ctx.moveTo(this.points[0].x, this.points[0].y);
  15087. for (var i = 0, len = this.points.length; i < len; i++) {
  15088. point = this.points[i];
  15089. ctx.lineTo(point.x, point.y);
  15090. }
  15091. },
  15092.  
  15093. /**
  15094. * @private
  15095. * @param {CanvasRenderingContext2D} ctx Context to render on
  15096. */
  15097. _renderDashedStroke: function(ctx) {
  15098. fabric.Polyline.prototype._renderDashedStroke.call(this, ctx);
  15099. ctx.closePath();
  15100. },
  15101.  
  15102. /**
  15103. * Returns complexity of an instance
  15104. * @return {Number} complexity of this instance
  15105. */
  15106. complexity: function() {
  15107. return this.points.length;
  15108. }
  15109. });
  15110.  
  15111. /* _FROM_SVG_START_ */
  15112. /**
  15113. * List of attribute names to account for when parsing SVG element (used by `fabric.Polygon.fromElement`)
  15114. * @static
  15115. * @memberOf fabric.Polygon
  15116. * @see: http://www.w3.org/TR/SVG/shapes.html#PolygonElement
  15117. */
  15118. fabric.Polygon.ATTRIBUTE_NAMES = fabric.SHARED_ATTRIBUTES.concat();
  15119.  
  15120. /**
  15121. * Returns {@link fabric.Polygon} instance from an SVG element
  15122. * @static
  15123. * @memberOf fabric.Polygon
  15124. * @param {SVGElement} element Element to parse
  15125. * @param {Object} [options] Options object
  15126. * @return {fabric.Polygon} Instance of fabric.Polygon
  15127. */
  15128. fabric.Polygon.fromElement = function(element, options) {
  15129. if (!element) {
  15130. return null;
  15131. }
  15132.  
  15133. options || (options = { });
  15134.  
  15135. var points = fabric.parsePointsAttribute(element.getAttribute('points')),
  15136. parsedAttributes = fabric.parseAttributes(element, fabric.Polygon.ATTRIBUTE_NAMES);
  15137.  
  15138. if (points === null) {
  15139. return null;
  15140. }
  15141.  
  15142. return new fabric.Polygon(points, extend(parsedAttributes, options));
  15143. };
  15144. /* _FROM_SVG_END_ */
  15145.  
  15146. /**
  15147. * Returns fabric.Polygon instance from an object representation
  15148. * @static
  15149. * @memberOf fabric.Polygon
  15150. * @param {Object} object Object to create an instance from
  15151. * @return {fabric.Polygon} Instance of fabric.Polygon
  15152. */
  15153. fabric.Polygon.fromObject = function(object) {
  15154. return new fabric.Polygon(object.points, object, true);
  15155. };
  15156.  
  15157. })(typeof exports !== 'undefined' ? exports : this);
  15158.  
  15159.  
  15160. (function(global) {
  15161.  
  15162. 'use strict';
  15163.  
  15164. var fabric = global.fabric || (global.fabric = { }),
  15165. min = fabric.util.array.min,
  15166. max = fabric.util.array.max,
  15167. extend = fabric.util.object.extend,
  15168. _toString = Object.prototype.toString,
  15169. drawArc = fabric.util.drawArc,
  15170. commandLengths = {
  15171. m: 2,
  15172. l: 2,
  15173. h: 1,
  15174. v: 1,
  15175. c: 6,
  15176. s: 4,
  15177. q: 4,
  15178. t: 2,
  15179. a: 7
  15180. },
  15181. repeatedCommands = {
  15182. m: 'l',
  15183. M: 'L'
  15184. };
  15185.  
  15186. if (fabric.Path) {
  15187. fabric.warn('fabric.Path is already defined');
  15188. return;
  15189. }
  15190.  
  15191. /**
  15192. * Path class
  15193. * @class fabric.Path
  15194. * @extends fabric.Object
  15195. * @tutorial {@link http://fabricjs.com/fabric-intro-part-1/#path_and_pathgroup}
  15196. * @see {@link fabric.Path#initialize} for constructor definition
  15197. */
  15198. fabric.Path = fabric.util.createClass(fabric.Object, /** @lends fabric.Path.prototype */ {
  15199.  
  15200. /**
  15201. * Type of an object
  15202. * @type String
  15203. * @default
  15204. */
  15205. type: 'path',
  15206.  
  15207. /**
  15208. * Array of path points
  15209. * @type Array
  15210. * @default
  15211. */
  15212. path: null,
  15213.  
  15214. /**
  15215. * Minimum X from points values, necessary to offset points
  15216. * @type Number
  15217. * @default
  15218. */
  15219. minX: 0,
  15220.  
  15221. /**
  15222. * Minimum Y from points values, necessary to offset points
  15223. * @type Number
  15224. * @default
  15225. */
  15226. minY: 0,
  15227.  
  15228. /**
  15229. * Constructor
  15230. * @param {Array|String} path Path data (sequence of coordinates and corresponding "command" tokens)
  15231. * @param {Object} [options] Options object
  15232. * @return {fabric.Path} thisArg
  15233. */
  15234. initialize: function(path, options) {
  15235. options = options || { };
  15236.  
  15237. this.setOptions(options);
  15238.  
  15239. if (!path) {
  15240. throw new Error('`path` argument is required');
  15241. }
  15242.  
  15243. var fromArray = _toString.call(path) === '[object Array]';
  15244.  
  15245. this.path = fromArray
  15246. ? path
  15247. // one of commands (m,M,l,L,q,Q,c,C,etc.) followed by non-command characters (i.e. command values)
  15248. : path.match && path.match(/[mzlhvcsqta][^mzlhvcsqta]*/gi);
  15249.  
  15250. if (!this.path) {
  15251. return;
  15252. }
  15253.  
  15254. if (!fromArray) {
  15255. this.path = this._parsePath();
  15256. }
  15257.  
  15258. var calcDim = this._parseDimensions();
  15259. this.minX = calcDim.left;
  15260. this.minY = calcDim.top;
  15261. this.width = calcDim.width;
  15262. this.height = calcDim.height;
  15263. this.top = this.top || this.minY;
  15264. this.left = this.left || this.minX;
  15265. this.pathOffset = this.pathOffset || {
  15266. x: this.minX + this.width / 2,
  15267. y: this.minY + this.height / 2
  15268. };
  15269.  
  15270. if (options.sourcePath) {
  15271. this.setSourcePath(options.sourcePath);
  15272. }
  15273. },
  15274.  
  15275. /**
  15276. * @private
  15277. * @param {CanvasRenderingContext2D} ctx context to render path on
  15278. */
  15279. _render: function(ctx) {
  15280. var current, // current instruction
  15281. previous = null,
  15282. subpathStartX = 0,
  15283. subpathStartY = 0,
  15284. x = 0, // current x
  15285. y = 0, // current y
  15286. controlX = 0, // current control point x
  15287. controlY = 0, // current control point y
  15288. tempX,
  15289. tempY,
  15290. tempControlX,
  15291. tempControlY,
  15292. l = -this.pathOffset.x,
  15293. t = -this.pathOffset.y;
  15294.  
  15295. if (this.group && this.group.type === 'path-group') {
  15296. l = 0;
  15297. t = 0;
  15298. }
  15299.  
  15300. ctx.beginPath();
  15301.  
  15302. for (var i = 0, len = this.path.length; i < len; ++i) {
  15303.  
  15304. current = this.path[i];
  15305.  
  15306. switch (current[0]) { // first letter
  15307.  
  15308. case 'l': // lineto, relative
  15309. x += current[1];
  15310. y += current[2];
  15311. ctx.lineTo(x + l, y + t);
  15312. break;
  15313.  
  15314. case 'L': // lineto, absolute
  15315. x = current[1];
  15316. y = current[2];
  15317. ctx.lineTo(x + l, y + t);
  15318. break;
  15319.  
  15320. case 'h': // horizontal lineto, relative
  15321. x += current[1];
  15322. ctx.lineTo(x + l, y + t);
  15323. break;
  15324.  
  15325. case 'H': // horizontal lineto, absolute
  15326. x = current[1];
  15327. ctx.lineTo(x + l, y + t);
  15328. break;
  15329.  
  15330. case 'v': // vertical lineto, relative
  15331. y += current[1];
  15332. ctx.lineTo(x + l, y + t);
  15333. break;
  15334.  
  15335. case 'V': // verical lineto, absolute
  15336. y = current[1];
  15337. ctx.lineTo(x + l, y + t);
  15338. break;
  15339.  
  15340. case 'm': // moveTo, relative
  15341. x += current[1];
  15342. y += current[2];
  15343. subpathStartX = x;
  15344. subpathStartY = y;
  15345. ctx.moveTo(x + l, y + t);
  15346. break;
  15347.  
  15348. case 'M': // moveTo, absolute
  15349. x = current[1];
  15350. y = current[2];
  15351. subpathStartX = x;
  15352. subpathStartY = y;
  15353. ctx.moveTo(x + l, y + t);
  15354. break;
  15355.  
  15356. case 'c': // bezierCurveTo, relative
  15357. tempX = x + current[5];
  15358. tempY = y + current[6];
  15359. controlX = x + current[3];
  15360. controlY = y + current[4];
  15361. ctx.bezierCurveTo(
  15362. x + current[1] + l, // x1
  15363. y + current[2] + t, // y1
  15364. controlX + l, // x2
  15365. controlY + t, // y2
  15366. tempX + l,
  15367. tempY + t
  15368. );
  15369. x = tempX;
  15370. y = tempY;
  15371. break;
  15372.  
  15373. case 'C': // bezierCurveTo, absolute
  15374. x = current[5];
  15375. y = current[6];
  15376. controlX = current[3];
  15377. controlY = current[4];
  15378. ctx.bezierCurveTo(
  15379. current[1] + l,
  15380. current[2] + t,
  15381. controlX + l,
  15382. controlY + t,
  15383. x + l,
  15384. y + t
  15385. );
  15386. break;
  15387.  
  15388. case 's': // shorthand cubic bezierCurveTo, relative
  15389.  
  15390. // transform to absolute x,y
  15391. tempX = x + current[3];
  15392. tempY = y + current[4];
  15393.  
  15394. // calculate reflection of previous control points
  15395. controlX = controlX ? (2 * x - controlX) : x;
  15396. controlY = controlY ? (2 * y - controlY) : y;
  15397.  
  15398. ctx.bezierCurveTo(
  15399. controlX + l,
  15400. controlY + t,
  15401. x + current[1] + l,
  15402. y + current[2] + t,
  15403. tempX + l,
  15404. tempY + t
  15405. );
  15406. // set control point to 2nd one of this command
  15407. // "... the first control point is assumed to be
  15408. // the reflection of the second control point on
  15409. // the previous command relative to the current point."
  15410. controlX = x + current[1];
  15411. controlY = y + current[2];
  15412.  
  15413. x = tempX;
  15414. y = tempY;
  15415. break;
  15416.  
  15417. case 'S': // shorthand cubic bezierCurveTo, absolute
  15418. tempX = current[3];
  15419. tempY = current[4];
  15420. // calculate reflection of previous control points
  15421. controlX = 2 * x - controlX;
  15422. controlY = 2 * y - controlY;
  15423. ctx.bezierCurveTo(
  15424. controlX + l,
  15425. controlY + t,
  15426. current[1] + l,
  15427. current[2] + t,
  15428. tempX + l,
  15429. tempY + t
  15430. );
  15431. x = tempX;
  15432. y = tempY;
  15433.  
  15434. // set control point to 2nd one of this command
  15435. // "... the first control point is assumed to be
  15436. // the reflection of the second control point on
  15437. // the previous command relative to the current point."
  15438. controlX = current[1];
  15439. controlY = current[2];
  15440.  
  15441. break;
  15442.  
  15443. case 'q': // quadraticCurveTo, relative
  15444. // transform to absolute x,y
  15445. tempX = x + current[3];
  15446. tempY = y + current[4];
  15447.  
  15448. controlX = x + current[1];
  15449. controlY = y + current[2];
  15450.  
  15451. ctx.quadraticCurveTo(
  15452. controlX + l,
  15453. controlY + t,
  15454. tempX + l,
  15455. tempY + t
  15456. );
  15457. x = tempX;
  15458. y = tempY;
  15459. break;
  15460.  
  15461. case 'Q': // quadraticCurveTo, absolute
  15462. tempX = current[3];
  15463. tempY = current[4];
  15464.  
  15465. ctx.quadraticCurveTo(
  15466. current[1] + l,
  15467. current[2] + t,
  15468. tempX + l,
  15469. tempY + t
  15470. );
  15471. x = tempX;
  15472. y = tempY;
  15473. controlX = current[1];
  15474. controlY = current[2];
  15475. break;
  15476.  
  15477. case 't': // shorthand quadraticCurveTo, relative
  15478.  
  15479. // transform to absolute x,y
  15480. tempX = x + current[1];
  15481. tempY = y + current[2];
  15482.  
  15483. if (previous[0].match(/[QqTt]/) === null) {
  15484. // If there is no previous command or if the previous command was not a Q, q, T or t,
  15485. // assume the control point is coincident with the current point
  15486. controlX = x;
  15487. controlY = y;
  15488. }
  15489. else if (previous[0] === 't') {
  15490. // calculate reflection of previous control points for t
  15491. controlX = 2 * x - tempControlX;
  15492. controlY = 2 * y - tempControlY;
  15493. }
  15494. else if (previous[0] === 'q') {
  15495. // calculate reflection of previous control points for q
  15496. controlX = 2 * x - controlX;
  15497. controlY = 2 * y - controlY;
  15498. }
  15499.  
  15500. tempControlX = controlX;
  15501. tempControlY = controlY;
  15502.  
  15503. ctx.quadraticCurveTo(
  15504. controlX + l,
  15505. controlY + t,
  15506. tempX + l,
  15507. tempY + t
  15508. );
  15509. x = tempX;
  15510. y = tempY;
  15511. controlX = x + current[1];
  15512. controlY = y + current[2];
  15513. break;
  15514.  
  15515. case 'T':
  15516. tempX = current[1];
  15517. tempY = current[2];
  15518.  
  15519. // calculate reflection of previous control points
  15520. controlX = 2 * x - controlX;
  15521. controlY = 2 * y - controlY;
  15522. ctx.quadraticCurveTo(
  15523. controlX + l,
  15524. controlY + t,
  15525. tempX + l,
  15526. tempY + t
  15527. );
  15528. x = tempX;
  15529. y = tempY;
  15530. break;
  15531.  
  15532. case 'a':
  15533. // TODO: optimize this
  15534. drawArc(ctx, x + l, y + t, [
  15535. current[1],
  15536. current[2],
  15537. current[3],
  15538. current[4],
  15539. current[5],
  15540. current[6] + x + l,
  15541. current[7] + y + t
  15542. ]);
  15543. x += current[6];
  15544. y += current[7];
  15545. break;
  15546.  
  15547. case 'A':
  15548. // TODO: optimize this
  15549. drawArc(ctx, x + l, y + t, [
  15550. current[1],
  15551. current[2],
  15552. current[3],
  15553. current[4],
  15554. current[5],
  15555. current[6] + l,
  15556. current[7] + t
  15557. ]);
  15558. x = current[6];
  15559. y = current[7];
  15560. break;
  15561.  
  15562. case 'z':
  15563. case 'Z':
  15564. x = subpathStartX;
  15565. y = subpathStartY;
  15566. ctx.closePath();
  15567. break;
  15568. }
  15569. previous = current;
  15570. }
  15571. this._renderFill(ctx);
  15572. this._renderStroke(ctx);
  15573. },
  15574.  
  15575. /**
  15576. * Renders path on a specified context
  15577. * @param {CanvasRenderingContext2D} ctx context to render path on
  15578. * @param {Boolean} [noTransform] When true, context is not transformed
  15579. */
  15580. render: function(ctx, noTransform) {
  15581. // do not render if width/height are zeros or object is not visible
  15582. if (!this.visible) {
  15583. return;
  15584. }
  15585.  
  15586. ctx.save();
  15587.  
  15588. this._setupCompositeOperation(ctx);
  15589. if (!noTransform) {
  15590. this.transform(ctx);
  15591. }
  15592. this._setStrokeStyles(ctx);
  15593. this._setFillStyles(ctx);
  15594. if (this.group && this.group.type === 'path-group') {
  15595. ctx.translate(-this.group.width / 2, -this.group.height / 2);
  15596. }
  15597. if (this.transformMatrix) {
  15598. ctx.transform.apply(ctx, this.transformMatrix);
  15599. }
  15600. this._setOpacity(ctx);
  15601. this._setShadow(ctx);
  15602. this.clipTo && fabric.util.clipContext(this, ctx);
  15603. this._render(ctx, noTransform);
  15604. this.clipTo && ctx.restore();
  15605. this._removeShadow(ctx);
  15606. this._restoreCompositeOperation(ctx);
  15607.  
  15608. ctx.restore();
  15609. },
  15610.  
  15611. /**
  15612. * Returns string representation of an instance
  15613. * @return {String} string representation of an instance
  15614. */
  15615. toString: function() {
  15616. return '#<fabric.Path (' + this.complexity() +
  15617. '): { "top": ' + this.top + ', "left": ' + this.left + ' }>';
  15618. },
  15619.  
  15620. /**
  15621. * Returns object representation of an instance
  15622. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  15623. * @return {Object} object representation of an instance
  15624. */
  15625. toObject: function(propertiesToInclude) {
  15626. var o = extend(this.callSuper('toObject', propertiesToInclude), {
  15627. path: this.path.map(function(item) { return item.slice() }),
  15628. pathOffset: this.pathOffset
  15629. });
  15630. if (this.sourcePath) {
  15631. o.sourcePath = this.sourcePath;
  15632. }
  15633. if (this.transformMatrix) {
  15634. o.transformMatrix = this.transformMatrix;
  15635. }
  15636. return o;
  15637. },
  15638.  
  15639. /**
  15640. * Returns dataless object representation of an instance
  15641. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  15642. * @return {Object} object representation of an instance
  15643. */
  15644. toDatalessObject: function(propertiesToInclude) {
  15645. var o = this.toObject(propertiesToInclude);
  15646. if (this.sourcePath) {
  15647. o.path = this.sourcePath;
  15648. }
  15649. delete o.sourcePath;
  15650. return o;
  15651. },
  15652.  
  15653. /* _TO_SVG_START_ */
  15654. /**
  15655. * Returns svg representation of an instance
  15656. * @param {Function} [reviver] Method for further parsing of svg representation.
  15657. * @return {String} svg representation of an instance
  15658. */
  15659. toSVG: function(reviver) {
  15660. var chunks = [],
  15661. markup = this._createBaseSVGMarkup(), addTransform = '';
  15662.  
  15663. for (var i = 0, len = this.path.length; i < len; i++) {
  15664. chunks.push(this.path[i].join(' '));
  15665. }
  15666. var path = chunks.join(' ');
  15667. if (!(this.group && this.group.type === 'path-group')) {
  15668. addTransform = 'translate(' + (-this.pathOffset.x) + ', ' + (-this.pathOffset.y) + ')';
  15669. }
  15670. markup.push(
  15671. //jscs:disable validateIndentation
  15672. '<path ',
  15673. 'd="', path,
  15674. '" style="', this.getSvgStyles(),
  15675. '" transform="', this.getSvgTransform(), addTransform,
  15676. this.getSvgTransformMatrix(), '" stroke-linecap="round" ',
  15677. '/>\n'
  15678. //jscs:enable validateIndentation
  15679. );
  15680.  
  15681. return reviver ? reviver(markup.join('')) : markup.join('');
  15682. },
  15683. /* _TO_SVG_END_ */
  15684.  
  15685. /**
  15686. * Returns number representation of an instance complexity
  15687. * @return {Number} complexity of this instance
  15688. */
  15689. complexity: function() {
  15690. return this.path.length;
  15691. },
  15692.  
  15693. /**
  15694. * @private
  15695. */
  15696. _parsePath: function() {
  15697. var result = [ ],
  15698. coords = [ ],
  15699. currentPath,
  15700. parsed,
  15701. re = /([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:e[-+]?\d+)?)/ig,
  15702. match,
  15703. coordsStr;
  15704.  
  15705. for (var i = 0, coordsParsed, len = this.path.length; i < len; i++) {
  15706. currentPath = this.path[i];
  15707.  
  15708. coordsStr = currentPath.slice(1).trim();
  15709. coords.length = 0;
  15710.  
  15711. while ((match = re.exec(coordsStr))) {
  15712. coords.push(match[0]);
  15713. }
  15714.  
  15715. coordsParsed = [ currentPath.charAt(0) ];
  15716.  
  15717. for (var j = 0, jlen = coords.length; j < jlen; j++) {
  15718. parsed = parseFloat(coords[j]);
  15719. if (!isNaN(parsed)) {
  15720. coordsParsed.push(parsed);
  15721. }
  15722. }
  15723.  
  15724. var command = coordsParsed[0],
  15725. commandLength = commandLengths[command.toLowerCase()],
  15726. repeatedCommand = repeatedCommands[command] || command;
  15727.  
  15728. if (coordsParsed.length - 1 > commandLength) {
  15729. for (var k = 1, klen = coordsParsed.length; k < klen; k += commandLength) {
  15730. result.push([ command ].concat(coordsParsed.slice(k, k + commandLength)));
  15731. command = repeatedCommand;
  15732. }
  15733. }
  15734. else {
  15735. result.push(coordsParsed);
  15736. }
  15737. }
  15738.  
  15739. return result;
  15740. },
  15741.  
  15742. /**
  15743. * @private
  15744. */
  15745. _parseDimensions: function() {
  15746.  
  15747. var aX = [],
  15748. aY = [],
  15749. current, // current instruction
  15750. previous = null,
  15751. subpathStartX = 0,
  15752. subpathStartY = 0,
  15753. x = 0, // current x
  15754. y = 0, // current y
  15755. controlX = 0, // current control point x
  15756. controlY = 0, // current control point y
  15757. tempX,
  15758. tempY,
  15759. tempControlX,
  15760. tempControlY,
  15761. bounds;
  15762.  
  15763. for (var i = 0, len = this.path.length; i < len; ++i) {
  15764.  
  15765. current = this.path[i];
  15766.  
  15767. switch (current[0]) { // first letter
  15768.  
  15769. case 'l': // lineto, relative
  15770. x += current[1];
  15771. y += current[2];
  15772. bounds = [ ];
  15773. break;
  15774.  
  15775. case 'L': // lineto, absolute
  15776. x = current[1];
  15777. y = current[2];
  15778. bounds = [ ];
  15779. break;
  15780.  
  15781. case 'h': // horizontal lineto, relative
  15782. x += current[1];
  15783. bounds = [ ];
  15784. break;
  15785.  
  15786. case 'H': // horizontal lineto, absolute
  15787. x = current[1];
  15788. bounds = [ ];
  15789. break;
  15790.  
  15791. case 'v': // vertical lineto, relative
  15792. y += current[1];
  15793. bounds = [ ];
  15794. break;
  15795.  
  15796. case 'V': // verical lineto, absolute
  15797. y = current[1];
  15798. bounds = [ ];
  15799. break;
  15800.  
  15801. case 'm': // moveTo, relative
  15802. x += current[1];
  15803. y += current[2];
  15804. subpathStartX = x;
  15805. subpathStartY = y;
  15806. bounds = [ ];
  15807. break;
  15808.  
  15809. case 'M': // moveTo, absolute
  15810. x = current[1];
  15811. y = current[2];
  15812. subpathStartX = x;
  15813. subpathStartY = y;
  15814. bounds = [ ];
  15815. break;
  15816.  
  15817. case 'c': // bezierCurveTo, relative
  15818. tempX = x + current[5];
  15819. tempY = y + current[6];
  15820. controlX = x + current[3];
  15821. controlY = y + current[4];
  15822. bounds = fabric.util.getBoundsOfCurve(x, y,
  15823. x + current[1], // x1
  15824. y + current[2], // y1
  15825. controlX, // x2
  15826. controlY, // y2
  15827. tempX,
  15828. tempY
  15829. );
  15830. x = tempX;
  15831. y = tempY;
  15832. break;
  15833.  
  15834. case 'C': // bezierCurveTo, absolute
  15835. x = current[5];
  15836. y = current[6];
  15837. controlX = current[3];
  15838. controlY = current[4];
  15839. bounds = fabric.util.getBoundsOfCurve(x, y,
  15840. current[1],
  15841. current[2],
  15842. controlX,
  15843. controlY,
  15844. x,
  15845. y
  15846. );
  15847. break;
  15848.  
  15849. case 's': // shorthand cubic bezierCurveTo, relative
  15850.  
  15851. // transform to absolute x,y
  15852. tempX = x + current[3];
  15853. tempY = y + current[4];
  15854.  
  15855. // calculate reflection of previous control points
  15856. controlX = controlX ? (2 * x - controlX) : x;
  15857. controlY = controlY ? (2 * y - controlY) : y;
  15858.  
  15859. bounds = fabric.util.getBoundsOfCurve(x, y,
  15860. controlX,
  15861. controlY,
  15862. x + current[1],
  15863. y + current[2],
  15864. tempX,
  15865. tempY
  15866. );
  15867. // set control point to 2nd one of this command
  15868. // "... the first control point is assumed to be
  15869. // the reflection of the second control point on
  15870. // the previous command relative to the current point."
  15871. controlX = x + current[1];
  15872. controlY = y + current[2];
  15873. x = tempX;
  15874. y = tempY;
  15875. break;
  15876.  
  15877. case 'S': // shorthand cubic bezierCurveTo, absolute
  15878. tempX = current[3];
  15879. tempY = current[4];
  15880. // calculate reflection of previous control points
  15881. controlX = 2 * x - controlX;
  15882. controlY = 2 * y - controlY;
  15883. bounds = fabric.util.getBoundsOfCurve(x, y,
  15884. controlX,
  15885. controlY,
  15886. current[1],
  15887. current[2],
  15888. tempX,
  15889. tempY
  15890. );
  15891. x = tempX;
  15892. y = tempY;
  15893. // set control point to 2nd one of this command
  15894. // "... the first control point is assumed to be
  15895. // the reflection of the second control point on
  15896. // the previous command relative to the current point."
  15897. controlX = current[1];
  15898. controlY = current[2];
  15899. break;
  15900.  
  15901. case 'q': // quadraticCurveTo, relative
  15902. // transform to absolute x,y
  15903. tempX = x + current[3];
  15904. tempY = y + current[4];
  15905. controlX = x + current[1];
  15906. controlY = y + current[2];
  15907. bounds = fabric.util.getBoundsOfCurve(x, y,
  15908. controlX,
  15909. controlY,
  15910. controlX,
  15911. controlY,
  15912. tempX,
  15913. tempY
  15914. );
  15915. x = tempX;
  15916. y = tempY;
  15917. break;
  15918.  
  15919. case 'Q': // quadraticCurveTo, absolute
  15920. controlX = current[1];
  15921. controlY = current[2];
  15922. bounds = fabric.util.getBoundsOfCurve(x, y,
  15923. controlX,
  15924. controlY,
  15925. controlX,
  15926. controlY,
  15927. current[3],
  15928. current[4]
  15929. );
  15930. x = current[3];
  15931. y = current[4];
  15932. break;
  15933.  
  15934. case 't': // shorthand quadraticCurveTo, relative
  15935. // transform to absolute x,y
  15936. tempX = x + current[1];
  15937. tempY = y + current[2];
  15938. if (previous[0].match(/[QqTt]/) === null) {
  15939. // If there is no previous command or if the previous command was not a Q, q, T or t,
  15940. // assume the control point is coincident with the current point
  15941. controlX = x;
  15942. controlY = y;
  15943. }
  15944. else if (previous[0] === 't') {
  15945. // calculate reflection of previous control points for t
  15946. controlX = 2 * x - tempControlX;
  15947. controlY = 2 * y - tempControlY;
  15948. }
  15949. else if (previous[0] === 'q') {
  15950. // calculate reflection of previous control points for q
  15951. controlX = 2 * x - controlX;
  15952. controlY = 2 * y - controlY;
  15953. }
  15954.  
  15955. tempControlX = controlX;
  15956. tempControlY = controlY;
  15957.  
  15958. bounds = fabric.util.getBoundsOfCurve(x, y,
  15959. controlX,
  15960. controlY,
  15961. controlX,
  15962. controlY,
  15963. tempX,
  15964. tempY
  15965. );
  15966. x = tempX;
  15967. y = tempY;
  15968. controlX = x + current[1];
  15969. controlY = y + current[2];
  15970. break;
  15971.  
  15972. case 'T':
  15973. tempX = current[1];
  15974. tempY = current[2];
  15975. // calculate reflection of previous control points
  15976. controlX = 2 * x - controlX;
  15977. controlY = 2 * y - controlY;
  15978. bounds = fabric.util.getBoundsOfCurve(x, y,
  15979. controlX,
  15980. controlY,
  15981. controlX,
  15982. controlY,
  15983. tempX,
  15984. tempY
  15985. );
  15986. x = tempX;
  15987. y = tempY;
  15988. break;
  15989.  
  15990. case 'a':
  15991. // TODO: optimize this
  15992. bounds = fabric.util.getBoundsOfArc(x, y,
  15993. current[1],
  15994. current[2],
  15995. current[3],
  15996. current[4],
  15997. current[5],
  15998. current[6] + x,
  15999. current[7] + y
  16000. );
  16001. x += current[6];
  16002. y += current[7];
  16003. break;
  16004.  
  16005. case 'A':
  16006. // TODO: optimize this
  16007. bounds = fabric.util.getBoundsOfArc(x, y,
  16008. current[1],
  16009. current[2],
  16010. current[3],
  16011. current[4],
  16012. current[5],
  16013. current[6],
  16014. current[7]
  16015. );
  16016. x = current[6];
  16017. y = current[7];
  16018. break;
  16019.  
  16020. case 'z':
  16021. case 'Z':
  16022. x = subpathStartX;
  16023. y = subpathStartY;
  16024. break;
  16025. }
  16026. previous = current;
  16027. bounds.forEach(function (point) {
  16028. aX.push(point.x);
  16029. aY.push(point.y);
  16030. });
  16031. aX.push(x);
  16032. aY.push(y);
  16033. }
  16034.  
  16035. var minX = min(aX),
  16036. minY = min(aY),
  16037. maxX = max(aX),
  16038. maxY = max(aY),
  16039. deltaX = maxX - minX,
  16040. deltaY = maxY - minY,
  16041.  
  16042. o = {
  16043. left: minX,
  16044. top: minY,
  16045. width: deltaX,
  16046. height: deltaY
  16047. };
  16048.  
  16049. return o;
  16050. }
  16051. });
  16052.  
  16053. /**
  16054. * Creates an instance of fabric.Path from an object
  16055. * @static
  16056. * @memberOf fabric.Path
  16057. * @param {Object} object
  16058. * @param {Function} callback Callback to invoke when an fabric.Path instance is created
  16059. */
  16060. fabric.Path.fromObject = function(object, callback) {
  16061. if (typeof object.path === 'string') {
  16062. fabric.loadSVGFromURL(object.path, function (elements) {
  16063. var path = elements[0],
  16064. pathUrl = object.path;
  16065.  
  16066. delete object.path;
  16067.  
  16068. fabric.util.object.extend(path, object);
  16069. path.setSourcePath(pathUrl);
  16070.  
  16071. callback(path);
  16072. });
  16073. }
  16074. else {
  16075. callback(new fabric.Path(object.path, object));
  16076. }
  16077. };
  16078.  
  16079. /* _FROM_SVG_START_ */
  16080. /**
  16081. * List of attribute names to account for when parsing SVG element (used by `fabric.Path.fromElement`)
  16082. * @static
  16083. * @memberOf fabric.Path
  16084. * @see http://www.w3.org/TR/SVG/paths.html#PathElement
  16085. */
  16086. fabric.Path.ATTRIBUTE_NAMES = fabric.SHARED_ATTRIBUTES.concat(['d']);
  16087.  
  16088. /**
  16089. * Creates an instance of fabric.Path from an SVG <path> element
  16090. * @static
  16091. * @memberOf fabric.Path
  16092. * @param {SVGElement} element to parse
  16093. * @param {Function} callback Callback to invoke when an fabric.Path instance is created
  16094. * @param {Object} [options] Options object
  16095. */
  16096. fabric.Path.fromElement = function(element, callback, options) {
  16097. var parsedAttributes = fabric.parseAttributes(element, fabric.Path.ATTRIBUTE_NAMES);
  16098. callback && callback(new fabric.Path(parsedAttributes.d, extend(parsedAttributes, options)));
  16099. };
  16100. /* _FROM_SVG_END_ */
  16101.  
  16102. /**
  16103. * Indicates that instances of this type are async
  16104. * @static
  16105. * @memberOf fabric.Path
  16106. * @type Boolean
  16107. * @default
  16108. */
  16109. fabric.Path.async = true;
  16110.  
  16111. })(typeof exports !== 'undefined' ? exports : this);
  16112.  
  16113.  
  16114. (function(global) {
  16115.  
  16116. 'use strict';
  16117.  
  16118. var fabric = global.fabric || (global.fabric = { }),
  16119. extend = fabric.util.object.extend,
  16120. invoke = fabric.util.array.invoke,
  16121. parentToObject = fabric.Object.prototype.toObject;
  16122.  
  16123. if (fabric.PathGroup) {
  16124. fabric.warn('fabric.PathGroup is already defined');
  16125. return;
  16126. }
  16127.  
  16128. /**
  16129. * Path group class
  16130. * @class fabric.PathGroup
  16131. * @extends fabric.Path
  16132. * @tutorial {@link http://fabricjs.com/fabric-intro-part-1/#path_and_pathgroup}
  16133. * @see {@link fabric.PathGroup#initialize} for constructor definition
  16134. */
  16135. fabric.PathGroup = fabric.util.createClass(fabric.Path, /** @lends fabric.PathGroup.prototype */ {
  16136.  
  16137. /**
  16138. * Type of an object
  16139. * @type String
  16140. * @default
  16141. */
  16142. type: 'path-group',
  16143.  
  16144. /**
  16145. * Fill value
  16146. * @type String
  16147. * @default
  16148. */
  16149. fill: '',
  16150.  
  16151. /**
  16152. * Constructor
  16153. * @param {Array} paths
  16154. * @param {Object} [options] Options object
  16155. * @return {fabric.PathGroup} thisArg
  16156. */
  16157. initialize: function(paths, options) {
  16158.  
  16159. options = options || { };
  16160. this.paths = paths || [ ];
  16161.  
  16162. for (var i = this.paths.length; i--; ) {
  16163. this.paths[i].group = this;
  16164. }
  16165.  
  16166. this.setOptions(options);
  16167.  
  16168. if (options.widthAttr) {
  16169. this.scaleX = options.widthAttr / options.width;
  16170. }
  16171. if (options.heightAttr) {
  16172. this.scaleY = options.heightAttr / options.height;
  16173. }
  16174.  
  16175. this.setCoords();
  16176.  
  16177. if (options.sourcePath) {
  16178. this.setSourcePath(options.sourcePath);
  16179. }
  16180. },
  16181.  
  16182. /**
  16183. * Renders this group on a specified context
  16184. * @param {CanvasRenderingContext2D} ctx Context to render this instance on
  16185. */
  16186. render: function(ctx) {
  16187. // do not render if object is not visible
  16188. if (!this.visible) {
  16189. return;
  16190. }
  16191.  
  16192. ctx.save();
  16193.  
  16194. var m = this.transformMatrix;
  16195.  
  16196. if (m) {
  16197. ctx.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
  16198. }
  16199. this.transform(ctx);
  16200.  
  16201. this._setShadow(ctx);
  16202. this.clipTo && fabric.util.clipContext(this, ctx);
  16203. for (var i = 0, l = this.paths.length; i < l; ++i) {
  16204. this.paths[i].render(ctx, true);
  16205. }
  16206. this.clipTo && ctx.restore();
  16207. this._removeShadow(ctx);
  16208. ctx.restore();
  16209. },
  16210.  
  16211. /**
  16212. * Sets certain property to a certain value
  16213. * @param {String} prop
  16214. * @param {Any} value
  16215. * @return {fabric.PathGroup} thisArg
  16216. */
  16217. _set: function(prop, value) {
  16218.  
  16219. if (prop === 'fill' && value && this.isSameColor()) {
  16220. var i = this.paths.length;
  16221. while (i--) {
  16222. this.paths[i]._set(prop, value);
  16223. }
  16224. }
  16225.  
  16226. return this.callSuper('_set', prop, value);
  16227. },
  16228.  
  16229. /**
  16230. * Returns object representation of this path group
  16231. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  16232. * @return {Object} object representation of an instance
  16233. */
  16234. toObject: function(propertiesToInclude) {
  16235. var o = extend(parentToObject.call(this, propertiesToInclude), {
  16236. paths: invoke(this.getObjects(), 'toObject', propertiesToInclude)
  16237. });
  16238. if (this.sourcePath) {
  16239. o.sourcePath = this.sourcePath;
  16240. }
  16241. return o;
  16242. },
  16243.  
  16244. /**
  16245. * Returns dataless object representation of this path group
  16246. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  16247. * @return {Object} dataless object representation of an instance
  16248. */
  16249. toDatalessObject: function(propertiesToInclude) {
  16250. var o = this.toObject(propertiesToInclude);
  16251. if (this.sourcePath) {
  16252. o.paths = this.sourcePath;
  16253. }
  16254. return o;
  16255. },
  16256.  
  16257. /* _TO_SVG_START_ */
  16258. /**
  16259. * Returns svg representation of an instance
  16260. * @param {Function} [reviver] Method for further parsing of svg representation.
  16261. * @return {String} svg representation of an instance
  16262. */
  16263. toSVG: function(reviver) {
  16264. var objects = this.getObjects(),
  16265. translatePart = 'translate(' + this.left + ' ' + this.top + ')',
  16266. markup = [
  16267. //jscs:disable validateIndentation
  16268. '<g ',
  16269. 'style="', this.getSvgStyles(), '" ',
  16270. 'transform="', translatePart, this.getSvgTransform(), '" ',
  16271. '>\n'
  16272. //jscs:enable validateIndentation
  16273. ];
  16274.  
  16275. for (var i = 0, len = objects.length; i < len; i++) {
  16276. markup.push(objects[i].toSVG(reviver));
  16277. }
  16278. markup.push('</g>\n');
  16279.  
  16280. return reviver ? reviver(markup.join('')) : markup.join('');
  16281. },
  16282. /* _TO_SVG_END_ */
  16283.  
  16284. /**
  16285. * Returns a string representation of this path group
  16286. * @return {String} string representation of an object
  16287. */
  16288. toString: function() {
  16289. return '#<fabric.PathGroup (' + this.complexity() +
  16290. '): { top: ' + this.top + ', left: ' + this.left + ' }>';
  16291. },
  16292.  
  16293. /**
  16294. * Returns true if all paths in this group are of same color
  16295. * @return {Boolean} true if all paths are of the same color (`fill`)
  16296. */
  16297. isSameColor: function() {
  16298. var firstPathFill = (this.getObjects()[0].get('fill') || '').toLowerCase();
  16299. return this.getObjects().every(function(path) {
  16300. return (path.get('fill') || '').toLowerCase() === firstPathFill;
  16301. });
  16302. },
  16303.  
  16304. /**
  16305. * Returns number representation of object's complexity
  16306. * @return {Number} complexity
  16307. */
  16308. complexity: function() {
  16309. return this.paths.reduce(function(total, path) {
  16310. return total + ((path && path.complexity) ? path.complexity() : 0);
  16311. }, 0);
  16312. },
  16313.  
  16314. /**
  16315. * Returns all paths in this path group
  16316. * @return {Array} array of path objects included in this path group
  16317. */
  16318. getObjects: function() {
  16319. return this.paths;
  16320. }
  16321. });
  16322.  
  16323. /**
  16324. * Creates fabric.PathGroup instance from an object representation
  16325. * @static
  16326. * @memberOf fabric.PathGroup
  16327. * @param {Object} object Object to create an instance from
  16328. * @param {Function} callback Callback to invoke when an fabric.PathGroup instance is created
  16329. */
  16330. fabric.PathGroup.fromObject = function(object, callback) {
  16331. if (typeof object.paths === 'string') {
  16332. fabric.loadSVGFromURL(object.paths, function (elements) {
  16333.  
  16334. var pathUrl = object.paths;
  16335. delete object.paths;
  16336.  
  16337. var pathGroup = fabric.util.groupSVGElements(elements, object, pathUrl);
  16338.  
  16339. callback(pathGroup);
  16340. });
  16341. }
  16342. else {
  16343. fabric.util.enlivenObjects(object.paths, function(enlivenedObjects) {
  16344. delete object.paths;
  16345. callback(new fabric.PathGroup(enlivenedObjects, object));
  16346. });
  16347. }
  16348. };
  16349.  
  16350. /**
  16351. * Indicates that instances of this type are async
  16352. * @static
  16353. * @memberOf fabric.PathGroup
  16354. * @type Boolean
  16355. * @default
  16356. */
  16357. fabric.PathGroup.async = true;
  16358.  
  16359. })(typeof exports !== 'undefined' ? exports : this);
  16360.  
  16361.  
  16362. (function(global) {
  16363.  
  16364. 'use strict';
  16365.  
  16366. var fabric = global.fabric || (global.fabric = { }),
  16367. extend = fabric.util.object.extend,
  16368. min = fabric.util.array.min,
  16369. max = fabric.util.array.max,
  16370. invoke = fabric.util.array.invoke;
  16371.  
  16372. if (fabric.Group) {
  16373. return;
  16374. }
  16375.  
  16376. // lock-related properties, for use in fabric.Group#get
  16377. // to enable locking behavior on group
  16378. // when one of its objects has lock-related properties set
  16379. var _lockProperties = {
  16380. lockMovementX: true,
  16381. lockMovementY: true,
  16382. lockRotation: true,
  16383. lockScalingX: true,
  16384. lockScalingY: true,
  16385. lockUniScaling: true
  16386. };
  16387.  
  16388. /**
  16389. * Group class
  16390. * @class fabric.Group
  16391. * @extends fabric.Object
  16392. * @mixes fabric.Collection
  16393. * @tutorial {@link http://fabricjs.com/fabric-intro-part-3/#groups}
  16394. * @see {@link fabric.Group#initialize} for constructor definition
  16395. */
  16396. fabric.Group = fabric.util.createClass(fabric.Object, fabric.Collection, /** @lends fabric.Group.prototype */ {
  16397.  
  16398. /**
  16399. * Type of an object
  16400. * @type String
  16401. * @default
  16402. */
  16403. type: 'group',
  16404.  
  16405. /**
  16406. * Constructor
  16407. * @param {Object} objects Group objects
  16408. * @param {Object} [options] Options object
  16409. * @return {Object} thisArg
  16410. */
  16411. initialize: function(objects, options) {
  16412. options = options || { };
  16413.  
  16414. this._objects = objects || [];
  16415. for (var i = this._objects.length; i--; ) {
  16416. this._objects[i].group = this;
  16417. }
  16418.  
  16419. this.originalState = { };
  16420. this.callSuper('initialize');
  16421.  
  16422. this._calcBounds();
  16423. this._updateObjectsCoords();
  16424.  
  16425. if (options) {
  16426. extend(this, options);
  16427. }
  16428.  
  16429. this.setCoords();
  16430. this.saveCoords();
  16431. },
  16432.  
  16433. /**
  16434. * @private
  16435. */
  16436. _updateObjectsCoords: function() {
  16437. this.forEachObject(this._updateObjectCoords, this);
  16438. },
  16439.  
  16440. /**
  16441. * @private
  16442. */
  16443. _updateObjectCoords: function(object) {
  16444. var objectLeft = object.getLeft(),
  16445. objectTop = object.getTop();
  16446.  
  16447. object.set({
  16448. originalLeft: objectLeft,
  16449. originalTop: objectTop,
  16450. left: objectLeft - this.left,
  16451. top: objectTop - this.top
  16452. });
  16453.  
  16454. object.setCoords();
  16455.  
  16456. // do not display corners of objects enclosed in a group
  16457. object.__origHasControls = object.hasControls;
  16458. object.hasControls = false;
  16459. },
  16460.  
  16461. /**
  16462. * Returns string represenation of a group
  16463. * @return {String}
  16464. */
  16465. toString: function() {
  16466. return '#<fabric.Group: (' + this.complexity() + ')>';
  16467. },
  16468.  
  16469. /**
  16470. * Adds an object to a group; Then recalculates group's dimension, position.
  16471. * @param {Object} object
  16472. * @return {fabric.Group} thisArg
  16473. * @chainable
  16474. */
  16475. addWithUpdate: function(object) {
  16476. this._restoreObjectsState();
  16477. if (object) {
  16478. this._objects.push(object);
  16479. object.group = this;
  16480. }
  16481. // since _restoreObjectsState set objects inactive
  16482. this.forEachObject(this._setObjectActive, this);
  16483. this._calcBounds();
  16484. this._updateObjectsCoords();
  16485. return this;
  16486. },
  16487.  
  16488. /**
  16489. * @private
  16490. */
  16491. _setObjectActive: function(object) {
  16492. object.set('active', true);
  16493. object.group = this;
  16494. },
  16495.  
  16496. /**
  16497. * Removes an object from a group; Then recalculates group's dimension, position.
  16498. * @param {Object} object
  16499. * @return {fabric.Group} thisArg
  16500. * @chainable
  16501. */
  16502. removeWithUpdate: function(object) {
  16503. this._moveFlippedObject(object);
  16504. this._restoreObjectsState();
  16505.  
  16506. // since _restoreObjectsState set objects inactive
  16507. this.forEachObject(this._setObjectActive, this);
  16508.  
  16509. this.remove(object);
  16510. this._calcBounds();
  16511. this._updateObjectsCoords();
  16512.  
  16513. return this;
  16514. },
  16515.  
  16516. /**
  16517. * @private
  16518. */
  16519. _onObjectAdded: function(object) {
  16520. object.group = this;
  16521. },
  16522.  
  16523. /**
  16524. * @private
  16525. */
  16526. _onObjectRemoved: function(object) {
  16527. delete object.group;
  16528. object.set('active', false);
  16529. },
  16530.  
  16531. /**
  16532. * Properties that are delegated to group objects when reading/writing
  16533. * @param {Object} delegatedProperties
  16534. */
  16535. delegatedProperties: {
  16536. fill: true,
  16537. opacity: true,
  16538. fontFamily: true,
  16539. fontWeight: true,
  16540. fontSize: true,
  16541. fontStyle: true,
  16542. lineHeight: true,
  16543. textDecoration: true,
  16544. textAlign: true,
  16545. backgroundColor: true
  16546. },
  16547.  
  16548. /**
  16549. * @private
  16550. */
  16551. _set: function(key, value) {
  16552. if (key in this.delegatedProperties) {
  16553. var i = this._objects.length;
  16554. this[key] = value;
  16555. while (i--) {
  16556. this._objects[i].set(key, value);
  16557. }
  16558. }
  16559. else {
  16560. this[key] = value;
  16561. }
  16562. },
  16563.  
  16564. /**
  16565. * Returns object representation of an instance
  16566. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  16567. * @return {Object} object representation of an instance
  16568. */
  16569. toObject: function(propertiesToInclude) {
  16570. return extend(this.callSuper('toObject', propertiesToInclude), {
  16571. objects: invoke(this._objects, 'toObject', propertiesToInclude)
  16572. });
  16573. },
  16574.  
  16575. /**
  16576. * Renders instance on a given context
  16577. * @param {CanvasRenderingContext2D} ctx context to render instance on
  16578. */
  16579. render: function(ctx) {
  16580. // do not render if object is not visible
  16581. if (!this.visible) {
  16582. return;
  16583. }
  16584.  
  16585. ctx.save();
  16586. this.clipTo && fabric.util.clipContext(this, ctx);
  16587.  
  16588. // the array is now sorted in order of highest first, so start from end
  16589. for (var i = 0, len = this._objects.length; i < len; i++) {
  16590. this._renderObject(this._objects[i], ctx);
  16591. }
  16592.  
  16593. this.clipTo && ctx.restore();
  16594.  
  16595. ctx.restore();
  16596. },
  16597.  
  16598. /**
  16599. * Renders controls and borders for the object
  16600. * @param {CanvasRenderingContext2D} ctx Context to render on
  16601. * @param {Boolean} [noTransform] When true, context is not transformed
  16602. */
  16603. _renderControls: function(ctx, noTransform) {
  16604. this.callSuper('_renderControls', ctx, noTransform);
  16605. for (var i = 0, len = this._objects.length; i < len; i++) {
  16606. this._objects[i]._renderControls(ctx);
  16607. }
  16608. },
  16609.  
  16610. /**
  16611. * @private
  16612. */
  16613. _renderObject: function(object, ctx) {
  16614. var originalHasRotatingPoint = object.hasRotatingPoint;
  16615.  
  16616. // do not render if object is not visible
  16617. if (!object.visible) {
  16618. return;
  16619. }
  16620.  
  16621. object.hasRotatingPoint = false;
  16622.  
  16623. object.render(ctx);
  16624.  
  16625. object.hasRotatingPoint = originalHasRotatingPoint;
  16626. },
  16627.  
  16628. /**
  16629. * Retores original state of each of group objects (original state is that which was before group was created).
  16630. * @private
  16631. * @return {fabric.Group} thisArg
  16632. * @chainable
  16633. */
  16634. _restoreObjectsState: function() {
  16635. this._objects.forEach(this._restoreObjectState, this);
  16636. return this;
  16637. },
  16638.  
  16639. /**
  16640. * Moves a flipped object to the position where it's displayed
  16641. * @private
  16642. * @param {fabric.Object} object
  16643. * @return {fabric.Group} thisArg
  16644. */
  16645. _moveFlippedObject: function(object) {
  16646. var oldOriginX = object.get('originX'),
  16647. oldOriginY = object.get('originY'),
  16648. center = object.getCenterPoint();
  16649.  
  16650. object.set({
  16651. originX: 'center',
  16652. originY: 'center',
  16653. left: center.x,
  16654. top: center.y
  16655. });
  16656.  
  16657. this._toggleFlipping(object);
  16658.  
  16659. var newOrigin = object.getPointByOrigin(oldOriginX, oldOriginY);
  16660.  
  16661. object.set({
  16662. originX: oldOriginX,
  16663. originY: oldOriginY,
  16664. left: newOrigin.x,
  16665. top: newOrigin.y
  16666. });
  16667.  
  16668. return this;
  16669. },
  16670.  
  16671. /**
  16672. * @private
  16673. */
  16674. _toggleFlipping: function(object) {
  16675. if (this.flipX) {
  16676. object.toggle('flipX');
  16677. object.set('left', -object.get('left'));
  16678. object.setAngle(-object.getAngle());
  16679. }
  16680. if (this.flipY) {
  16681. object.toggle('flipY');
  16682. object.set('top', -object.get('top'));
  16683. object.setAngle(-object.getAngle());
  16684. }
  16685. },
  16686.  
  16687. /**
  16688. * Restores original state of a specified object in group
  16689. * @private
  16690. * @param {fabric.Object} object
  16691. * @return {fabric.Group} thisArg
  16692. */
  16693. _restoreObjectState: function(object) {
  16694. this._setObjectPosition(object);
  16695.  
  16696. object.setCoords();
  16697. object.hasControls = object.__origHasControls;
  16698. delete object.__origHasControls;
  16699. object.set('active', false);
  16700. object.setCoords();
  16701. delete object.group;
  16702.  
  16703. return this;
  16704. },
  16705.  
  16706. /**
  16707. * @private
  16708. */
  16709. _setObjectPosition: function(object) {
  16710. var groupLeft = this.getLeft(),
  16711. groupTop = this.getTop(),
  16712. rotated = this._getRotatedLeftTop(object);
  16713.  
  16714. object.set({
  16715. angle: object.getAngle() + this.getAngle(),
  16716. left: groupLeft + rotated.left,
  16717. top: groupTop + rotated.top,
  16718. scaleX: object.get('scaleX') * this.get('scaleX'),
  16719. scaleY: object.get('scaleY') * this.get('scaleY')
  16720. });
  16721. },
  16722.  
  16723. /**
  16724. * @private
  16725. */
  16726. _getRotatedLeftTop: function(object) {
  16727. var groupAngle = this.getAngle() * (Math.PI / 180);
  16728. return {
  16729. left: (-Math.sin(groupAngle) * object.getTop() * this.get('scaleY') +
  16730. Math.cos(groupAngle) * object.getLeft() * this.get('scaleX')),
  16731.  
  16732. top: (Math.cos(groupAngle) * object.getTop() * this.get('scaleY') +
  16733. Math.sin(groupAngle) * object.getLeft() * this.get('scaleX'))
  16734. };
  16735. },
  16736.  
  16737. /**
  16738. * Destroys a group (restoring state of its objects)
  16739. * @return {fabric.Group} thisArg
  16740. * @chainable
  16741. */
  16742. destroy: function() {
  16743. this._objects.forEach(this._moveFlippedObject, this);
  16744. return this._restoreObjectsState();
  16745. },
  16746.  
  16747. /**
  16748. * Saves coordinates of this instance (to be used together with `hasMoved`)
  16749. * @saveCoords
  16750. * @return {fabric.Group} thisArg
  16751. * @chainable
  16752. */
  16753. saveCoords: function() {
  16754. this._originalLeft = this.get('left');
  16755. this._originalTop = this.get('top');
  16756. return this;
  16757. },
  16758.  
  16759. /**
  16760. * Checks whether this group was moved (since `saveCoords` was called last)
  16761. * @return {Boolean} true if an object was moved (since fabric.Group#saveCoords was called)
  16762. */
  16763. hasMoved: function() {
  16764. return this._originalLeft !== this.get('left') ||
  16765. this._originalTop !== this.get('top');
  16766. },
  16767.  
  16768. /**
  16769. * Sets coordinates of all group objects
  16770. * @return {fabric.Group} thisArg
  16771. * @chainable
  16772. */
  16773. setObjectsCoords: function() {
  16774. this.forEachObject(function(object) {
  16775. object.setCoords();
  16776. });
  16777. return this;
  16778. },
  16779.  
  16780. /**
  16781. * @private
  16782. */
  16783. _calcBounds: function(onlyWidthHeight) {
  16784. var aX = [],
  16785. aY = [],
  16786. o;
  16787.  
  16788. for (var i = 0, len = this._objects.length; i < len; ++i) {
  16789. o = this._objects[i];
  16790. o.setCoords();
  16791. for (var prop in o.oCoords) {
  16792. aX.push(o.oCoords[prop].x);
  16793. aY.push(o.oCoords[prop].y);
  16794. }
  16795. }
  16796.  
  16797. this.set(this._getBounds(aX, aY, onlyWidthHeight));
  16798. },
  16799.  
  16800. /**
  16801. * @private
  16802. */
  16803. _getBounds: function(aX, aY, onlyWidthHeight) {
  16804. var ivt = fabric.util.invertTransform(this.getViewportTransform()),
  16805. minXY = fabric.util.transformPoint(new fabric.Point(min(aX), min(aY)), ivt),
  16806. maxXY = fabric.util.transformPoint(new fabric.Point(max(aX), max(aY)), ivt),
  16807. obj = {
  16808. width: (maxXY.x - minXY.x) || 0,
  16809. height: (maxXY.y - minXY.y) || 0
  16810. };
  16811.  
  16812. if (!onlyWidthHeight) {
  16813. obj.left = (minXY.x + maxXY.x) / 2 || 0;
  16814. obj.top = (minXY.y + maxXY.y) / 2 || 0;
  16815. }
  16816. return obj;
  16817. },
  16818.  
  16819. /* _TO_SVG_START_ */
  16820. /**
  16821. * Returns svg representation of an instance
  16822. * @param {Function} [reviver] Method for further parsing of svg representation.
  16823. * @return {String} svg representation of an instance
  16824. */
  16825. toSVG: function(reviver) {
  16826. var markup = [
  16827. //jscs:disable validateIndentation
  16828. '<g ',
  16829. 'transform="', this.getSvgTransform(),
  16830. '">\n'
  16831. //jscs:enable validateIndentation
  16832. ];
  16833.  
  16834. for (var i = 0, len = this._objects.length; i < len; i++) {
  16835. markup.push(this._objects[i].toSVG(reviver));
  16836. }
  16837.  
  16838. markup.push('</g>\n');
  16839.  
  16840. return reviver ? reviver(markup.join('')) : markup.join('');
  16841. },
  16842. /* _TO_SVG_END_ */
  16843.  
  16844. /**
  16845. * Returns requested property
  16846. * @param {String} prop Property to get
  16847. * @return {Any}
  16848. */
  16849. get: function(prop) {
  16850. if (prop in _lockProperties) {
  16851. if (this[prop]) {
  16852. return this[prop];
  16853. }
  16854. else {
  16855. for (var i = 0, len = this._objects.length; i < len; i++) {
  16856. if (this._objects[i][prop]) {
  16857. return true;
  16858. }
  16859. }
  16860. return false;
  16861. }
  16862. }
  16863. else {
  16864. if (prop in this.delegatedProperties) {
  16865. return this._objects[0] && this._objects[0].get(prop);
  16866. }
  16867. return this[prop];
  16868. }
  16869. }
  16870. });
  16871.  
  16872. /**
  16873. * Returns {@link fabric.Group} instance from an object representation
  16874. * @static
  16875. * @memberOf fabric.Group
  16876. * @param {Object} object Object to create a group from
  16877. * @param {Function} [callback] Callback to invoke when an group instance is created
  16878. * @return {fabric.Group} An instance of fabric.Group
  16879. */
  16880. fabric.Group.fromObject = function(object, callback) {
  16881. fabric.util.enlivenObjects(object.objects, function(enlivenedObjects) {
  16882. delete object.objects;
  16883. callback && callback(new fabric.Group(enlivenedObjects, object));
  16884. });
  16885. };
  16886.  
  16887. /**
  16888. * Indicates that instances of this type are async
  16889. * @static
  16890. * @memberOf fabric.Group
  16891. * @type Boolean
  16892. * @default
  16893. */
  16894. fabric.Group.async = true;
  16895.  
  16896. })(typeof exports !== 'undefined' ? exports : this);
  16897.  
  16898.  
  16899. (function(global) {
  16900.  
  16901. 'use strict';
  16902.  
  16903. var extend = fabric.util.object.extend;
  16904.  
  16905. if (!global.fabric) {
  16906. global.fabric = { };
  16907. }
  16908.  
  16909. if (global.fabric.Image) {
  16910. fabric.warn('fabric.Image is already defined.');
  16911. return;
  16912. }
  16913.  
  16914. /**
  16915. * Image class
  16916. * @class fabric.Image
  16917. * @extends fabric.Object
  16918. * @tutorial {@link http://fabricjs.com/fabric-intro-part-1/#images}
  16919. * @see {@link fabric.Image#initialize} for constructor definition
  16920. */
  16921. fabric.Image = fabric.util.createClass(fabric.Object, /** @lends fabric.Image.prototype */ {
  16922.  
  16923. /**
  16924. * Type of an object
  16925. * @type String
  16926. * @default
  16927. */
  16928. type: 'image',
  16929.  
  16930. /**
  16931. * crossOrigin value (one of "", "anonymous", "allow-credentials")
  16932. * @see https://developer.mozilla.org/en-US/docs/HTML/CORS_settings_attributes
  16933. * @type String
  16934. * @default
  16935. */
  16936. crossOrigin: '',
  16937.  
  16938. /**
  16939. * Constructor
  16940. * @param {HTMLImageElement | String} element Image element
  16941. * @param {Object} [options] Options object
  16942. * @return {fabric.Image} thisArg
  16943. */
  16944. initialize: function(element, options) {
  16945. options || (options = { });
  16946.  
  16947. this.filters = [ ];
  16948.  
  16949. this.callSuper('initialize', options);
  16950.  
  16951. this._initElement(element, options);
  16952. this._initConfig(options);
  16953.  
  16954. if (options.filters) {
  16955. this.filters = options.filters;
  16956. this.applyFilters();
  16957. }
  16958. },
  16959.  
  16960. /**
  16961. * Returns image element which this instance if based on
  16962. * @return {HTMLImageElement} Image element
  16963. */
  16964. getElement: function() {
  16965. return this._element;
  16966. },
  16967.  
  16968. /**
  16969. * Sets image element for this instance to a specified one.
  16970. * If filters defined they are applied to new image.
  16971. * You might need to call `canvas.renderAll` and `object.setCoords` after replacing, to render new image and update controls area.
  16972. * @param {HTMLImageElement} element
  16973. * @param {Function} [callback] Callback is invoked when all filters have been applied and new image is generated
  16974. * @return {fabric.Image} thisArg
  16975. * @chainable
  16976. */
  16977. setElement: function(element, callback) {
  16978. this._element = element;
  16979. this._originalElement = element;
  16980. this._initConfig();
  16981.  
  16982. if (this.filters.length !== 0) {
  16983. this.applyFilters(callback);
  16984. }
  16985.  
  16986. return this;
  16987. },
  16988.  
  16989. /**
  16990. * Sets crossOrigin value (on an instance and corresponding image element)
  16991. * @return {fabric.Image} thisArg
  16992. * @chainable
  16993. */
  16994. setCrossOrigin: function(value) {
  16995. this.crossOrigin = value;
  16996. this._element.crossOrigin = value;
  16997.  
  16998. return this;
  16999. },
  17000.  
  17001. /**
  17002. * Returns original size of an image
  17003. * @return {Object} Object with "width" and "height" properties
  17004. */
  17005. getOriginalSize: function() {
  17006. var element = this.getElement();
  17007. return {
  17008. width: element.width,
  17009. height: element.height
  17010. };
  17011. },
  17012.  
  17013. /**
  17014. * @private
  17015. * @param {CanvasRenderingContext2D} ctx Context to render on
  17016. */
  17017. _stroke: function(ctx) {
  17018. ctx.save();
  17019. this._setStrokeStyles(ctx);
  17020. ctx.beginPath();
  17021. ctx.strokeRect(-this.width / 2, -this.height / 2, this.width, this.height);
  17022. ctx.closePath();
  17023. ctx.restore();
  17024. },
  17025.  
  17026. /**
  17027. * @private
  17028. * @param {CanvasRenderingContext2D} ctx Context to render on
  17029. */
  17030. _renderDashedStroke: function(ctx) {
  17031. var x = -this.width / 2,
  17032. y = -this.height / 2,
  17033. w = this.width,
  17034. h = this.height;
  17035.  
  17036. ctx.save();
  17037. this._setStrokeStyles(ctx);
  17038.  
  17039. ctx.beginPath();
  17040. fabric.util.drawDashedLine(ctx, x, y, x + w, y, this.strokeDashArray);
  17041. fabric.util.drawDashedLine(ctx, x + w, y, x + w, y + h, this.strokeDashArray);
  17042. fabric.util.drawDashedLine(ctx, x + w, y + h, x, y + h, this.strokeDashArray);
  17043. fabric.util.drawDashedLine(ctx, x, y + h, x, y, this.strokeDashArray);
  17044. ctx.closePath();
  17045. ctx.restore();
  17046. },
  17047.  
  17048. /**
  17049. * Returns object representation of an instance
  17050. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  17051. * @return {Object} Object representation of an instance
  17052. */
  17053. toObject: function(propertiesToInclude) {
  17054. return extend(this.callSuper('toObject', propertiesToInclude), {
  17055. src: this._originalElement.src || this._originalElement._src,
  17056. filters: this.filters.map(function(filterObj) {
  17057. return filterObj && filterObj.toObject();
  17058. }),
  17059. crossOrigin: this.crossOrigin
  17060. });
  17061. },
  17062.  
  17063. /* _TO_SVG_START_ */
  17064. /**
  17065. * Returns SVG representation of an instance
  17066. * @param {Function} [reviver] Method for further parsing of svg representation.
  17067. * @return {String} svg representation of an instance
  17068. */
  17069. toSVG: function(reviver) {
  17070. var markup = [], x = -this.width / 2, y = -this.height / 2;
  17071. if (this.group && this.group.type === 'path-group') {
  17072. x = this.left;
  17073. y = this.top;
  17074. }
  17075. markup.push(
  17076. '<g transform="', this.getSvgTransform(), this.getSvgTransformMatrix(), '">\n',
  17077. '<image xlink:href="', this.getSvgSrc(),
  17078. '" x="', x, '" y="', y,
  17079. '" style="', this.getSvgStyles(),
  17080. // we're essentially moving origin of transformation from top/left corner to the center of the shape
  17081. // by wrapping it in container <g> element with actual transformation, then offsetting object to the top/left
  17082. // so that object's center aligns with container's left/top
  17083. '" width="', this.width,
  17084. '" height="', this.height,
  17085. '" preserveAspectRatio="none"',
  17086. '></image>\n'
  17087. );
  17088.  
  17089. if (this.stroke || this.strokeDashArray) {
  17090. var origFill = this.fill;
  17091. this.fill = null;
  17092. markup.push(
  17093. '<rect ',
  17094. 'x="', x, '" y="', y,
  17095. '" width="', this.width, '" height="', this.height,
  17096. '" style="', this.getSvgStyles(),
  17097. '"/>\n'
  17098. );
  17099. this.fill = origFill;
  17100. }
  17101.  
  17102. markup.push('</g>\n');
  17103.  
  17104. return reviver ? reviver(markup.join('')) : markup.join('');
  17105. },
  17106. /* _TO_SVG_END_ */
  17107.  
  17108. /**
  17109. * Returns source of an image
  17110. * @return {String} Source of an image
  17111. */
  17112. getSrc: function() {
  17113. if (this.getElement()) {
  17114. return this.getElement().src || this.getElement()._src;
  17115. }
  17116. },
  17117.  
  17118. /**
  17119. * Returns string representation of an instance
  17120. * @return {String} String representation of an instance
  17121. */
  17122. toString: function() {
  17123. return '#<fabric.Image: { src: "' + this.getSrc() + '" }>';
  17124. },
  17125.  
  17126. /**
  17127. * Returns a clone of an instance
  17128. * @param {Function} callback Callback is invoked with a clone as a first argument
  17129. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  17130. */
  17131. clone: function(callback, propertiesToInclude) {
  17132. this.constructor.fromObject(this.toObject(propertiesToInclude), callback);
  17133. },
  17134.  
  17135. /**
  17136. * Applies filters assigned to this image (from "filters" array)
  17137. * @mthod applyFilters
  17138. * @param {Function} callback Callback is invoked when all filters have been applied and new image is generated
  17139. * @return {fabric.Image} thisArg
  17140. * @chainable
  17141. */
  17142. applyFilters: function(callback) {
  17143.  
  17144. if (!this._originalElement) {
  17145. return;
  17146. }
  17147.  
  17148. if (this.filters.length === 0) {
  17149. this._element = this._originalElement;
  17150. callback && callback();
  17151. return;
  17152. }
  17153.  
  17154. var imgEl = this._originalElement,
  17155. canvasEl = fabric.util.createCanvasElement(),
  17156. replacement = fabric.util.createImage(),
  17157. _this = this;
  17158.  
  17159. canvasEl.width = imgEl.width;
  17160. canvasEl.height = imgEl.height;
  17161.  
  17162. canvasEl.getContext('2d').drawImage(imgEl, 0, 0, imgEl.width, imgEl.height);
  17163.  
  17164. this.filters.forEach(function(filter) {
  17165. filter && filter.applyTo(canvasEl);
  17166. });
  17167.  
  17168. /** @ignore */
  17169.  
  17170. replacement.width = imgEl.width;
  17171. replacement.height = imgEl.height;
  17172.  
  17173. if (fabric.isLikelyNode) {
  17174. replacement.src = canvasEl.toBuffer(undefined, fabric.Image.pngCompression);
  17175.  
  17176. // onload doesn't fire in some node versions, so we invoke callback manually
  17177. _this._element = replacement;
  17178. callback && callback();
  17179. }
  17180. else {
  17181. replacement.onload = function() {
  17182. _this._element = replacement;
  17183. callback && callback();
  17184. replacement.onload = canvasEl = imgEl = null;
  17185. };
  17186. replacement.src = canvasEl.toDataURL('image/png');
  17187. }
  17188.  
  17189. return this;
  17190. },
  17191.  
  17192. /**
  17193. * @private
  17194. * @param {CanvasRenderingContext2D} ctx Context to render on
  17195. */
  17196. _render: function(ctx, noTransform) {
  17197. this._element &&
  17198. ctx.drawImage(
  17199. this._element,
  17200. noTransform ? this.left : -this.width/2,
  17201. noTransform ? this.top : -this.height/2,
  17202. this.width,
  17203. this.height
  17204. );
  17205. this._renderStroke(ctx);
  17206. },
  17207.  
  17208. /**
  17209. * @private
  17210. */
  17211. _resetWidthHeight: function() {
  17212. var element = this.getElement();
  17213.  
  17214. this.set('width', element.width);
  17215. this.set('height', element.height);
  17216. },
  17217.  
  17218. /**
  17219. * The Image class's initialization method. This method is automatically
  17220. * called by the constructor.
  17221. * @private
  17222. * @param {HTMLImageElement|String} element The element representing the image
  17223. */
  17224. _initElement: function(element) {
  17225. this.setElement(fabric.util.getById(element));
  17226. fabric.util.addClass(this.getElement(), fabric.Image.CSS_CANVAS);
  17227. },
  17228.  
  17229. /**
  17230. * @private
  17231. * @param {Object} [options] Options object
  17232. */
  17233. _initConfig: function(options) {
  17234. options || (options = { });
  17235. this.setOptions(options);
  17236. this._setWidthHeight(options);
  17237. if (this._element && this.crossOrigin) {
  17238. this._element.crossOrigin = this.crossOrigin;
  17239. }
  17240. },
  17241.  
  17242. /**
  17243. * @private
  17244. * @param {Object} object Object with filters property
  17245. * @param {Function} callback Callback to invoke when all fabric.Image.filters instances are created
  17246. */
  17247. _initFilters: function(object, callback) {
  17248. if (object.filters && object.filters.length) {
  17249. fabric.util.enlivenObjects(object.filters, function(enlivenedObjects) {
  17250. callback && callback(enlivenedObjects);
  17251. }, 'fabric.Image.filters');
  17252. }
  17253. else {
  17254. callback && callback();
  17255. }
  17256. },
  17257.  
  17258. /**
  17259. * @private
  17260. * @param {Object} [options] Object with width/height properties
  17261. */
  17262. _setWidthHeight: function(options) {
  17263. this.width = 'width' in options
  17264. ? options.width
  17265. : (this.getElement()
  17266. ? this.getElement().width || 0
  17267. : 0);
  17268.  
  17269. this.height = 'height' in options
  17270. ? options.height
  17271. : (this.getElement()
  17272. ? this.getElement().height || 0
  17273. : 0);
  17274. },
  17275.  
  17276. /**
  17277. * Returns complexity of an instance
  17278. * @return {Number} complexity of this instance
  17279. */
  17280. complexity: function() {
  17281. return 1;
  17282. }
  17283. });
  17284.  
  17285. /**
  17286. * Default CSS class name for canvas
  17287. * @static
  17288. * @type String
  17289. * @default
  17290. */
  17291. fabric.Image.CSS_CANVAS = 'canvas-img';
  17292.  
  17293. /**
  17294. * Alias for getSrc
  17295. * @static
  17296. */
  17297. fabric.Image.prototype.getSvgSrc = fabric.Image.prototype.getSrc;
  17298.  
  17299. /**
  17300. * Creates an instance of fabric.Image from its object representation
  17301. * @static
  17302. * @param {Object} object Object to create an instance from
  17303. * @param {Function} [callback] Callback to invoke when an image instance is created
  17304. */
  17305. fabric.Image.fromObject = function(object, callback) {
  17306. fabric.util.loadImage(object.src, function(img) {
  17307. fabric.Image.prototype._initFilters.call(object, object, function(filters) {
  17308. object.filters = filters || [ ];
  17309. var instance = new fabric.Image(img, object);
  17310. callback && callback(instance);
  17311. });
  17312. }, null, object.crossOrigin);
  17313. };
  17314.  
  17315. /**
  17316. * Creates an instance of fabric.Image from an URL string
  17317. * @static
  17318. * @param {String} url URL to create an image from
  17319. * @param {Function} [callback] Callback to invoke when image is created (newly created image is passed as a first argument)
  17320. * @param {Object} [imgOptions] Options object
  17321. */
  17322. fabric.Image.fromURL = function(url, callback, imgOptions) {
  17323. fabric.util.loadImage(url, function(img) {
  17324. callback(new fabric.Image(img, imgOptions));
  17325. }, null, imgOptions && imgOptions.crossOrigin);
  17326. };
  17327.  
  17328. /* _FROM_SVG_START_ */
  17329. /**
  17330. * List of attribute names to account for when parsing SVG element (used by {@link fabric.Image.fromElement})
  17331. * @static
  17332. * @see {@link http://www.w3.org/TR/SVG/struct.html#ImageElement}
  17333. */
  17334. fabric.Image.ATTRIBUTE_NAMES = fabric.SHARED_ATTRIBUTES.concat('x y width height xlink:href'.split(' '));
  17335.  
  17336. /**
  17337. * Returns {@link fabric.Image} instance from an SVG element
  17338. * @static
  17339. * @param {SVGElement} element Element to parse
  17340. * @param {Function} callback Callback to execute when fabric.Image object is created
  17341. * @param {Object} [options] Options object
  17342. * @return {fabric.Image} Instance of fabric.Image
  17343. */
  17344. fabric.Image.fromElement = function(element, callback, options) {
  17345. var parsedAttributes = fabric.parseAttributes(element, fabric.Image.ATTRIBUTE_NAMES);
  17346.  
  17347. fabric.Image.fromURL(parsedAttributes['xlink:href'], callback,
  17348. extend((options ? fabric.util.object.clone(options) : { }), parsedAttributes));
  17349. };
  17350. /* _FROM_SVG_END_ */
  17351.  
  17352. /**
  17353. * Indicates that instances of this type are async
  17354. * @static
  17355. * @type Boolean
  17356. * @default
  17357. */
  17358. fabric.Image.async = true;
  17359.  
  17360. /**
  17361. * Indicates compression level used when generating PNG under Node (in applyFilters). Any of 0-9
  17362. * @static
  17363. * @type Number
  17364. * @default
  17365. */
  17366. fabric.Image.pngCompression = 1;
  17367.  
  17368. })(typeof exports !== 'undefined' ? exports : this);
  17369.  
  17370.  
  17371. fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {
  17372.  
  17373. /**
  17374. * @private
  17375. * @return {Number} angle value
  17376. */
  17377. _getAngleValueForStraighten: function() {
  17378. var angle = this.getAngle() % 360;
  17379. if (angle > 0) {
  17380. return Math.round((angle - 1) / 90) * 90;
  17381. }
  17382. return Math.round(angle / 90) * 90;
  17383. },
  17384.  
  17385. /**
  17386. * Straightens an object (rotating it from current angle to one of 0, 90, 180, 270, etc. depending on which is closer)
  17387. * @return {fabric.Object} thisArg
  17388. * @chainable
  17389. */
  17390. straighten: function() {
  17391. this.setAngle(this._getAngleValueForStraighten());
  17392. return this;
  17393. },
  17394.  
  17395. /**
  17396. * Same as {@link fabric.Object.prototype.straighten} but with animation
  17397. * @param {Object} callbacks Object with callback functions
  17398. * @param {Function} [callbacks.onComplete] Invoked on completion
  17399. * @param {Function} [callbacks.onChange] Invoked on every step of animation
  17400. * @return {fabric.Object} thisArg
  17401. * @chainable
  17402. */
  17403. fxStraighten: function(callbacks) {
  17404. callbacks = callbacks || { };
  17405.  
  17406. var empty = function() { },
  17407. onComplete = callbacks.onComplete || empty,
  17408. onChange = callbacks.onChange || empty,
  17409. _this = this;
  17410.  
  17411. fabric.util.animate({
  17412. startValue: this.get('angle'),
  17413. endValue: this._getAngleValueForStraighten(),
  17414. duration: this.FX_DURATION,
  17415. onChange: function(value) {
  17416. _this.setAngle(value);
  17417. onChange();
  17418. },
  17419. onComplete: function() {
  17420. _this.setCoords();
  17421. onComplete();
  17422. },
  17423. onStart: function() {
  17424. _this.set('active', false);
  17425. }
  17426. });
  17427.  
  17428. return this;
  17429. }
  17430. });
  17431.  
  17432. fabric.util.object.extend(fabric.StaticCanvas.prototype, /** @lends fabric.StaticCanvas.prototype */ {
  17433.  
  17434. /**
  17435. * Straightens object, then rerenders canvas
  17436. * @param {fabric.Object} object Object to straighten
  17437. * @return {fabric.Canvas} thisArg
  17438. * @chainable
  17439. */
  17440. straightenObject: function (object) {
  17441. object.straighten();
  17442. this.renderAll();
  17443. return this;
  17444. },
  17445.  
  17446. /**
  17447. * Same as {@link fabric.Canvas.prototype.straightenObject}, but animated
  17448. * @param {fabric.Object} object Object to straighten
  17449. * @return {fabric.Canvas} thisArg
  17450. * @chainable
  17451. */
  17452. fxStraightenObject: function (object) {
  17453. object.fxStraighten({
  17454. onChange: this.renderAll.bind(this)
  17455. });
  17456. return this;
  17457. }
  17458. });
  17459.  
  17460.  
  17461. /**
  17462. * @namespace fabric.Image.filters
  17463. * @memberOf fabric.Image
  17464. * @tutorial {@link http://fabricjs.com/fabric-intro-part-2/#image_filters}
  17465. * @see {@link http://fabricjs.com/image-filters/|ImageFilters demo}
  17466. */
  17467. fabric.Image.filters = fabric.Image.filters || { };
  17468.  
  17469. /**
  17470. * Root filter class from which all filter classes inherit from
  17471. * @class fabric.Image.filters.BaseFilter
  17472. * @memberOf fabric.Image.filters
  17473. */
  17474. fabric.Image.filters.BaseFilter = fabric.util.createClass(/** @lends fabric.Image.filters.BaseFilter.prototype */ {
  17475.  
  17476. /**
  17477. * Filter type
  17478. * @param {String} type
  17479. * @default
  17480. */
  17481. type: 'BaseFilter',
  17482.  
  17483. /**
  17484. * Returns object representation of an instance
  17485. * @return {Object} Object representation of an instance
  17486. */
  17487. toObject: function() {
  17488. return { type: this.type };
  17489. },
  17490.  
  17491. /**
  17492. * Returns a JSON representation of an instance
  17493. * @return {Object} JSON
  17494. */
  17495. toJSON: function() {
  17496. // delegate, not alias
  17497. return this.toObject();
  17498. }
  17499. });
  17500.  
  17501.  
  17502. (function(global) {
  17503.  
  17504. 'use strict';
  17505.  
  17506. var fabric = global.fabric || (global.fabric = { }),
  17507. extend = fabric.util.object.extend;
  17508.  
  17509. /**
  17510. * Brightness filter class
  17511. * @class fabric.Image.filters.Brightness
  17512. * @memberOf fabric.Image.filters
  17513. * @extends fabric.Image.filters.BaseFilter
  17514. * @see {@link fabric.Image.filters.Brightness#initialize} for constructor definition
  17515. * @see {@link http://fabricjs.com/image-filters/|ImageFilters demo}
  17516. * @example
  17517. * var filter = new fabric.Image.filters.Brightness({
  17518. * brightness: 200
  17519. * });
  17520. * object.filters.push(filter);
  17521. * object.applyFilters(canvas.renderAll.bind(canvas));
  17522. */
  17523. fabric.Image.filters.Brightness = fabric.util.createClass(fabric.Image.filters.BaseFilter, /** @lends fabric.Image.filters.Brightness.prototype */ {
  17524.  
  17525. /**
  17526. * Filter type
  17527. * @param {String} type
  17528. * @default
  17529. */
  17530. type: 'Brightness',
  17531.  
  17532. /**
  17533. * Constructor
  17534. * @memberOf fabric.Image.filters.Brightness.prototype
  17535. * @param {Object} [options] Options object
  17536. * @param {Number} [options.brightness=0] Value to brighten the image up (0..255)
  17537. */
  17538. initialize: function(options) {
  17539. options = options || { };
  17540. this.brightness = options.brightness || 0;
  17541. },
  17542.  
  17543. /**
  17544. * Applies filter to canvas element
  17545. * @param {Object} canvasEl Canvas element to apply filter to
  17546. */
  17547. applyTo: function(canvasEl) {
  17548. var context = canvasEl.getContext('2d'),
  17549. imageData = context.getImageData(0, 0, canvasEl.width, canvasEl.height),
  17550. data = imageData.data,
  17551. brightness = this.brightness;
  17552.  
  17553. for (var i = 0, len = data.length; i < len; i += 4) {
  17554. data[i] += brightness;
  17555. data[i + 1] += brightness;
  17556. data[i + 2] += brightness;
  17557. }
  17558.  
  17559. context.putImageData(imageData, 0, 0);
  17560. },
  17561.  
  17562. /**
  17563. * Returns object representation of an instance
  17564. * @return {Object} Object representation of an instance
  17565. */
  17566. toObject: function() {
  17567. return extend(this.callSuper('toObject'), {
  17568. brightness: this.brightness
  17569. });
  17570. }
  17571. });
  17572.  
  17573. /**
  17574. * Returns filter instance from an object representation
  17575. * @static
  17576. * @param {Object} object Object to create an instance from
  17577. * @return {fabric.Image.filters.Brightness} Instance of fabric.Image.filters.Brightness
  17578. */
  17579. fabric.Image.filters.Brightness.fromObject = function(object) {
  17580. return new fabric.Image.filters.Brightness(object);
  17581. };
  17582.  
  17583. })(typeof exports !== 'undefined' ? exports : this);
  17584.  
  17585.  
  17586. (function(global) {
  17587.  
  17588. 'use strict';
  17589.  
  17590. var fabric = global.fabric || (global.fabric = { }),
  17591. extend = fabric.util.object.extend;
  17592.  
  17593. /**
  17594. * Adapted from <a href="http://www.html5rocks.com/en/tutorials/canvas/imagefilters/">html5rocks article</a>
  17595. * @class fabric.Image.filters.Convolute
  17596. * @memberOf fabric.Image.filters
  17597. * @extends fabric.Image.filters.BaseFilter
  17598. * @see {@link fabric.Image.filters.Convolute#initialize} for constructor definition
  17599. * @see {@link http://fabricjs.com/image-filters/|ImageFilters demo}
  17600. * @example <caption>Sharpen filter</caption>
  17601. * var filter = new fabric.Image.filters.Convolute({
  17602. * matrix: [ 0, -1, 0,
  17603. * -1, 5, -1,
  17604. * 0, -1, 0 ]
  17605. * });
  17606. * object.filters.push(filter);
  17607. * object.applyFilters(canvas.renderAll.bind(canvas));
  17608. * @example <caption>Blur filter</caption>
  17609. * var filter = new fabric.Image.filters.Convolute({
  17610. * matrix: [ 1/9, 1/9, 1/9,
  17611. * 1/9, 1/9, 1/9,
  17612. * 1/9, 1/9, 1/9 ]
  17613. * });
  17614. * object.filters.push(filter);
  17615. * object.applyFilters(canvas.renderAll.bind(canvas));
  17616. * @example <caption>Emboss filter</caption>
  17617. * var filter = new fabric.Image.filters.Convolute({
  17618. * matrix: [ 1, 1, 1,
  17619. * 1, 0.7, -1,
  17620. * -1, -1, -1 ]
  17621. * });
  17622. * object.filters.push(filter);
  17623. * object.applyFilters(canvas.renderAll.bind(canvas));
  17624. * @example <caption>Emboss filter with opaqueness</caption>
  17625. * var filter = new fabric.Image.filters.Convolute({
  17626. * opaque: true,
  17627. * matrix: [ 1, 1, 1,
  17628. * 1, 0.7, -1,
  17629. * -1, -1, -1 ]
  17630. * });
  17631. * object.filters.push(filter);
  17632. * object.applyFilters(canvas.renderAll.bind(canvas));
  17633. */
  17634. fabric.Image.filters.Convolute = fabric.util.createClass(fabric.Image.filters.BaseFilter, /** @lends fabric.Image.filters.Convolute.prototype */ {
  17635.  
  17636. /**
  17637. * Filter type
  17638. * @param {String} type
  17639. * @default
  17640. */
  17641. type: 'Convolute',
  17642.  
  17643. /**
  17644. * Constructor
  17645. * @memberOf fabric.Image.filters.Convolute.prototype
  17646. * @param {Object} [options] Options object
  17647. * @param {Boolean} [options.opaque=false] Opaque value (true/false)
  17648. * @param {Array} [options.matrix] Filter matrix
  17649. */
  17650. initialize: function(options) {
  17651. options = options || { };
  17652.  
  17653. this.opaque = options.opaque;
  17654. this.matrix = options.matrix || [
  17655. 0, 0, 0,
  17656. 0, 1, 0,
  17657. 0, 0, 0
  17658. ];
  17659.  
  17660. var canvasEl = fabric.util.createCanvasElement();
  17661. this.tmpCtx = canvasEl.getContext('2d');
  17662. },
  17663.  
  17664. /**
  17665. * @private
  17666. */
  17667. _createImageData: function(w, h) {
  17668. return this.tmpCtx.createImageData(w, h);
  17669. },
  17670.  
  17671. /**
  17672. * Applies filter to canvas element
  17673. * @param {Object} canvasEl Canvas element to apply filter to
  17674. */
  17675. applyTo: function(canvasEl) {
  17676.  
  17677. var weights = this.matrix,
  17678. context = canvasEl.getContext('2d'),
  17679. pixels = context.getImageData(0, 0, canvasEl.width, canvasEl.height),
  17680.  
  17681. side = Math.round(Math.sqrt(weights.length)),
  17682. halfSide = Math.floor(side/2),
  17683. src = pixels.data,
  17684. sw = pixels.width,
  17685. sh = pixels.height,
  17686.  
  17687. // pad output by the convolution matrix
  17688. w = sw,
  17689. h = sh,
  17690. output = this._createImageData(w, h),
  17691.  
  17692. dst = output.data,
  17693.  
  17694. // go through the destination image pixels
  17695. alphaFac = this.opaque ? 1 : 0;
  17696.  
  17697. for (var y = 0; y < h; y++) {
  17698. for (var x = 0; x < w; x++) {
  17699. var sy = y,
  17700. sx = x,
  17701. dstOff = (y * w + x) * 4,
  17702. // calculate the weighed sum of the source image pixels that
  17703. // fall under the convolution matrix
  17704. r = 0, g = 0, b = 0, a = 0;
  17705.  
  17706. for (var cy = 0; cy < side; cy++) {
  17707. for (var cx = 0; cx < side; cx++) {
  17708.  
  17709. var scy = sy + cy - halfSide,
  17710. scx = sx + cx - halfSide;
  17711.  
  17712. /* jshint maxdepth:5 */
  17713. if (scy < 0 || scy > sh || scx < 0 || scx > sw) {
  17714. continue;
  17715. }
  17716.  
  17717. var srcOff = (scy * sw + scx) * 4,
  17718. wt = weights[cy * side + cx];
  17719.  
  17720. r += src[srcOff] * wt;
  17721. g += src[srcOff + 1] * wt;
  17722. b += src[srcOff + 2] * wt;
  17723. a += src[srcOff + 3] * wt;
  17724. }
  17725. }
  17726. dst[dstOff] = r;
  17727. dst[dstOff + 1] = g;
  17728. dst[dstOff + 2] = b;
  17729. dst[dstOff + 3] = a + alphaFac * (255 - a);
  17730. }
  17731. }
  17732.  
  17733. context.putImageData(output, 0, 0);
  17734. },
  17735.  
  17736. /**
  17737. * Returns object representation of an instance
  17738. * @return {Object} Object representation of an instance
  17739. */
  17740. toObject: function() {
  17741. return extend(this.callSuper('toObject'), {
  17742. opaque: this.opaque,
  17743. matrix: this.matrix
  17744. });
  17745. }
  17746. });
  17747.  
  17748. /**
  17749. * Returns filter instance from an object representation
  17750. * @static
  17751. * @param {Object} object Object to create an instance from
  17752. * @return {fabric.Image.filters.Convolute} Instance of fabric.Image.filters.Convolute
  17753. */
  17754. fabric.Image.filters.Convolute.fromObject = function(object) {
  17755. return new fabric.Image.filters.Convolute(object);
  17756. };
  17757.  
  17758. })(typeof exports !== 'undefined' ? exports : this);
  17759.  
  17760.  
  17761. (function(global) {
  17762.  
  17763. 'use strict';
  17764.  
  17765. var fabric = global.fabric || (global.fabric = { }),
  17766. extend = fabric.util.object.extend;
  17767.  
  17768. /**
  17769. * GradientTransparency filter class
  17770. * @class fabric.Image.filters.GradientTransparency
  17771. * @memberOf fabric.Image.filters
  17772. * @extends fabric.Image.filters.BaseFilter
  17773. * @see {@link fabric.Image.filters.GradientTransparency#initialize} for constructor definition
  17774. * @see {@link http://fabricjs.com/image-filters/|ImageFilters demo}
  17775. * @example
  17776. * var filter = new fabric.Image.filters.GradientTransparency({
  17777. * threshold: 200
  17778. * });
  17779. * object.filters.push(filter);
  17780. * object.applyFilters(canvas.renderAll.bind(canvas));
  17781. */
  17782. fabric.Image.filters.GradientTransparency = fabric.util.createClass(fabric.Image.filters.BaseFilter, /** @lends fabric.Image.filters.GradientTransparency.prototype */ {
  17783.  
  17784. /**
  17785. * Filter type
  17786. * @param {String} type
  17787. * @default
  17788. */
  17789. type: 'GradientTransparency',
  17790.  
  17791. /**
  17792. * Constructor
  17793. * @memberOf fabric.Image.filters.GradientTransparency.prototype
  17794. * @param {Object} [options] Options object
  17795. * @param {Number} [options.threshold=100] Threshold value
  17796. */
  17797. initialize: function(options) {
  17798. options = options || { };
  17799. this.threshold = options.threshold || 100;
  17800. },
  17801.  
  17802. /**
  17803. * Applies filter to canvas element
  17804. * @param {Object} canvasEl Canvas element to apply filter to
  17805. */
  17806. applyTo: function(canvasEl) {
  17807. var context = canvasEl.getContext('2d'),
  17808. imageData = context.getImageData(0, 0, canvasEl.width, canvasEl.height),
  17809. data = imageData.data,
  17810. threshold = this.threshold,
  17811. total = data.length;
  17812.  
  17813. for (var i = 0, len = data.length; i < len; i += 4) {
  17814. data[i + 3] = threshold + 255 * (total - i) / total;
  17815. }
  17816.  
  17817. context.putImageData(imageData, 0, 0);
  17818. },
  17819.  
  17820. /**
  17821. * Returns object representation of an instance
  17822. * @return {Object} Object representation of an instance
  17823. */
  17824. toObject: function() {
  17825. return extend(this.callSuper('toObject'), {
  17826. threshold: this.threshold
  17827. });
  17828. }
  17829. });
  17830.  
  17831. /**
  17832. * Returns filter instance from an object representation
  17833. * @static
  17834. * @param {Object} object Object to create an instance from
  17835. * @return {fabric.Image.filters.GradientTransparency} Instance of fabric.Image.filters.GradientTransparency
  17836. */
  17837. fabric.Image.filters.GradientTransparency.fromObject = function(object) {
  17838. return new fabric.Image.filters.GradientTransparency(object);
  17839. };
  17840.  
  17841. })(typeof exports !== 'undefined' ? exports : this);
  17842.  
  17843.  
  17844. (function(global) {
  17845.  
  17846. 'use strict';
  17847.  
  17848. var fabric = global.fabric || (global.fabric = { });
  17849.  
  17850. /**
  17851. * Grayscale image filter class
  17852. * @class fabric.Image.filters.Grayscale
  17853. * @memberOf fabric.Image.filters
  17854. * @extends fabric.Image.filters.BaseFilter
  17855. * @see {@link http://fabricjs.com/image-filters/|ImageFilters demo}
  17856. * @example
  17857. * var filter = new fabric.Image.filters.Grayscale();
  17858. * object.filters.push(filter);
  17859. * object.applyFilters(canvas.renderAll.bind(canvas));
  17860. */
  17861. fabric.Image.filters.Grayscale = fabric.util.createClass(fabric.Image.filters.BaseFilter, /** @lends fabric.Image.filters.Grayscale.prototype */ {
  17862.  
  17863. /**
  17864. * Filter type
  17865. * @param {String} type
  17866. * @default
  17867. */
  17868. type: 'Grayscale',
  17869.  
  17870. /**
  17871. * Applies filter to canvas element
  17872. * @memberOf fabric.Image.filters.Grayscale.prototype
  17873. * @param {Object} canvasEl Canvas element to apply filter to
  17874. */
  17875. applyTo: function(canvasEl) {
  17876. var context = canvasEl.getContext('2d'),
  17877. imageData = context.getImageData(0, 0, canvasEl.width, canvasEl.height),
  17878. data = imageData.data,
  17879. len = imageData.width * imageData.height * 4,
  17880. index = 0,
  17881. average;
  17882.  
  17883. while (index < len) {
  17884. average = (data[index] + data[index + 1] + data[index + 2]) / 3;
  17885. data[index] = average;
  17886. data[index + 1] = average;
  17887. data[index + 2] = average;
  17888. index += 4;
  17889. }
  17890.  
  17891. context.putImageData(imageData, 0, 0);
  17892. }
  17893. });
  17894.  
  17895. /**
  17896. * Returns filter instance from an object representation
  17897. * @static
  17898. * @return {fabric.Image.filters.Grayscale} Instance of fabric.Image.filters.Grayscale
  17899. */
  17900. fabric.Image.filters.Grayscale.fromObject = function() {
  17901. return new fabric.Image.filters.Grayscale();
  17902. };
  17903.  
  17904. })(typeof exports !== 'undefined' ? exports : this);
  17905.  
  17906.  
  17907. (function(global) {
  17908.  
  17909. 'use strict';
  17910.  
  17911. var fabric = global.fabric || (global.fabric = { });
  17912.  
  17913. /**
  17914. * Invert filter class
  17915. * @class fabric.Image.filters.Invert
  17916. * @memberOf fabric.Image.filters
  17917. * @extends fabric.Image.filters.BaseFilter
  17918. * @see {@link http://fabricjs.com/image-filters/|ImageFilters demo}
  17919. * @example
  17920. * var filter = new fabric.Image.filters.Invert();
  17921. * object.filters.push(filter);
  17922. * object.applyFilters(canvas.renderAll.bind(canvas));
  17923. */
  17924. fabric.Image.filters.Invert = fabric.util.createClass(fabric.Image.filters.BaseFilter, /** @lends fabric.Image.filters.Invert.prototype */ {
  17925.  
  17926. /**
  17927. * Filter type
  17928. * @param {String} type
  17929. * @default
  17930. */
  17931. type: 'Invert',
  17932.  
  17933. /**
  17934. * Applies filter to canvas element
  17935. * @memberOf fabric.Image.filters.Invert.prototype
  17936. * @param {Object} canvasEl Canvas element to apply filter to
  17937. */
  17938. applyTo: function(canvasEl) {
  17939. var context = canvasEl.getContext('2d'),
  17940. imageData = context.getImageData(0, 0, canvasEl.width, canvasEl.height),
  17941. data = imageData.data,
  17942. iLen = data.length, i;
  17943.  
  17944. for (i = 0; i < iLen; i+=4) {
  17945. data[i] = 255 - data[i];
  17946. data[i + 1] = 255 - data[i + 1];
  17947. data[i + 2] = 255 - data[i + 2];
  17948. }
  17949.  
  17950. context.putImageData(imageData, 0, 0);
  17951. }
  17952. });
  17953.  
  17954. /**
  17955. * Returns filter instance from an object representation
  17956. * @static
  17957. * @return {fabric.Image.filters.Invert} Instance of fabric.Image.filters.Invert
  17958. */
  17959. fabric.Image.filters.Invert.fromObject = function() {
  17960. return new fabric.Image.filters.Invert();
  17961. };
  17962.  
  17963. })(typeof exports !== 'undefined' ? exports : this);
  17964.  
  17965.  
  17966. (function(global) {
  17967.  
  17968. 'use strict';
  17969.  
  17970. var fabric = global.fabric || (global.fabric = { }),
  17971. extend = fabric.util.object.extend;
  17972.  
  17973. /**
  17974. * Mask filter class
  17975. * See http://resources.aleph-1.com/mask/
  17976. * @class fabric.Image.filters.Mask
  17977. * @memberOf fabric.Image.filters
  17978. * @extends fabric.Image.filters.BaseFilter
  17979. * @see {@link fabric.Image.filters.Mask#initialize} for constructor definition
  17980. */
  17981. fabric.Image.filters.Mask = fabric.util.createClass(fabric.Image.filters.BaseFilter, /** @lends fabric.Image.filters.Mask.prototype */ {
  17982.  
  17983. /**
  17984. * Filter type
  17985. * @param {String} type
  17986. * @default
  17987. */
  17988. type: 'Mask',
  17989.  
  17990. /**
  17991. * Constructor
  17992. * @memberOf fabric.Image.filters.Mask.prototype
  17993. * @param {Object} [options] Options object
  17994. * @param {fabric.Image} [options.mask] Mask image object
  17995. * @param {Number} [options.channel=0] Rgb channel (0, 1, 2 or 3)
  17996. */
  17997. initialize: function(options) {
  17998. options = options || { };
  17999.  
  18000. this.mask = options.mask;
  18001. this.channel = [ 0, 1, 2, 3 ].indexOf(options.channel) > -1 ? options.channel : 0;
  18002. },
  18003.  
  18004. /**
  18005. * Applies filter to canvas element
  18006. * @param {Object} canvasEl Canvas element to apply filter to
  18007. */
  18008. applyTo: function(canvasEl) {
  18009. if (!this.mask) {
  18010. return;
  18011. }
  18012.  
  18013. var context = canvasEl.getContext('2d'),
  18014. imageData = context.getImageData(0, 0, canvasEl.width, canvasEl.height),
  18015. data = imageData.data,
  18016. maskEl = this.mask.getElement(),
  18017. maskCanvasEl = fabric.util.createCanvasElement(),
  18018. channel = this.channel,
  18019. i,
  18020. iLen = imageData.width * imageData.height * 4;
  18021.  
  18022. maskCanvasEl.width = maskEl.width;
  18023. maskCanvasEl.height = maskEl.height;
  18024.  
  18025. maskCanvasEl.getContext('2d').drawImage(maskEl, 0, 0, maskEl.width, maskEl.height);
  18026.  
  18027. var maskImageData = maskCanvasEl.getContext('2d').getImageData(0, 0, maskEl.width, maskEl.height),
  18028. maskData = maskImageData.data;
  18029.  
  18030. for (i = 0; i < iLen; i += 4) {
  18031. data[i + 3] = maskData[i + channel];
  18032. }
  18033.  
  18034. context.putImageData(imageData, 0, 0);
  18035. },
  18036.  
  18037. /**
  18038. * Returns object representation of an instance
  18039. * @return {Object} Object representation of an instance
  18040. */
  18041. toObject: function() {
  18042. return extend(this.callSuper('toObject'), {
  18043. mask: this.mask.toObject(),
  18044. channel: this.channel
  18045. });
  18046. }
  18047. });
  18048.  
  18049. /**
  18050. * Returns filter instance from an object representation
  18051. * @static
  18052. * @param {Object} object Object to create an instance from
  18053. * @param {Function} [callback] Callback to invoke when a mask filter instance is created
  18054. */
  18055. fabric.Image.filters.Mask.fromObject = function(object, callback) {
  18056. fabric.util.loadImage(object.mask.src, function(img) {
  18057. object.mask = new fabric.Image(img, object.mask);
  18058. callback && callback(new fabric.Image.filters.Mask(object));
  18059. });
  18060. };
  18061.  
  18062. /**
  18063. * Indicates that instances of this type are async
  18064. * @static
  18065. * @type Boolean
  18066. * @default
  18067. */
  18068. fabric.Image.filters.Mask.async = true;
  18069.  
  18070. })(typeof exports !== 'undefined' ? exports : this);
  18071.  
  18072.  
  18073. (function(global) {
  18074.  
  18075. 'use strict';
  18076.  
  18077. var fabric = global.fabric || (global.fabric = { }),
  18078. extend = fabric.util.object.extend;
  18079.  
  18080. /**
  18081. * Noise filter class
  18082. * @class fabric.Image.filters.Noise
  18083. * @memberOf fabric.Image.filters
  18084. * @extends fabric.Image.filters.BaseFilter
  18085. * @see {@link fabric.Image.filters.Noise#initialize} for constructor definition
  18086. * @see {@link http://fabricjs.com/image-filters/|ImageFilters demo}
  18087. * @example
  18088. * var filter = new fabric.Image.filters.Noise({
  18089. * noise: 700
  18090. * });
  18091. * object.filters.push(filter);
  18092. * object.applyFilters(canvas.renderAll.bind(canvas));
  18093. */
  18094. fabric.Image.filters.Noise = fabric.util.createClass(fabric.Image.filters.BaseFilter, /** @lends fabric.Image.filters.Noise.prototype */ {
  18095.  
  18096. /**
  18097. * Filter type
  18098. * @param {String} type
  18099. * @default
  18100. */
  18101. type: 'Noise',
  18102.  
  18103. /**
  18104. * Constructor
  18105. * @memberOf fabric.Image.filters.Noise.prototype
  18106. * @param {Object} [options] Options object
  18107. * @param {Number} [options.noise=0] Noise value
  18108. */
  18109. initialize: function(options) {
  18110. options = options || { };
  18111. this.noise = options.noise || 0;
  18112. },
  18113.  
  18114. /**
  18115. * Applies filter to canvas element
  18116. * @param {Object} canvasEl Canvas element to apply filter to
  18117. */
  18118. applyTo: function(canvasEl) {
  18119. var context = canvasEl.getContext('2d'),
  18120. imageData = context.getImageData(0, 0, canvasEl.width, canvasEl.height),
  18121. data = imageData.data,
  18122. noise = this.noise, rand;
  18123.  
  18124. for (var i = 0, len = data.length; i < len; i += 4) {
  18125.  
  18126. rand = (0.5 - Math.random()) * noise;
  18127.  
  18128. data[i] += rand;
  18129. data[i + 1] += rand;
  18130. data[i + 2] += rand;
  18131. }
  18132.  
  18133. context.putImageData(imageData, 0, 0);
  18134. },
  18135.  
  18136. /**
  18137. * Returns object representation of an instance
  18138. * @return {Object} Object representation of an instance
  18139. */
  18140. toObject: function() {
  18141. return extend(this.callSuper('toObject'), {
  18142. noise: this.noise
  18143. });
  18144. }
  18145. });
  18146.  
  18147. /**
  18148. * Returns filter instance from an object representation
  18149. * @static
  18150. * @param {Object} object Object to create an instance from
  18151. * @return {fabric.Image.filters.Noise} Instance of fabric.Image.filters.Noise
  18152. */
  18153. fabric.Image.filters.Noise.fromObject = function(object) {
  18154. return new fabric.Image.filters.Noise(object);
  18155. };
  18156.  
  18157. })(typeof exports !== 'undefined' ? exports : this);
  18158.  
  18159.  
  18160. (function(global) {
  18161.  
  18162. 'use strict';
  18163.  
  18164. var fabric = global.fabric || (global.fabric = { }),
  18165. extend = fabric.util.object.extend;
  18166.  
  18167. /**
  18168. * Pixelate filter class
  18169. * @class fabric.Image.filters.Pixelate
  18170. * @memberOf fabric.Image.filters
  18171. * @extends fabric.Image.filters.BaseFilter
  18172. * @see {@link fabric.Image.filters.Pixelate#initialize} for constructor definition
  18173. * @see {@link http://fabricjs.com/image-filters/|ImageFilters demo}
  18174. * @example
  18175. * var filter = new fabric.Image.filters.Pixelate({
  18176. * blocksize: 8
  18177. * });
  18178. * object.filters.push(filter);
  18179. * object.applyFilters(canvas.renderAll.bind(canvas));
  18180. */
  18181. fabric.Image.filters.Pixelate = fabric.util.createClass(fabric.Image.filters.BaseFilter, /** @lends fabric.Image.filters.Pixelate.prototype */ {
  18182.  
  18183. /**
  18184. * Filter type
  18185. * @param {String} type
  18186. * @default
  18187. */
  18188. type: 'Pixelate',
  18189.  
  18190. /**
  18191. * Constructor
  18192. * @memberOf fabric.Image.filters.Pixelate.prototype
  18193. * @param {Object} [options] Options object
  18194. * @param {Number} [options.blocksize=4] Blocksize for pixelate
  18195. */
  18196. initialize: function(options) {
  18197. options = options || { };
  18198. this.blocksize = options.blocksize || 4;
  18199. },
  18200.  
  18201. /**
  18202. * Applies filter to canvas element
  18203. * @param {Object} canvasEl Canvas element to apply filter to
  18204. */
  18205. applyTo: function(canvasEl) {
  18206. var context = canvasEl.getContext('2d'),
  18207. imageData = context.getImageData(0, 0, canvasEl.width, canvasEl.height),
  18208. data = imageData.data,
  18209. iLen = imageData.height,
  18210. jLen = imageData.width,
  18211. index, i, j, r, g, b, a;
  18212.  
  18213. for (i = 0; i < iLen; i += this.blocksize) {
  18214. for (j = 0; j < jLen; j += this.blocksize) {
  18215.  
  18216. index = (i * 4) * jLen + (j * 4);
  18217.  
  18218. r = data[index];
  18219. g = data[index + 1];
  18220. b = data[index + 2];
  18221. a = data[index + 3];
  18222.  
  18223. /*
  18224. blocksize: 4
  18225.  
  18226. [1,x,x,x,1]
  18227. [x,x,x,x,1]
  18228. [x,x,x,x,1]
  18229. [x,x,x,x,1]
  18230. [1,1,1,1,1]
  18231. */
  18232.  
  18233. for (var _i = i, _ilen = i + this.blocksize; _i < _ilen; _i++) {
  18234. for (var _j = j, _jlen = j + this.blocksize; _j < _jlen; _j++) {
  18235. index = (_i * 4) * jLen + (_j * 4);
  18236. data[index] = r;
  18237. data[index + 1] = g;
  18238. data[index + 2] = b;
  18239. data[index + 3] = a;
  18240. }
  18241. }
  18242. }
  18243. }
  18244.  
  18245. context.putImageData(imageData, 0, 0);
  18246. },
  18247.  
  18248. /**
  18249. * Returns object representation of an instance
  18250. * @return {Object} Object representation of an instance
  18251. */
  18252. toObject: function() {
  18253. return extend(this.callSuper('toObject'), {
  18254. blocksize: this.blocksize
  18255. });
  18256. }
  18257. });
  18258.  
  18259. /**
  18260. * Returns filter instance from an object representation
  18261. * @static
  18262. * @param {Object} object Object to create an instance from
  18263. * @return {fabric.Image.filters.Pixelate} Instance of fabric.Image.filters.Pixelate
  18264. */
  18265. fabric.Image.filters.Pixelate.fromObject = function(object) {
  18266. return new fabric.Image.filters.Pixelate(object);
  18267. };
  18268.  
  18269. })(typeof exports !== 'undefined' ? exports : this);
  18270.  
  18271.  
  18272. (function(global) {
  18273.  
  18274. 'use strict';
  18275.  
  18276. var fabric = global.fabric || (global.fabric = { }),
  18277. extend = fabric.util.object.extend;
  18278.  
  18279. /**
  18280. * Remove white filter class
  18281. * @class fabric.Image.filters.RemoveWhite
  18282. * @memberOf fabric.Image.filters
  18283. * @extends fabric.Image.filters.BaseFilter
  18284. * @see {@link fabric.Image.filters.RemoveWhite#initialize} for constructor definition
  18285. * @see {@link http://fabricjs.com/image-filters/|ImageFilters demo}
  18286. * @example
  18287. * var filter = new fabric.Image.filters.RemoveWhite({
  18288. * threshold: 40,
  18289. * distance: 140
  18290. * });
  18291. * object.filters.push(filter);
  18292. * object.applyFilters(canvas.renderAll.bind(canvas));
  18293. */
  18294. fabric.Image.filters.RemoveWhite = fabric.util.createClass(fabric.Image.filters.BaseFilter, /** @lends fabric.Image.filters.RemoveWhite.prototype */ {
  18295.  
  18296. /**
  18297. * Filter type
  18298. * @param {String} type
  18299. * @default
  18300. */
  18301. type: 'RemoveWhite',
  18302.  
  18303. /**
  18304. * Constructor
  18305. * @memberOf fabric.Image.filters.RemoveWhite.prototype
  18306. * @param {Object} [options] Options object
  18307. * @param {Number} [options.threshold=30] Threshold value
  18308. * @param {Number} [options.distance=20] Distance value
  18309. */
  18310. initialize: function(options) {
  18311. options = options || { };
  18312. this.threshold = options.threshold || 30;
  18313. this.distance = options.distance || 20;
  18314. },
  18315.  
  18316. /**
  18317. * Applies filter to canvas element
  18318. * @param {Object} canvasEl Canvas element to apply filter to
  18319. */
  18320. applyTo: function(canvasEl) {
  18321. var context = canvasEl.getContext('2d'),
  18322. imageData = context.getImageData(0, 0, canvasEl.width, canvasEl.height),
  18323. data = imageData.data,
  18324. threshold = this.threshold,
  18325. distance = this.distance,
  18326. limit = 255 - threshold,
  18327. abs = Math.abs,
  18328. r, g, b;
  18329.  
  18330. for (var i = 0, len = data.length; i < len; i += 4) {
  18331. r = data[i];
  18332. g = data[i + 1];
  18333. b = data[i + 2];
  18334.  
  18335. if (r > limit &&
  18336. g > limit &&
  18337. b > limit &&
  18338. abs(r - g) < distance &&
  18339. abs(r - b) < distance &&
  18340. abs(g - b) < distance
  18341. ) {
  18342. data[i + 3] = 1;
  18343. }
  18344. }
  18345.  
  18346. context.putImageData(imageData, 0, 0);
  18347. },
  18348.  
  18349. /**
  18350. * Returns object representation of an instance
  18351. * @return {Object} Object representation of an instance
  18352. */
  18353. toObject: function() {
  18354. return extend(this.callSuper('toObject'), {
  18355. threshold: this.threshold,
  18356. distance: this.distance
  18357. });
  18358. }
  18359. });
  18360.  
  18361. /**
  18362. * Returns filter instance from an object representation
  18363. * @static
  18364. * @param {Object} object Object to create an instance from
  18365. * @return {fabric.Image.filters.RemoveWhite} Instance of fabric.Image.filters.RemoveWhite
  18366. */
  18367. fabric.Image.filters.RemoveWhite.fromObject = function(object) {
  18368. return new fabric.Image.filters.RemoveWhite(object);
  18369. };
  18370.  
  18371. })(typeof exports !== 'undefined' ? exports : this);
  18372.  
  18373.  
  18374. (function(global) {
  18375.  
  18376. 'use strict';
  18377.  
  18378. var fabric = global.fabric || (global.fabric = { });
  18379.  
  18380. /**
  18381. * Sepia filter class
  18382. * @class fabric.Image.filters.Sepia
  18383. * @memberOf fabric.Image.filters
  18384. * @extends fabric.Image.filters.BaseFilter
  18385. * @see {@link http://fabricjs.com/image-filters/|ImageFilters demo}
  18386. * @example
  18387. * var filter = new fabric.Image.filters.Sepia();
  18388. * object.filters.push(filter);
  18389. * object.applyFilters(canvas.renderAll.bind(canvas));
  18390. */
  18391. fabric.Image.filters.Sepia = fabric.util.createClass(fabric.Image.filters.BaseFilter, /** @lends fabric.Image.filters.Sepia.prototype */ {
  18392.  
  18393. /**
  18394. * Filter type
  18395. * @param {String} type
  18396. * @default
  18397. */
  18398. type: 'Sepia',
  18399.  
  18400. /**
  18401. * Applies filter to canvas element
  18402. * @memberOf fabric.Image.filters.Sepia.prototype
  18403. * @param {Object} canvasEl Canvas element to apply filter to
  18404. */
  18405. applyTo: function(canvasEl) {
  18406. var context = canvasEl.getContext('2d'),
  18407. imageData = context.getImageData(0, 0, canvasEl.width, canvasEl.height),
  18408. data = imageData.data,
  18409. iLen = data.length, i, avg;
  18410.  
  18411. for (i = 0; i < iLen; i+=4) {
  18412. avg = 0.3 * data[i] + 0.59 * data[i + 1] + 0.11 * data[i + 2];
  18413. data[i] = avg + 100;
  18414. data[i + 1] = avg + 50;
  18415. data[i + 2] = avg + 255;
  18416. }
  18417.  
  18418. context.putImageData(imageData, 0, 0);
  18419. }
  18420. });
  18421.  
  18422. /**
  18423. * Returns filter instance from an object representation
  18424. * @static
  18425. * @return {fabric.Image.filters.Sepia} Instance of fabric.Image.filters.Sepia
  18426. */
  18427. fabric.Image.filters.Sepia.fromObject = function() {
  18428. return new fabric.Image.filters.Sepia();
  18429. };
  18430.  
  18431. })(typeof exports !== 'undefined' ? exports : this);
  18432.  
  18433.  
  18434. (function(global) {
  18435.  
  18436. 'use strict';
  18437.  
  18438. var fabric = global.fabric || (global.fabric = { });
  18439.  
  18440. /**
  18441. * Sepia2 filter class
  18442. * @class fabric.Image.filters.Sepia2
  18443. * @memberOf fabric.Image.filters
  18444. * @extends fabric.Image.filters.BaseFilter
  18445. * @see {@link http://fabricjs.com/image-filters/|ImageFilters demo}
  18446. * @example
  18447. * var filter = new fabric.Image.filters.Sepia2();
  18448. * object.filters.push(filter);
  18449. * object.applyFilters(canvas.renderAll.bind(canvas));
  18450. */
  18451. fabric.Image.filters.Sepia2 = fabric.util.createClass(fabric.Image.filters.BaseFilter, /** @lends fabric.Image.filters.Sepia2.prototype */ {
  18452.  
  18453. /**
  18454. * Filter type
  18455. * @param {String} type
  18456. * @default
  18457. */
  18458. type: 'Sepia2',
  18459.  
  18460. /**
  18461. * Applies filter to canvas element
  18462. * @memberOf fabric.Image.filters.Sepia.prototype
  18463. * @param {Object} canvasEl Canvas element to apply filter to
  18464. */
  18465. applyTo: function(canvasEl) {
  18466. var context = canvasEl.getContext('2d'),
  18467. imageData = context.getImageData(0, 0, canvasEl.width, canvasEl.height),
  18468. data = imageData.data,
  18469. iLen = data.length, i, r, g, b;
  18470.  
  18471. for (i = 0; i < iLen; i+=4) {
  18472. r = data[i];
  18473. g = data[i + 1];
  18474. b = data[i + 2];
  18475.  
  18476. data[i] = (r * 0.393 + g * 0.769 + b * 0.189 ) / 1.351;
  18477. data[i + 1] = (r * 0.349 + g * 0.686 + b * 0.168 ) / 1.203;
  18478. data[i + 2] = (r * 0.272 + g * 0.534 + b * 0.131 ) / 2.140;
  18479. }
  18480.  
  18481. context.putImageData(imageData, 0, 0);
  18482. }
  18483. });
  18484.  
  18485. /**
  18486. * Returns filter instance from an object representation
  18487. * @static
  18488. * @return {fabric.Image.filters.Sepia2} Instance of fabric.Image.filters.Sepia2
  18489. */
  18490. fabric.Image.filters.Sepia2.fromObject = function() {
  18491. return new fabric.Image.filters.Sepia2();
  18492. };
  18493.  
  18494. })(typeof exports !== 'undefined' ? exports : this);
  18495.  
  18496.  
  18497. (function(global) {
  18498.  
  18499. 'use strict';
  18500.  
  18501. var fabric = global.fabric || (global.fabric = { }),
  18502. extend = fabric.util.object.extend;
  18503.  
  18504. /**
  18505. * Tint filter class
  18506. * Adapted from <a href="https://github.com/mezzoblue/PaintbrushJS">https://github.com/mezzoblue/PaintbrushJS</a>
  18507. * @class fabric.Image.filters.Tint
  18508. * @memberOf fabric.Image.filters
  18509. * @extends fabric.Image.filters.BaseFilter
  18510. * @see {@link fabric.Image.filters.Tint#initialize} for constructor definition
  18511. * @see {@link http://fabricjs.com/image-filters/|ImageFilters demo}
  18512. * @example <caption>Tint filter with hex color and opacity</caption>
  18513. * var filter = new fabric.Image.filters.Tint({
  18514. * color: '#3513B0',
  18515. * opacity: 0.5
  18516. * });
  18517. * object.filters.push(filter);
  18518. * object.applyFilters(canvas.renderAll.bind(canvas));
  18519. * @example <caption>Tint filter with rgba color</caption>
  18520. * var filter = new fabric.Image.filters.Tint({
  18521. * color: 'rgba(53, 21, 176, 0.5)'
  18522. * });
  18523. * object.filters.push(filter);
  18524. * object.applyFilters(canvas.renderAll.bind(canvas));
  18525. */
  18526. fabric.Image.filters.Tint = fabric.util.createClass(fabric.Image.filters.BaseFilter, /** @lends fabric.Image.filters.Tint.prototype */ {
  18527.  
  18528. /**
  18529. * Filter type
  18530. * @param {String} type
  18531. * @default
  18532. */
  18533. type: 'Tint',
  18534.  
  18535. /**
  18536. * Constructor
  18537. * @memberOf fabric.Image.filters.Tint.prototype
  18538. * @param {Object} [options] Options object
  18539. * @param {String} [options.color=#000000] Color to tint the image with
  18540. * @param {Number} [options.opacity] Opacity value that controls the tint effect's transparency (0..1)
  18541. */
  18542. initialize: function(options) {
  18543. options = options || { };
  18544.  
  18545. this.color = options.color || '#000000';
  18546. this.opacity = typeof options.opacity !== 'undefined'
  18547. ? options.opacity
  18548. : new fabric.Color(this.color).getAlpha();
  18549. },
  18550.  
  18551. /**
  18552. * Applies filter to canvas element
  18553. * @param {Object} canvasEl Canvas element to apply filter to
  18554. */
  18555. applyTo: function(canvasEl) {
  18556. var context = canvasEl.getContext('2d'),
  18557. imageData = context.getImageData(0, 0, canvasEl.width, canvasEl.height),
  18558. data = imageData.data,
  18559. iLen = data.length, i,
  18560. tintR, tintG, tintB,
  18561. r, g, b, alpha1,
  18562. source;
  18563.  
  18564. source = new fabric.Color(this.color).getSource();
  18565.  
  18566. tintR = source[0] * this.opacity;
  18567. tintG = source[1] * this.opacity;
  18568. tintB = source[2] * this.opacity;
  18569.  
  18570. alpha1 = 1 - this.opacity;
  18571.  
  18572. for (i = 0; i < iLen; i+=4) {
  18573. r = data[i];
  18574. g = data[i + 1];
  18575. b = data[i + 2];
  18576.  
  18577. // alpha compositing
  18578. data[i] = tintR + r * alpha1;
  18579. data[i + 1] = tintG + g * alpha1;
  18580. data[i + 2] = tintB + b * alpha1;
  18581. }
  18582.  
  18583. context.putImageData(imageData, 0, 0);
  18584. },
  18585.  
  18586. /**
  18587. * Returns object representation of an instance
  18588. * @return {Object} Object representation of an instance
  18589. */
  18590. toObject: function() {
  18591. return extend(this.callSuper('toObject'), {
  18592. color: this.color,
  18593. opacity: this.opacity
  18594. });
  18595. }
  18596. });
  18597.  
  18598. /**
  18599. * Returns filter instance from an object representation
  18600. * @static
  18601. * @param {Object} object Object to create an instance from
  18602. * @return {fabric.Image.filters.Tint} Instance of fabric.Image.filters.Tint
  18603. */
  18604. fabric.Image.filters.Tint.fromObject = function(object) {
  18605. return new fabric.Image.filters.Tint(object);
  18606. };
  18607.  
  18608. })(typeof exports !== 'undefined' ? exports : this);
  18609.  
  18610.  
  18611. (function(global) {
  18612.  
  18613. 'use strict';
  18614.  
  18615. var fabric = global.fabric || (global.fabric = { }),
  18616. extend = fabric.util.object.extend;
  18617.  
  18618. /**
  18619. * Multiply filter class
  18620. * Adapted from <a href="http://www.laurenscorijn.com/articles/colormath-basics">http://www.laurenscorijn.com/articles/colormath-basics</a>
  18621. * @class fabric.Image.filters.Multiply
  18622. * @memberOf fabric.Image.filters
  18623. * @extends fabric.Image.filters.BaseFilter
  18624. * @example <caption>Multiply filter with hex color</caption>
  18625. * var filter = new fabric.Image.filters.Multiply({
  18626. * color: '#F0F'
  18627. * });
  18628. * object.filters.push(filter);
  18629. * object.applyFilters(canvas.renderAll.bind(canvas));
  18630. * @example <caption>Multiply filter with rgb color</caption>
  18631. * var filter = new fabric.Image.filters.Multiply({
  18632. * color: 'rgb(53, 21, 176)'
  18633. * });
  18634. * object.filters.push(filter);
  18635. * object.applyFilters(canvas.renderAll.bind(canvas));
  18636. */
  18637. fabric.Image.filters.Multiply = fabric.util.createClass(fabric.Image.filters.BaseFilter, /** @lends fabric.Image.filters.Multiply.prototype */ {
  18638.  
  18639. /**
  18640. * Filter type
  18641. * @param {String} type
  18642. * @default
  18643. */
  18644. type: 'Multiply',
  18645.  
  18646. /**
  18647. * Constructor
  18648. * @memberOf fabric.Image.filters.Multiply.prototype
  18649. * @param {Object} [options] Options object
  18650. * @param {String} [options.color=#000000] Color to multiply the image pixels with
  18651. */
  18652. initialize: function(options) {
  18653. options = options || { };
  18654.  
  18655. this.color = options.color || '#000000';
  18656. },
  18657.  
  18658. /**
  18659. * Applies filter to canvas element
  18660. * @param {Object} canvasEl Canvas element to apply filter to
  18661. */
  18662. applyTo: function(canvasEl) {
  18663. var context = canvasEl.getContext('2d'),
  18664. imageData = context.getImageData(0, 0, canvasEl.width, canvasEl.height),
  18665. data = imageData.data,
  18666. iLen = data.length, i,
  18667. source;
  18668.  
  18669. source = new fabric.Color(this.color).getSource();
  18670.  
  18671. for (i = 0; i < iLen; i+=4) {
  18672. data[i] *= source[0] / 255;
  18673. data[i + 1] *= source[1] / 255;
  18674. data[i + 2] *= source[2] / 255;
  18675. }
  18676.  
  18677. context.putImageData(imageData, 0, 0);
  18678. },
  18679.  
  18680. /**
  18681. * Returns object representation of an instance
  18682. * @return {Object} Object representation of an instance
  18683. */
  18684. toObject: function() {
  18685. return extend(this.callSuper('toObject'), {
  18686. color: this.color
  18687. });
  18688. }
  18689. });
  18690.  
  18691. /**
  18692. * Returns filter instance from an object representation
  18693. * @static
  18694. * @param {Object} object Object to create an instance from
  18695. * @return {fabric.Image.filters.Multiply} Instance of fabric.Image.filters.Multiply
  18696. */
  18697. fabric.Image.filters.Multiply.fromObject = function(object) {
  18698. return new fabric.Image.filters.Multiply(object);
  18699. };
  18700.  
  18701. })(typeof exports !== 'undefined' ? exports : this);
  18702.  
  18703.  
  18704. (function(global) {
  18705. 'use strict';
  18706.  
  18707. var fabric = global.fabric;
  18708.  
  18709. /**
  18710. * Color Blend filter class
  18711. * @class fabric.Image.filter.Blend
  18712. * @memberOf fabric.Image.filters
  18713. * @extends fabric.Image.filters.BaseFilter
  18714. * @example
  18715. * var filter = new fabric.Image.filters.Blend({
  18716. * color: '#000',
  18717. * mode: 'multiply'
  18718. * });
  18719. *
  18720. * var filter = new fabric.Image.filters.Blend({
  18721. * image: fabricImageObject,
  18722. * mode: 'multiply',
  18723. * alpha: 0.5
  18724. * });
  18725.  
  18726. * object.filters.push(filter);
  18727. * object.applyFilters(canvas.renderAll.bind(canvas));
  18728. */
  18729. fabric.Image.filters.Blend = fabric.util.createClass({
  18730. type: 'Blend',
  18731.  
  18732. initialize: function(options) {
  18733. options = options || {};
  18734. this.color = options.color || '#000';
  18735. this.image = options.image || false;
  18736. this.mode = options.mode || 'multiply';
  18737. this.alpha = options.alpha || 1;
  18738. },
  18739.  
  18740. applyTo: function(canvasEl) {
  18741. var context = canvasEl.getContext('2d'),
  18742. imageData = context.getImageData(0, 0, canvasEl.width, canvasEl.height),
  18743. data = imageData.data,
  18744. tr, tg, tb,
  18745. r, g, b,
  18746. source,
  18747. isImage = false;
  18748.  
  18749. if (this.image) {
  18750. // Blend images
  18751. isImage = true;
  18752.  
  18753. var _el = fabric.util.createCanvasElement();
  18754. _el.width = this.image.width;
  18755. _el.height = this.image.height;
  18756.  
  18757. var tmpCanvas = new fabric.StaticCanvas(_el);
  18758. tmpCanvas.add(this.image);
  18759. var context2 = tmpCanvas.getContext('2d');
  18760. source = context2.getImageData(0, 0, tmpCanvas.width, tmpCanvas.height).data;
  18761. }
  18762. else {
  18763. // Blend color
  18764. source = new fabric.Color(this.color).getSource();
  18765.  
  18766. tr = source[0] * this.alpha;
  18767. tg = source[1] * this.alpha;
  18768. tb = source[2] * this.alpha;
  18769. }
  18770.  
  18771. for (var i = 0, len = data.length; i < len; i += 4) {
  18772.  
  18773. r = data[i];
  18774. g = data[i + 1];
  18775. b = data[i + 2];
  18776.  
  18777. if (isImage) {
  18778. tr = source[i] * this.alpha;
  18779. tg = source[i + 1] * this.alpha;
  18780. tb = source[i + 2] * this.alpha;
  18781. }
  18782.  
  18783. switch (this.mode) {
  18784. case 'multiply':
  18785. data[i] = r * tr / 255;
  18786. data[i + 1] = g * tg / 255;
  18787. data[i + 2] = b * tb / 255;
  18788. break;
  18789. case 'screen':
  18790. data[i] = 1 - (1 - r) * (1 - tr);
  18791. data[i + 1] = 1 - (1 - g) * (1 - tg);
  18792. data[i + 2] = 1 - (1 - b) * (1 - tb);
  18793. break;
  18794. case 'add':
  18795. data[i] = Math.min(255, r + tr);
  18796. data[i + 1] = Math.min(255, g + tg);
  18797. data[i + 2] = Math.min(255, b + tb);
  18798. break;
  18799. case 'diff':
  18800. case 'difference':
  18801. data[i] = Math.abs(r - tr);
  18802. data[i + 1] = Math.abs(g - tg);
  18803. data[i + 2] = Math.abs(b - tb);
  18804. break;
  18805. case 'subtract':
  18806. var _r = r - tr,
  18807. _g = g - tg,
  18808. _b = b - tb;
  18809.  
  18810. data[i] = (_r < 0) ? 0 : _r;
  18811. data[i + 1] = (_g < 0) ? 0 : _g;
  18812. data[i + 2] = (_b < 0) ? 0 : _b;
  18813. break;
  18814. case 'darken':
  18815. data[i] = Math.min(r, tr);
  18816. data[i + 1] = Math.min(g, tg);
  18817. data[i + 2] = Math.min(b, tb);
  18818. break;
  18819. case 'lighten':
  18820. data[i] = Math.max(r, tr);
  18821. data[i + 1] = Math.max(g, tg);
  18822. data[i + 2] = Math.max(b, tb);
  18823. break;
  18824. }
  18825. }
  18826.  
  18827. context.putImageData(imageData, 0, 0);
  18828. },
  18829.  
  18830. /**
  18831. * Returns object representation of an instance
  18832. * @return {Object} Object representation of an instance
  18833. */
  18834. toObject: function() {
  18835. return {
  18836. color: this.color,
  18837. image: this.image,
  18838. mode: this.mode,
  18839. alpha: this.alpha
  18840. };
  18841. }
  18842. });
  18843.  
  18844. fabric.Image.filters.Blend.fromObject = function(object) {
  18845. return new fabric.Image.filters.Blend(object);
  18846. };
  18847. })(typeof exports !== 'undefined' ? exports : this);
  18848.  
  18849.  
  18850. (function(global) {
  18851.  
  18852. 'use strict';
  18853.  
  18854. var fabric = global.fabric || (global.fabric = { }),
  18855. extend = fabric.util.object.extend,
  18856. clone = fabric.util.object.clone,
  18857. toFixed = fabric.util.toFixed,
  18858. supportsLineDash = fabric.StaticCanvas.supports('setLineDash');
  18859.  
  18860. if (fabric.Text) {
  18861. fabric.warn('fabric.Text is already defined');
  18862. return;
  18863. }
  18864.  
  18865. var stateProperties = fabric.Object.prototype.stateProperties.concat();
  18866. stateProperties.push(
  18867. 'fontFamily',
  18868. 'fontWeight',
  18869. 'fontSize',
  18870. 'text',
  18871. 'textDecoration',
  18872. 'textAlign',
  18873. 'fontStyle',
  18874. 'lineHeight',
  18875. 'textBackgroundColor',
  18876. 'useNative',
  18877. 'path'
  18878. );
  18879.  
  18880. /**
  18881. * Text class
  18882. * @class fabric.Text
  18883. * @extends fabric.Object
  18884. * @return {fabric.Text} thisArg
  18885. * @tutorial {@link http://fabricjs.com/fabric-intro-part-2/#text}
  18886. * @see {@link fabric.Text#initialize} for constructor definition
  18887. */
  18888. fabric.Text = fabric.util.createClass(fabric.Object, /** @lends fabric.Text.prototype */ {
  18889.  
  18890. /**
  18891. * Properties which when set cause object to change dimensions
  18892. * @type Object
  18893. * @private
  18894. */
  18895. _dimensionAffectingProps: {
  18896. fontSize: true,
  18897. fontWeight: true,
  18898. fontFamily: true,
  18899. textDecoration: true,
  18900. fontStyle: true,
  18901. lineHeight: true,
  18902. stroke: true,
  18903. strokeWidth: true,
  18904. text: true
  18905. },
  18906.  
  18907. /**
  18908. * @private
  18909. */
  18910. _reNewline: /\r?\n/,
  18911.  
  18912. /**
  18913. * Retrieves object's fontSize
  18914. * @method getFontSize
  18915. * @memberOf fabric.Text.prototype
  18916. * @return {String} Font size (in pixels)
  18917. */
  18918.  
  18919. /**
  18920. * Sets object's fontSize
  18921. * @method setFontSize
  18922. * @memberOf fabric.Text.prototype
  18923. * @param {Number} fontSize Font size (in pixels)
  18924. * @return {fabric.Text}
  18925. * @chainable
  18926. */
  18927.  
  18928. /**
  18929. * Retrieves object's fontWeight
  18930. * @method getFontWeight
  18931. * @memberOf fabric.Text.prototype
  18932. * @return {(String|Number)} Font weight
  18933. */
  18934.  
  18935. /**
  18936. * Sets object's fontWeight
  18937. * @method setFontWeight
  18938. * @memberOf fabric.Text.prototype
  18939. * @param {(Number|String)} fontWeight Font weight
  18940. * @return {fabric.Text}
  18941. * @chainable
  18942. */
  18943.  
  18944. /**
  18945. * Retrieves object's fontFamily
  18946. * @method getFontFamily
  18947. * @memberOf fabric.Text.prototype
  18948. * @return {String} Font family
  18949. */
  18950.  
  18951. /**
  18952. * Sets object's fontFamily
  18953. * @method setFontFamily
  18954. * @memberOf fabric.Text.prototype
  18955. * @param {String} fontFamily Font family
  18956. * @return {fabric.Text}
  18957. * @chainable
  18958. */
  18959.  
  18960. /**
  18961. * Retrieves object's text
  18962. * @method getText
  18963. * @memberOf fabric.Text.prototype
  18964. * @return {String} text
  18965. */
  18966.  
  18967. /**
  18968. * Sets object's text
  18969. * @method setText
  18970. * @memberOf fabric.Text.prototype
  18971. * @param {String} text Text
  18972. * @return {fabric.Text}
  18973. * @chainable
  18974. */
  18975.  
  18976. /**
  18977. * Retrieves object's textDecoration
  18978. * @method getTextDecoration
  18979. * @memberOf fabric.Text.prototype
  18980. * @return {String} Text decoration
  18981. */
  18982.  
  18983. /**
  18984. * Sets object's textDecoration
  18985. * @method setTextDecoration
  18986. * @memberOf fabric.Text.prototype
  18987. * @param {String} textDecoration Text decoration
  18988. * @return {fabric.Text}
  18989. * @chainable
  18990. */
  18991.  
  18992. /**
  18993. * Retrieves object's fontStyle
  18994. * @method getFontStyle
  18995. * @memberOf fabric.Text.prototype
  18996. * @return {String} Font style
  18997. */
  18998.  
  18999. /**
  19000. * Sets object's fontStyle
  19001. * @method setFontStyle
  19002. * @memberOf fabric.Text.prototype
  19003. * @param {String} fontStyle Font style
  19004. * @return {fabric.Text}
  19005. * @chainable
  19006. */
  19007.  
  19008. /**
  19009. * Retrieves object's lineHeight
  19010. * @method getLineHeight
  19011. * @memberOf fabric.Text.prototype
  19012. * @return {Number} Line height
  19013. */
  19014.  
  19015. /**
  19016. * Sets object's lineHeight
  19017. * @method setLineHeight
  19018. * @memberOf fabric.Text.prototype
  19019. * @param {Number} lineHeight Line height
  19020. * @return {fabric.Text}
  19021. * @chainable
  19022. */
  19023.  
  19024. /**
  19025. * Retrieves object's textAlign
  19026. * @method getTextAlign
  19027. * @memberOf fabric.Text.prototype
  19028. * @return {String} Text alignment
  19029. */
  19030.  
  19031. /**
  19032. * Sets object's textAlign
  19033. * @method setTextAlign
  19034. * @memberOf fabric.Text.prototype
  19035. * @param {String} textAlign Text alignment
  19036. * @return {fabric.Text}
  19037. * @chainable
  19038. */
  19039.  
  19040. /**
  19041. * Retrieves object's textBackgroundColor
  19042. * @method getTextBackgroundColor
  19043. * @memberOf fabric.Text.prototype
  19044. * @return {String} Text background color
  19045. */
  19046.  
  19047. /**
  19048. * Sets object's textBackgroundColor
  19049. * @method setTextBackgroundColor
  19050. * @memberOf fabric.Text.prototype
  19051. * @param {String} textBackgroundColor Text background color
  19052. * @return {fabric.Text}
  19053. * @chainable
  19054. */
  19055.  
  19056. /**
  19057. * Type of an object
  19058. * @type String
  19059. * @default
  19060. */
  19061. type: 'text',
  19062.  
  19063. /**
  19064. * Font size (in pixels)
  19065. * @type Number
  19066. * @default
  19067. */
  19068. fontSize: 40,
  19069.  
  19070. /**
  19071. * Font weight (e.g. bold, normal, 400, 600, 800)
  19072. * @type {(Number|String)}
  19073. * @default
  19074. */
  19075. fontWeight: 'normal',
  19076.  
  19077. /**
  19078. * Font family
  19079. * @type String
  19080. * @default
  19081. */
  19082. fontFamily: 'Times New Roman',
  19083.  
  19084. /**
  19085. * Text decoration Possible values: "", "underline", "overline" or "line-through".
  19086. * @type String
  19087. * @default
  19088. */
  19089. textDecoration: '',
  19090.  
  19091. /**
  19092. * Text alignment. Possible values: "left", "center", or "right".
  19093. * @type String
  19094. * @default
  19095. */
  19096. textAlign: 'left',
  19097.  
  19098. /**
  19099. * Font style . Possible values: "", "normal", "italic" or "oblique".
  19100. * @type String
  19101. * @default
  19102. */
  19103. fontStyle: '',
  19104.  
  19105. /**
  19106. * Line height
  19107. * @type Number
  19108. * @default
  19109. */
  19110. lineHeight: 1.3,
  19111.  
  19112. /**
  19113. * Background color of text lines
  19114. * @type String
  19115. * @default
  19116. */
  19117. textBackgroundColor: '',
  19118.  
  19119. /**
  19120. * URL of a font file, when using Cufon
  19121. * @type String | null
  19122. * @default
  19123. */
  19124. path: null,
  19125.  
  19126. /**
  19127. * Indicates whether canvas native text methods should be used to render text (otherwise, Cufon is used)
  19128. * @type Boolean
  19129. * @default
  19130. */
  19131. useNative: true,
  19132.  
  19133. /**
  19134. * List of properties to consider when checking if
  19135. * state of an object is changed ({@link fabric.Object#hasStateChanged})
  19136. * as well as for history (undo/redo) purposes
  19137. * @type Array
  19138. */
  19139. stateProperties: stateProperties,
  19140.  
  19141. /**
  19142. * When defined, an object is rendered via stroke and this property specifies its color.
  19143. * <b>Backwards incompatibility note:</b> This property was named "strokeStyle" until v1.1.6
  19144. * @type String
  19145. * @default
  19146. */
  19147. stroke: null,
  19148.  
  19149. /**
  19150. * Shadow object representing shadow of this shape.
  19151. * <b>Backwards incompatibility note:</b> This property was named "textShadow" (String) until v1.2.11
  19152. * @type fabric.Shadow
  19153. * @default
  19154. */
  19155. shadow: null,
  19156.  
  19157. /**
  19158. * Constructor
  19159. * @param {String} text Text string
  19160. * @param {Object} [options] Options object
  19161. * @return {fabric.Text} thisArg
  19162. */
  19163. initialize: function(text, options) {
  19164. options = options || { };
  19165.  
  19166. this.text = text;
  19167. this.__skipDimension = true;
  19168. this.setOptions(options);
  19169. this.__skipDimension = false;
  19170. this._initDimensions();
  19171. },
  19172.  
  19173. /**
  19174. * Renders text object on offscreen canvas, so that it would get dimensions
  19175. * @private
  19176. */
  19177. _initDimensions: function() {
  19178. if (this.__skipDimension) {
  19179. return;
  19180. }
  19181. var canvasEl = fabric.util.createCanvasElement();
  19182. this._render(canvasEl.getContext('2d'));
  19183. },
  19184.  
  19185. /**
  19186. * Returns string representation of an instance
  19187. * @return {String} String representation of text object
  19188. */
  19189. toString: function() {
  19190. return '#<fabric.Text (' + this.complexity() +
  19191. '): { "text": "' + this.text + '", "fontFamily": "' + this.fontFamily + '" }>';
  19192. },
  19193.  
  19194. /**
  19195. * @private
  19196. * @param {CanvasRenderingContext2D} ctx Context to render on
  19197. */
  19198. _render: function(ctx) {
  19199.  
  19200. if (typeof Cufon === 'undefined' || this.useNative === true) {
  19201. this._renderViaNative(ctx);
  19202. }
  19203. else {
  19204. this._renderViaCufon(ctx);
  19205. }
  19206. },
  19207.  
  19208. /**
  19209. * @private
  19210. * @param {CanvasRenderingContext2D} ctx Context to render on
  19211. */
  19212. _renderViaNative: function(ctx) {
  19213. var textLines = this.text.split(this._reNewline);
  19214.  
  19215. this._setTextStyles(ctx);
  19216.  
  19217. this.width = this._getTextWidth(ctx, textLines);
  19218. this.height = this._getTextHeight(ctx, textLines);
  19219.  
  19220. this.clipTo && fabric.util.clipContext(this, ctx);
  19221.  
  19222. this._renderTextBackground(ctx, textLines);
  19223. this._translateForTextAlign(ctx);
  19224. this._renderText(ctx, textLines);
  19225.  
  19226. if (this.textAlign !== 'left' && this.textAlign !== 'justify') {
  19227. ctx.restore();
  19228. }
  19229.  
  19230. this._renderTextDecoration(ctx, textLines);
  19231. this.clipTo && ctx.restore();
  19232.  
  19233. this._setBoundaries(ctx, textLines);
  19234. this._totalLineHeight = 0;
  19235. },
  19236.  
  19237. /**
  19238. * @private
  19239. * @param {CanvasRenderingContext2D} ctx Context to render on
  19240. */
  19241. _renderText: function(ctx, textLines) {
  19242. ctx.save();
  19243. this._setShadow(ctx);
  19244. this._setupCompositeOperation(ctx);
  19245. this._renderTextFill(ctx, textLines);
  19246. this._renderTextStroke(ctx, textLines);
  19247. this._restoreCompositeOperation(ctx);
  19248. this._removeShadow(ctx);
  19249. ctx.restore();
  19250. },
  19251.  
  19252. /**
  19253. * @private
  19254. * @param {CanvasRenderingContext2D} ctx Context to render on
  19255. */
  19256. _translateForTextAlign: function(ctx) {
  19257. if (this.textAlign !== 'left' && this.textAlign !== 'justify') {
  19258. ctx.save();
  19259. ctx.translate(this.textAlign === 'center' ? (this.width / 2) : this.width, 0);
  19260. }
  19261. },
  19262.  
  19263. /**
  19264. * @private
  19265. * @param {CanvasRenderingContext2D} ctx Context to render on
  19266. * @param {Array} textLines Array of all text lines
  19267. */
  19268. _setBoundaries: function(ctx, textLines) {
  19269. this._boundaries = [ ];
  19270.  
  19271. for (var i = 0, len = textLines.length; i < len; i++) {
  19272.  
  19273. var lineWidth = this._getLineWidth(ctx, textLines[i]),
  19274. lineLeftOffset = this._getLineLeftOffset(lineWidth);
  19275.  
  19276. this._boundaries.push({
  19277. height: this.fontSize * this.lineHeight,
  19278. width: lineWidth,
  19279. left: lineLeftOffset
  19280. });
  19281. }
  19282. },
  19283.  
  19284. /**
  19285. * @private
  19286. * @param {CanvasRenderingContext2D} ctx Context to render on
  19287. */
  19288. _setTextStyles: function(ctx) {
  19289. this._setFillStyles(ctx);
  19290. this._setStrokeStyles(ctx);
  19291. ctx.textBaseline = 'alphabetic';
  19292. if (!this.skipTextAlign) {
  19293. ctx.textAlign = this.textAlign;
  19294. }
  19295. ctx.font = this._getFontDeclaration();
  19296. },
  19297.  
  19298. /**
  19299. * @private
  19300. * @param {CanvasRenderingContext2D} ctx Context to render on
  19301. * @param {Array} textLines Array of all text lines
  19302. * @return {Number} Height of fabric.Text object
  19303. */
  19304. _getTextHeight: function(ctx, textLines) {
  19305. return this.fontSize * textLines.length * this.lineHeight;
  19306. },
  19307.  
  19308. /**
  19309. * @private
  19310. * @param {CanvasRenderingContext2D} ctx Context to render on
  19311. * @param {Array} textLines Array of all text lines
  19312. * @return {Number} Maximum width of fabric.Text object
  19313. */
  19314. _getTextWidth: function(ctx, textLines) {
  19315. var maxWidth = ctx.measureText(textLines[0] || '|').width;
  19316.  
  19317. for (var i = 1, len = textLines.length; i < len; i++) {
  19318. var currentLineWidth = ctx.measureText(textLines[i]).width;
  19319. if (currentLineWidth > maxWidth) {
  19320. maxWidth = currentLineWidth;
  19321. }
  19322. }
  19323. return maxWidth;
  19324. },
  19325.  
  19326. /**
  19327. * @private
  19328. * @param {String} method Method name ("fillText" or "strokeText")
  19329. * @param {CanvasRenderingContext2D} ctx Context to render on
  19330. * @param {String} chars Chars to render
  19331. * @param {Number} left Left position of text
  19332. * @param {Number} top Top position of text
  19333. */
  19334. _renderChars: function(method, ctx, chars, left, top) {
  19335. ctx[method](chars, left, top);
  19336. },
  19337.  
  19338. /**
  19339. * @private
  19340. * @param {String} method Method name ("fillText" or "strokeText")
  19341. * @param {CanvasRenderingContext2D} ctx Context to render on
  19342. * @param {String} line Text to render
  19343. * @param {Number} left Left position of text
  19344. * @param {Number} top Top position of text
  19345. * @param {Number} lineIndex Index of a line in a text
  19346. */
  19347. _renderTextLine: function(method, ctx, line, left, top, lineIndex) {
  19348. // lift the line by quarter of fontSize
  19349. top -= this.fontSize / 4;
  19350.  
  19351. // short-circuit
  19352. if (this.textAlign !== 'justify') {
  19353. this._renderChars(method, ctx, line, left, top, lineIndex);
  19354. return;
  19355. }
  19356.  
  19357. var lineWidth = ctx.measureText(line).width,
  19358. totalWidth = this.width;
  19359.  
  19360. if (totalWidth > lineWidth) {
  19361. // stretch the line
  19362. var words = line.split(/\s+/),
  19363. wordsWidth = ctx.measureText(line.replace(/\s+/g, '')).width,
  19364. widthDiff = totalWidth - wordsWidth,
  19365. numSpaces = words.length - 1,
  19366. spaceWidth = widthDiff / numSpaces,
  19367. leftOffset = 0;
  19368.  
  19369. for (var i = 0, len = words.length; i < len; i++) {
  19370. this._renderChars(method, ctx, words[i], left + leftOffset, top, lineIndex);
  19371. leftOffset += ctx.measureText(words[i]).width + spaceWidth;
  19372. }
  19373. }
  19374. else {
  19375. this._renderChars(method, ctx, line, left, top, lineIndex);
  19376. }
  19377. },
  19378.  
  19379. /**
  19380. * @private
  19381. * @return {Number} Left offset
  19382. */
  19383. _getLeftOffset: function() {
  19384. if (fabric.isLikelyNode) {
  19385. return 0;
  19386. }
  19387. return -this.width / 2;
  19388. },
  19389.  
  19390. /**
  19391. * @private
  19392. * @return {Number} Top offset
  19393. */
  19394. _getTopOffset: function() {
  19395. return -this.height / 2;
  19396. },
  19397.  
  19398. /**
  19399. * @private
  19400. * @param {CanvasRenderingContext2D} ctx Context to render on
  19401. * @param {Array} textLines Array of all text lines
  19402. */
  19403. _renderTextFill: function(ctx, textLines) {
  19404. if (!this.fill && !this._skipFillStrokeCheck) {
  19405. return;
  19406. }
  19407.  
  19408. this._boundaries = [ ];
  19409. var lineHeights = 0;
  19410.  
  19411. for (var i = 0, len = textLines.length; i < len; i++) {
  19412. var heightOfLine = this._getHeightOfLine(ctx, i, textLines);
  19413. lineHeights += heightOfLine;
  19414.  
  19415. this._renderTextLine(
  19416. 'fillText',
  19417. ctx,
  19418. textLines[i],
  19419. this._getLeftOffset(),
  19420. this._getTopOffset() + lineHeights,
  19421. i
  19422. );
  19423. }
  19424. if (this.shadow && !this.shadow.affectStroke) {
  19425. this._removeShadow(ctx);
  19426. }
  19427. },
  19428.  
  19429. /**
  19430. * @private
  19431. * @param {CanvasRenderingContext2D} ctx Context to render on
  19432. * @param {Array} textLines Array of all text lines
  19433. */
  19434. _renderTextStroke: function(ctx, textLines) {
  19435. if ((!this.stroke || this.strokeWidth === 0) && !this._skipFillStrokeCheck) {
  19436. return;
  19437. }
  19438.  
  19439. var lineHeights = 0;
  19440.  
  19441. ctx.save();
  19442. if (this.strokeDashArray) {
  19443. // Spec requires the concatenation of two copies the dash list when the number of elements is odd
  19444. if (1 & this.strokeDashArray.length) {
  19445. this.strokeDashArray.push.apply(this.strokeDashArray, this.strokeDashArray);
  19446. }
  19447. supportsLineDash && ctx.setLineDash(this.strokeDashArray);
  19448. }
  19449.  
  19450. ctx.beginPath();
  19451. for (var i = 0, len = textLines.length; i < len; i++) {
  19452. var heightOfLine = this._getHeightOfLine(ctx, i, textLines);
  19453. lineHeights += heightOfLine;
  19454.  
  19455. this._renderTextLine(
  19456. 'strokeText',
  19457. ctx,
  19458. textLines[i],
  19459. this._getLeftOffset(),
  19460. this._getTopOffset() + lineHeights,
  19461. i
  19462. );
  19463. }
  19464. ctx.closePath();
  19465. ctx.restore();
  19466. },
  19467.  
  19468. _getHeightOfLine: function() {
  19469. return this.fontSize * this.lineHeight;
  19470. },
  19471.  
  19472. /**
  19473. * @private
  19474. * @param {CanvasRenderingContext2D} ctx Context to render on
  19475. * @param {Array} textLines Array of all text lines
  19476. */
  19477. _renderTextBackground: function(ctx, textLines) {
  19478. this._renderTextBoxBackground(ctx);
  19479. this._renderTextLinesBackground(ctx, textLines);
  19480. },
  19481.  
  19482. /**
  19483. * @private
  19484. * @param {CanvasRenderingContext2D} ctx Context to render on
  19485. */
  19486. _renderTextBoxBackground: function(ctx) {
  19487. if (!this.backgroundColor) {
  19488. return;
  19489. }
  19490.  
  19491. ctx.save();
  19492. ctx.fillStyle = this.backgroundColor;
  19493.  
  19494. ctx.fillRect(
  19495. this._getLeftOffset(),
  19496. this._getTopOffset(),
  19497. this.width,
  19498. this.height
  19499. );
  19500.  
  19501. ctx.restore();
  19502. },
  19503.  
  19504. /**
  19505. * @private
  19506. * @param {CanvasRenderingContext2D} ctx Context to render on
  19507. * @param {Array} textLines Array of all text lines
  19508. */
  19509. _renderTextLinesBackground: function(ctx, textLines) {
  19510. if (!this.textBackgroundColor) {
  19511. return;
  19512. }
  19513.  
  19514. ctx.save();
  19515. ctx.fillStyle = this.textBackgroundColor;
  19516.  
  19517. for (var i = 0, len = textLines.length; i < len; i++) {
  19518.  
  19519. if (textLines[i] !== '') {
  19520.  
  19521. var lineWidth = this._getLineWidth(ctx, textLines[i]),
  19522. lineLeftOffset = this._getLineLeftOffset(lineWidth);
  19523.  
  19524. ctx.fillRect(
  19525. this._getLeftOffset() + lineLeftOffset,
  19526. this._getTopOffset() + (i * this.fontSize * this.lineHeight),
  19527. lineWidth,
  19528. this.fontSize * this.lineHeight
  19529. );
  19530. }
  19531. }
  19532. ctx.restore();
  19533. },
  19534.  
  19535. /**
  19536. * @private
  19537. * @param {Number} lineWidth Width of text line
  19538. * @return {Number} Line left offset
  19539. */
  19540. _getLineLeftOffset: function(lineWidth) {
  19541. if (this.textAlign === 'center') {
  19542. return (this.width - lineWidth) / 2;
  19543. }
  19544. if (this.textAlign === 'right') {
  19545. return this.width - lineWidth;
  19546. }
  19547. return 0;
  19548. },
  19549.  
  19550. /**
  19551. * @private
  19552. * @param {CanvasRenderingContext2D} ctx Context to render on
  19553. * @param {String} line Text line
  19554. * @return {Number} Line width
  19555. */
  19556. _getLineWidth: function(ctx, line) {
  19557. return this.textAlign === 'justify'
  19558. ? this.width
  19559. : ctx.measureText(line).width;
  19560. },
  19561.  
  19562. /**
  19563. * @private
  19564. * @param {CanvasRenderingContext2D} ctx Context to render on
  19565. * @param {Array} textLines Array of all text lines
  19566. */
  19567. _renderTextDecoration: function(ctx, textLines) {
  19568. if (!this.textDecoration) {
  19569. return;
  19570. }
  19571.  
  19572. // var halfOfVerticalBox = this.originY === 'top' ? 0 : this._getTextHeight(ctx, textLines) / 2;
  19573. var halfOfVerticalBox = this._getTextHeight(ctx, textLines) / 2,
  19574. _this = this;
  19575.  
  19576. /** @ignore */
  19577. function renderLinesAtOffset(offset) {
  19578. for (var i = 0, len = textLines.length; i < len; i++) {
  19579.  
  19580. var lineWidth = _this._getLineWidth(ctx, textLines[i]),
  19581. lineLeftOffset = _this._getLineLeftOffset(lineWidth);
  19582.  
  19583. ctx.fillRect(
  19584. _this._getLeftOffset() + lineLeftOffset,
  19585. ~~((offset + (i * _this._getHeightOfLine(ctx, i, textLines))) - halfOfVerticalBox),
  19586. lineWidth,
  19587. 1);
  19588. }
  19589. }
  19590.  
  19591. if (this.textDecoration.indexOf('underline') > -1) {
  19592. renderLinesAtOffset(this.fontSize * this.lineHeight);
  19593. }
  19594. if (this.textDecoration.indexOf('line-through') > -1) {
  19595. renderLinesAtOffset(this.fontSize * this.lineHeight - this.fontSize / 2);
  19596. }
  19597. if (this.textDecoration.indexOf('overline') > -1) {
  19598. renderLinesAtOffset(this.fontSize * this.lineHeight - this.fontSize);
  19599. }
  19600. },
  19601.  
  19602. /**
  19603. * @private
  19604. */
  19605. _getFontDeclaration: function() {
  19606. return [
  19607. // node-canvas needs "weight style", while browsers need "style weight"
  19608. (fabric.isLikelyNode ? this.fontWeight : this.fontStyle),
  19609. (fabric.isLikelyNode ? this.fontStyle : this.fontWeight),
  19610. this.fontSize + 'px',
  19611. (fabric.isLikelyNode ? ('"' + this.fontFamily + '"') : this.fontFamily)
  19612. ].join(' ');
  19613. },
  19614.  
  19615. /**
  19616. * Renders text instance on a specified context
  19617. * @param {CanvasRenderingContext2D} ctx Context to render on
  19618. */
  19619. render: function(ctx, noTransform) {
  19620. // do not render if object is not visible
  19621. if (!this.visible) {
  19622. return;
  19623. }
  19624.  
  19625. ctx.save();
  19626. if (!noTransform) {
  19627. this.transform(ctx);
  19628. }
  19629.  
  19630. var isInPathGroup = this.group && this.group.type === 'path-group';
  19631.  
  19632. if (isInPathGroup) {
  19633. ctx.translate(-this.group.width/2, -this.group.height/2);
  19634. }
  19635. if (this.transformMatrix) {
  19636. ctx.transform.apply(ctx, this.transformMatrix);
  19637. }
  19638. if (isInPathGroup) {
  19639. ctx.translate(this.left, this.top);
  19640. }
  19641. this._render(ctx);
  19642. ctx.restore();
  19643. },
  19644.  
  19645. /**
  19646. * Returns object representation of an instance
  19647. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  19648. * @return {Object} Object representation of an instance
  19649. */
  19650. toObject: function(propertiesToInclude) {
  19651. var object = extend(this.callSuper('toObject', propertiesToInclude), {
  19652. text: this.text,
  19653. fontSize: this.fontSize,
  19654. fontWeight: this.fontWeight,
  19655. fontFamily: this.fontFamily,
  19656. fontStyle: this.fontStyle,
  19657. lineHeight: this.lineHeight,
  19658. textDecoration: this.textDecoration,
  19659. textAlign: this.textAlign,
  19660. path: this.path,
  19661. textBackgroundColor: this.textBackgroundColor,
  19662. useNative: this.useNative
  19663. });
  19664. if (!this.includeDefaultValues) {
  19665. this._removeDefaultValues(object);
  19666. }
  19667. return object;
  19668. },
  19669.  
  19670. /* _TO_SVG_START_ */
  19671. /**
  19672. * Returns SVG representation of an instance
  19673. * @param {Function} [reviver] Method for further parsing of svg representation.
  19674. * @return {String} svg representation of an instance
  19675. */
  19676. toSVG: function(reviver) {
  19677. var markup = [ ],
  19678. textLines = this.text.split(this._reNewline),
  19679. offsets = this._getSVGLeftTopOffsets(textLines),
  19680. textAndBg = this._getSVGTextAndBg(offsets.lineTop, offsets.textLeft, textLines),
  19681. shadowSpans = this._getSVGShadows(offsets.lineTop, textLines);
  19682.  
  19683. // move top offset by an ascent
  19684. offsets.textTop += (this._fontAscent ? ((this._fontAscent / 5) * this.lineHeight) : 0);
  19685.  
  19686. this._wrapSVGTextAndBg(markup, textAndBg, shadowSpans, offsets);
  19687.  
  19688. return reviver ? reviver(markup.join('')) : markup.join('');
  19689. },
  19690.  
  19691. /**
  19692. * @private
  19693. */
  19694. _getSVGLeftTopOffsets: function(textLines) {
  19695. var lineTop = this.useNative
  19696. ? this.fontSize * this.lineHeight
  19697. : (-this._fontAscent - ((this._fontAscent / 5) * this.lineHeight)),
  19698.  
  19699. textLeft = -(this.width/2),
  19700. textTop = this.useNative
  19701. ? this.fontSize - 1
  19702. : (this.height/2) - (textLines.length * this.fontSize) - this._totalLineHeight;
  19703.  
  19704. return {
  19705. textLeft: textLeft + (this.group && this.group.type === 'path-group' ? this.left : 0),
  19706. textTop: textTop + (this.group && this.group.type === 'path-group' ? this.top : 0),
  19707. lineTop: lineTop
  19708. };
  19709. },
  19710.  
  19711. /**
  19712. * @private
  19713. */
  19714. _wrapSVGTextAndBg: function(markup, textAndBg, shadowSpans, offsets) {
  19715. markup.push(
  19716. '<g transform="', this.getSvgTransform(), this.getSvgTransformMatrix(), '">\n',
  19717. textAndBg.textBgRects.join(''),
  19718. '<text ',
  19719. (this.fontFamily ? 'font-family="' + this.fontFamily.replace(/"/g, '\'') + '" ': ''),
  19720. (this.fontSize ? 'font-size="' + this.fontSize + '" ': ''),
  19721. (this.fontStyle ? 'font-style="' + this.fontStyle + '" ': ''),
  19722. (this.fontWeight ? 'font-weight="' + this.fontWeight + '" ': ''),
  19723. (this.textDecoration ? 'text-decoration="' + this.textDecoration + '" ': ''),
  19724. 'style="', this.getSvgStyles(), '" ',
  19725. /* svg starts from left/bottom corner so we normalize height */
  19726. 'transform="translate(', toFixed(offsets.textLeft, 2), ' ', toFixed(offsets.textTop, 2), ')">',
  19727. shadowSpans.join(''),
  19728. textAndBg.textSpans.join(''),
  19729. '</text>\n',
  19730. '</g>\n'
  19731. );
  19732. },
  19733.  
  19734. /**
  19735. * @private
  19736. * @param {Number} lineHeight
  19737. * @param {Array} textLines Array of all text lines
  19738. * @return {Array}
  19739. */
  19740. _getSVGShadows: function(lineHeight, textLines) {
  19741. var shadowSpans = [],
  19742. i, len,
  19743. lineTopOffsetMultiplier = 1;
  19744.  
  19745. if (!this.shadow || !this._boundaries) {
  19746. return shadowSpans;
  19747. }
  19748.  
  19749. for (i = 0, len = textLines.length; i < len; i++) {
  19750. if (textLines[i] !== '') {
  19751. var lineLeftOffset = (this._boundaries && this._boundaries[i]) ? this._boundaries[i].left : 0;
  19752. shadowSpans.push(
  19753. '<tspan x="',
  19754. toFixed((lineLeftOffset + lineTopOffsetMultiplier) + this.shadow.offsetX, 2),
  19755. ((i === 0 || this.useNative) ? '" y' : '" dy'), '="',
  19756. toFixed(this.useNative
  19757. ? ((lineHeight * i) - this.height / 2 + this.shadow.offsetY)
  19758. : (lineHeight + (i === 0 ? this.shadow.offsetY : 0)), 2),
  19759. '" ',
  19760. this._getFillAttributes(this.shadow.color), '>',
  19761. fabric.util.string.escapeXml(textLines[i]),
  19762. '</tspan>');
  19763. lineTopOffsetMultiplier = 1;
  19764. }
  19765. else {
  19766. // in some environments (e.g. IE 7 & 8) empty tspans are completely ignored, using a lineTopOffsetMultiplier
  19767. // prevents empty tspans
  19768. lineTopOffsetMultiplier++;
  19769. }
  19770. }
  19771.  
  19772. return shadowSpans;
  19773. },
  19774.  
  19775. /**
  19776. * @private
  19777. * @param {Number} lineHeight
  19778. * @param {Number} textLeftOffset Text left offset
  19779. * @param {Array} textLines Array of all text lines
  19780. * @return {Object}
  19781. */
  19782. _getSVGTextAndBg: function(lineHeight, textLeftOffset, textLines) {
  19783. var textSpans = [ ],
  19784. textBgRects = [ ],
  19785. lineTopOffsetMultiplier = 1;
  19786.  
  19787. // bounding-box background
  19788. this._setSVGBg(textBgRects);
  19789.  
  19790. // text and text-background
  19791. for (var i = 0, len = textLines.length; i < len; i++) {
  19792. if (textLines[i] !== '') {
  19793. this._setSVGTextLineText(textLines[i], i, textSpans, lineHeight, lineTopOffsetMultiplier, textBgRects);
  19794. lineTopOffsetMultiplier = 1;
  19795. }
  19796. else {
  19797. // in some environments (e.g. IE 7 & 8) empty tspans are completely ignored, using a lineTopOffsetMultiplier
  19798. // prevents empty tspans
  19799. lineTopOffsetMultiplier++;
  19800. }
  19801.  
  19802. if (!this.textBackgroundColor || !this._boundaries) {
  19803. continue;
  19804. }
  19805.  
  19806. this._setSVGTextLineBg(textBgRects, i, textLeftOffset, lineHeight);
  19807. }
  19808.  
  19809. return {
  19810. textSpans: textSpans,
  19811. textBgRects: textBgRects
  19812. };
  19813. },
  19814.  
  19815. _setSVGTextLineText: function(textLine, i, textSpans, lineHeight, lineTopOffsetMultiplier) {
  19816. var lineLeftOffset = (this._boundaries && this._boundaries[i])
  19817. ? toFixed(this._boundaries[i].left, 2)
  19818. : 0;
  19819.  
  19820. textSpans.push(
  19821. '<tspan x="',
  19822. lineLeftOffset, '" ',
  19823. (i === 0 || this.useNative ? 'y' : 'dy'), '="',
  19824. toFixed(this.useNative
  19825. ? ((lineHeight * i) - this.height / 2)
  19826. : (lineHeight * lineTopOffsetMultiplier), 2), '" ',
  19827. // doing this on <tspan> elements since setting opacity
  19828. // on containing <text> one doesn't work in Illustrator
  19829. this._getFillAttributes(this.fill), '>',
  19830. fabric.util.string.escapeXml(textLine),
  19831. '</tspan>'
  19832. );
  19833. },
  19834.  
  19835. _setSVGTextLineBg: function(textBgRects, i, textLeftOffset, lineHeight) {
  19836. textBgRects.push(
  19837. '<rect ',
  19838. this._getFillAttributes(this.textBackgroundColor),
  19839. ' x="',
  19840. toFixed(textLeftOffset + this._boundaries[i].left, 2),
  19841. '" y="',
  19842. /* an offset that seems to straighten things out */
  19843. toFixed((lineHeight * i) - this.height / 2, 2),
  19844. '" width="',
  19845. toFixed(this._boundaries[i].width, 2),
  19846. '" height="',
  19847. toFixed(this._boundaries[i].height, 2),
  19848. '"></rect>\n');
  19849. },
  19850.  
  19851. _setSVGBg: function(textBgRects) {
  19852. if (this.backgroundColor && this._boundaries) {
  19853. textBgRects.push(
  19854. '<rect ',
  19855. this._getFillAttributes(this.backgroundColor),
  19856. ' x="',
  19857. toFixed(-this.width / 2, 2),
  19858. '" y="',
  19859. toFixed(-this.height / 2, 2),
  19860. '" width="',
  19861. toFixed(this.width, 2),
  19862. '" height="',
  19863. toFixed(this.height, 2),
  19864. '"></rect>');
  19865. }
  19866. },
  19867.  
  19868. /**
  19869. * Adobe Illustrator (at least CS5) is unable to render rgba()-based fill values
  19870. * we work around it by "moving" alpha channel into opacity attribute and setting fill's alpha to 1
  19871. *
  19872. * @private
  19873. * @param {Any} value
  19874. * @return {String}
  19875. */
  19876. _getFillAttributes: function(value) {
  19877. var fillColor = (value && typeof value === 'string') ? new fabric.Color(value) : '';
  19878. if (!fillColor || !fillColor.getSource() || fillColor.getAlpha() === 1) {
  19879. return 'fill="' + value + '"';
  19880. }
  19881. return 'opacity="' + fillColor.getAlpha() + '" fill="' + fillColor.setAlpha(1).toRgb() + '"';
  19882. },
  19883. /* _TO_SVG_END_ */
  19884.  
  19885. /**
  19886. * Sets specified property to a specified value
  19887. * @param {String} key
  19888. * @param {Any} value
  19889. * @return {fabric.Text} thisArg
  19890. * @chainable
  19891. */
  19892. _set: function(key, value) {
  19893. if (key === 'fontFamily' && this.path) {
  19894. this.path = this.path.replace(/(.*?)([^\/]*)(\.font\.js)/, '$1' + value + '$3');
  19895. }
  19896. this.callSuper('_set', key, value);
  19897.  
  19898. if (key in this._dimensionAffectingProps) {
  19899. this._initDimensions();
  19900. this.setCoords();
  19901. }
  19902. },
  19903.  
  19904. /**
  19905. * Returns complexity of an instance
  19906. * @return {Number} complexity
  19907. */
  19908. complexity: function() {
  19909. return 1;
  19910. }
  19911. });
  19912.  
  19913. /* _FROM_SVG_START_ */
  19914. /**
  19915. * List of attribute names to account for when parsing SVG element (used by {@link fabric.Text.fromElement})
  19916. * @static
  19917. * @memberOf fabric.Text
  19918. * @see: http://www.w3.org/TR/SVG/text.html#TextElement
  19919. */
  19920. fabric.Text.ATTRIBUTE_NAMES = fabric.SHARED_ATTRIBUTES.concat(
  19921. 'x y dx dy font-family font-style font-weight font-size text-decoration text-anchor'.split(' '));
  19922.  
  19923. /**
  19924. * Default SVG font size
  19925. * @static
  19926. * @memberOf fabric.Text
  19927. */
  19928. fabric.Text.DEFAULT_SVG_FONT_SIZE = 16;
  19929.  
  19930. /**
  19931. * Returns fabric.Text instance from an SVG element (<b>not yet implemented</b>)
  19932. * @static
  19933. * @memberOf fabric.Text
  19934. * @param {SVGElement} element Element to parse
  19935. * @param {Object} [options] Options object
  19936. * @return {fabric.Text} Instance of fabric.Text
  19937. */
  19938. fabric.Text.fromElement = function(element, options) {
  19939. if (!element) {
  19940. return null;
  19941. }
  19942.  
  19943. var parsedAttributes = fabric.parseAttributes(element, fabric.Text.ATTRIBUTE_NAMES);
  19944. options = fabric.util.object.extend((options ? fabric.util.object.clone(options) : { }), parsedAttributes);
  19945.  
  19946. if ('dx' in parsedAttributes) {
  19947. options.left += parsedAttributes.dx;
  19948. }
  19949. if ('dy' in parsedAttributes) {
  19950. options.top += parsedAttributes.dy;
  19951. }
  19952. if (!('fontSize' in options)) {
  19953. options.fontSize = fabric.Text.DEFAULT_SVG_FONT_SIZE;
  19954. }
  19955.  
  19956. if (!options.originX) {
  19957. options.originX = 'left';
  19958. }
  19959.  
  19960. var text = new fabric.Text(element.textContent, options),
  19961. /*
  19962. Adjust positioning:
  19963. x/y attributes in SVG correspond to the bottom-left corner of text bounding box
  19964. top/left properties in Fabric correspond to center point of text bounding box
  19965. */
  19966. offX = 0;
  19967.  
  19968. if (text.originX === 'left') {
  19969. offX = text.getWidth() / 2;
  19970. }
  19971. if (text.originX === 'right') {
  19972. offX = -text.getWidth() / 2;
  19973. }
  19974. text.set({
  19975. left: text.getLeft() + offX,
  19976. top: text.getTop() - text.getHeight() / 2
  19977. });
  19978.  
  19979. return text;
  19980. };
  19981. /* _FROM_SVG_END_ */
  19982.  
  19983. /**
  19984. * Returns fabric.Text instance from an object representation
  19985. * @static
  19986. * @memberOf fabric.Text
  19987. * @param {Object} object Object to create an instance from
  19988. * @return {fabric.Text} Instance of fabric.Text
  19989. */
  19990. fabric.Text.fromObject = function(object) {
  19991. return new fabric.Text(object.text, clone(object));
  19992. };
  19993.  
  19994. fabric.util.createAccessors(fabric.Text);
  19995.  
  19996. })(typeof exports !== 'undefined' ? exports : this);
  19997.  
  19998.  
  19999. (function() {
  20000.  
  20001. var clone = fabric.util.object.clone;
  20002.  
  20003. /**
  20004. * IText class (introduced in <b>v1.4</b>) Events are also fired with "text:"
  20005. * prefix when observing canvas.
  20006. * @class fabric.IText
  20007. * @extends fabric.Text
  20008. * @mixes fabric.Observable
  20009. *
  20010. * @fires changed
  20011. * @fires selection:changed
  20012. * @fires editing:entered
  20013. * @fires editing:exited
  20014. *
  20015. * @return {fabric.IText} thisArg
  20016. * @see {@link fabric.IText#initialize} for constructor definition
  20017. *
  20018. * <p>Supported key combinations:</p>
  20019. * <pre>
  20020. * Move cursor: left, right, up, down
  20021. * Select character: shift + left, shift + right
  20022. * Select text vertically: shift + up, shift + down
  20023. * Move cursor by word: alt + left, alt + right
  20024. * Select words: shift + alt + left, shift + alt + right
  20025. * Move cursor to line start/end: cmd + left, cmd + right
  20026. * Select till start/end of line: cmd + shift + left, cmd + shift + right
  20027. * Jump to start/end of text: cmd + up, cmd + down
  20028. * Select till start/end of text: cmd + shift + up, cmd + shift + down
  20029. * Delete character: backspace
  20030. * Delete word: alt + backspace
  20031. * Delete line: cmd + backspace
  20032. * Forward delete: delete
  20033. * Copy text: ctrl/cmd + c
  20034. * Paste text: ctrl/cmd + v
  20035. * Cut text: ctrl/cmd + x
  20036. * Select entire text: ctrl/cmd + a
  20037. * </pre>
  20038. *
  20039. * <p>Supported mouse/touch combination</p>
  20040. * <pre>
  20041. * Position cursor: click/touch
  20042. * Create selection: click/touch & drag
  20043. * Create selection: click & shift + click
  20044. * Select word: double click
  20045. * Select line: triple click
  20046. * </pre>
  20047. */
  20048. fabric.IText = fabric.util.createClass(fabric.Text, fabric.Observable, /** @lends fabric.IText.prototype */ {
  20049.  
  20050. /**
  20051. * Type of an object
  20052. * @type String
  20053. * @default
  20054. */
  20055. type: 'i-text',
  20056.  
  20057. /**
  20058. * Index where text selection starts (or where cursor is when there is no selection)
  20059. * @type Nubmer
  20060. * @default
  20061. */
  20062. selectionStart: 0,
  20063.  
  20064. /**
  20065. * Index where text selection ends
  20066. * @type Nubmer
  20067. * @default
  20068. */
  20069. selectionEnd: 0,
  20070.  
  20071. /**
  20072. * Color of text selection
  20073. * @type String
  20074. * @default
  20075. */
  20076. selectionColor: 'rgba(17,119,255,0.3)',
  20077.  
  20078. /**
  20079. * Indicates whether text is in editing mode
  20080. * @type Boolean
  20081. * @default
  20082. */
  20083. isEditing: false,
  20084.  
  20085. /**
  20086. * Indicates whether a text can be edited
  20087. * @type Boolean
  20088. * @default
  20089. */
  20090. editable: true,
  20091.  
  20092. /**
  20093. * Border color of text object while it's in editing mode
  20094. * @type String
  20095. * @default
  20096. */
  20097. editingBorderColor: 'rgba(102,153,255,0.25)',
  20098.  
  20099. /**
  20100. * Width of cursor (in px)
  20101. * @type Number
  20102. * @default
  20103. */
  20104. cursorWidth: 2,
  20105.  
  20106. /**
  20107. * Color of default cursor (when not overwritten by character style)
  20108. * @type String
  20109. * @default
  20110. */
  20111. cursorColor: '#333',
  20112.  
  20113. /**
  20114. * Delay between cursor blink (in ms)
  20115. * @type Number
  20116. * @default
  20117. */
  20118. cursorDelay: 1000,
  20119.  
  20120. /**
  20121. * Duration of cursor fadein (in ms)
  20122. * @type Number
  20123. * @default
  20124. */
  20125. cursorDuration: 600,
  20126.  
  20127. /**
  20128. * Object containing character styles
  20129. * (where top-level properties corresponds to line number and 2nd-level properties -- to char number in a line)
  20130. * @type Object
  20131. * @default
  20132. */
  20133. styles: null,
  20134.  
  20135. /**
  20136. * Indicates whether internal text char widths can be cached
  20137. * @type Boolean
  20138. * @default
  20139. */
  20140. caching: true,
  20141.  
  20142. /**
  20143. * @private
  20144. * @type Boolean
  20145. * @default
  20146. */
  20147. _skipFillStrokeCheck: true,
  20148.  
  20149. /**
  20150. * @private
  20151. */
  20152. _reSpace: /\s|\n/,
  20153.  
  20154. /**
  20155. * @private
  20156. */
  20157. _fontSizeFraction: 4,
  20158.  
  20159. /**
  20160. * @private
  20161. */
  20162. _currentCursorOpacity: 0,
  20163.  
  20164. /**
  20165. * @private
  20166. */
  20167. _selectionDirection: null,
  20168.  
  20169. /**
  20170. * @private
  20171. */
  20172. _abortCursorAnimation: false,
  20173.  
  20174. /**
  20175. * @private
  20176. */
  20177. _charWidthsCache: { },
  20178.  
  20179. /**
  20180. * Constructor
  20181. * @param {String} text Text string
  20182. * @param {Object} [options] Options object
  20183. * @return {fabric.IText} thisArg
  20184. */
  20185. initialize: function(text, options) {
  20186. this.styles = options ? (options.styles || { }) : { };
  20187. this.callSuper('initialize', text, options);
  20188. this.initBehavior();
  20189.  
  20190. fabric.IText.instances.push(this);
  20191.  
  20192. // caching
  20193. this.__lineWidths = { };
  20194. this.__lineHeights = { };
  20195. this.__lineOffsets = { };
  20196. },
  20197.  
  20198. /**
  20199. * Returns true if object has no styling
  20200. */
  20201. isEmptyStyles: function() {
  20202. if (!this.styles) {
  20203. return true;
  20204. }
  20205. var obj = this.styles;
  20206.  
  20207. for (var p1 in obj) {
  20208. for (var p2 in obj[p1]) {
  20209. /*jshint unused:false */
  20210. for (var p3 in obj[p1][p2]) {
  20211. return false;
  20212. }
  20213. }
  20214. }
  20215. return true;
  20216. },
  20217.  
  20218. /**
  20219. * Sets selection start (left boundary of a selection)
  20220. * @param {Number} index Index to set selection start to
  20221. */
  20222. setSelectionStart: function(index) {
  20223. if (this.selectionStart !== index) {
  20224. this.fire('selection:changed');
  20225. this.canvas && this.canvas.fire('text:selection:changed', { target: this });
  20226. }
  20227. this.selectionStart = index;
  20228. this.hiddenTextarea && (this.hiddenTextarea.selectionStart = index);
  20229. },
  20230.  
  20231. /**
  20232. * Sets selection end (right boundary of a selection)
  20233. * @param {Number} index Index to set selection end to
  20234. */
  20235. setSelectionEnd: function(index) {
  20236. if (this.selectionEnd !== index) {
  20237. this.fire('selection:changed');
  20238. this.canvas && this.canvas.fire('text:selection:changed', { target: this });
  20239. }
  20240. this.selectionEnd = index;
  20241. this.hiddenTextarea && (this.hiddenTextarea.selectionEnd = index);
  20242. },
  20243.  
  20244. /**
  20245. * Gets style of a current selection/cursor (at the start position)
  20246. * @param {Number} [startIndex] Start index to get styles at
  20247. * @param {Number} [endIndex] End index to get styles at
  20248. * @return {Object} styles Style object at a specified (or current) index
  20249. */
  20250. getSelectionStyles: function(startIndex, endIndex) {
  20251.  
  20252. if (arguments.length === 2) {
  20253. var styles = [ ];
  20254. for (var i = startIndex; i < endIndex; i++) {
  20255. styles.push(this.getSelectionStyles(i));
  20256. }
  20257. return styles;
  20258. }
  20259.  
  20260. var loc = this.get2DCursorLocation(startIndex);
  20261. if (this.styles[loc.lineIndex]) {
  20262. return this.styles[loc.lineIndex][loc.charIndex] || { };
  20263. }
  20264.  
  20265. return { };
  20266. },
  20267.  
  20268. /**
  20269. * Sets style of a current selection
  20270. * @param {Object} [styles] Styles object
  20271. * @return {fabric.IText} thisArg
  20272. * @chainable
  20273. */
  20274. setSelectionStyles: function(styles) {
  20275. if (this.selectionStart === this.selectionEnd) {
  20276. this._extendStyles(this.selectionStart, styles);
  20277. }
  20278. else {
  20279. for (var i = this.selectionStart; i < this.selectionEnd; i++) {
  20280. this._extendStyles(i, styles);
  20281. }
  20282. }
  20283. return this;
  20284. },
  20285.  
  20286. /**
  20287. * @private
  20288. */
  20289. _extendStyles: function(index, styles) {
  20290. var loc = this.get2DCursorLocation(index);
  20291.  
  20292. if (!this.styles[loc.lineIndex]) {
  20293. this.styles[loc.lineIndex] = { };
  20294. }
  20295. if (!this.styles[loc.lineIndex][loc.charIndex]) {
  20296. this.styles[loc.lineIndex][loc.charIndex] = { };
  20297. }
  20298.  
  20299. fabric.util.object.extend(this.styles[loc.lineIndex][loc.charIndex], styles);
  20300. },
  20301.  
  20302. /**
  20303. * @private
  20304. * @param {CanvasRenderingContext2D} ctx Context to render on
  20305. */
  20306. _render: function(ctx) {
  20307. this.callSuper('_render', ctx);
  20308. this.ctx = ctx;
  20309. this.isEditing && this.renderCursorOrSelection();
  20310. },
  20311.  
  20312. /**
  20313. * Renders cursor or selection (depending on what exists)
  20314. */
  20315. renderCursorOrSelection: function() {
  20316. if (!this.active) {
  20317. return;
  20318. }
  20319.  
  20320. var chars = this.text.split(''),
  20321. boundaries;
  20322.  
  20323. if (this.selectionStart === this.selectionEnd) {
  20324. boundaries = this._getCursorBoundaries(chars, 'cursor');
  20325. this.renderCursor(boundaries);
  20326. }
  20327. else {
  20328. boundaries = this._getCursorBoundaries(chars, 'selection');
  20329. this.renderSelection(chars, boundaries);
  20330. }
  20331. },
  20332.  
  20333. /**
  20334. * Returns 2d representation (lineIndex and charIndex) of cursor (or selection start)
  20335. * @param {Number} [selectionStart] Optional index. When not given, current selectionStart is used.
  20336. */
  20337. get2DCursorLocation: function(selectionStart) {
  20338. if (typeof selectionStart === 'undefined') {
  20339. selectionStart = this.selectionStart;
  20340. }
  20341. var textBeforeCursor = this.text.slice(0, selectionStart),
  20342. linesBeforeCursor = textBeforeCursor.split(this._reNewline);
  20343.  
  20344. return {
  20345. lineIndex: linesBeforeCursor.length - 1,
  20346. charIndex: linesBeforeCursor[linesBeforeCursor.length - 1].length
  20347. };
  20348. },
  20349.  
  20350. /**
  20351. * Returns complete style of char at the current cursor
  20352. * @param {Number} lineIndex Line index
  20353. * @param {Number} charIndex Char index
  20354. * @return {Object} Character style
  20355. */
  20356. getCurrentCharStyle: function(lineIndex, charIndex) {
  20357. var style = this.styles[lineIndex] && this.styles[lineIndex][charIndex === 0 ? 0 : (charIndex - 1)];
  20358.  
  20359. return {
  20360. fontSize: style && style.fontSize || this.fontSize,
  20361. fill: style && style.fill || this.fill,
  20362. textBackgroundColor: style && style.textBackgroundColor || this.textBackgroundColor,
  20363. textDecoration: style && style.textDecoration || this.textDecoration,
  20364. fontFamily: style && style.fontFamily || this.fontFamily,
  20365. fontWeight: style && style.fontWeight || this.fontWeight,
  20366. fontStyle: style && style.fontStyle || this.fontStyle,
  20367. stroke: style && style.stroke || this.stroke,
  20368. strokeWidth: style && style.strokeWidth || this.strokeWidth
  20369. };
  20370. },
  20371.  
  20372. /**
  20373. * Returns fontSize of char at the current cursor
  20374. * @param {Number} lineIndex Line index
  20375. * @param {Number} charIndex Char index
  20376. * @return {Number} Character font size
  20377. */
  20378. getCurrentCharFontSize: function(lineIndex, charIndex) {
  20379. return (
  20380. this.styles[lineIndex] &&
  20381. this.styles[lineIndex][charIndex === 0 ? 0 : (charIndex - 1)] &&
  20382. this.styles[lineIndex][charIndex === 0 ? 0 : (charIndex - 1)].fontSize) || this.fontSize;
  20383. },
  20384.  
  20385. /**
  20386. * Returns color (fill) of char at the current cursor
  20387. * @param {Number} lineIndex Line index
  20388. * @param {Number} charIndex Char index
  20389. * @return {String} Character color (fill)
  20390. */
  20391. getCurrentCharColor: function(lineIndex, charIndex) {
  20392. return (
  20393. this.styles[lineIndex] &&
  20394. this.styles[lineIndex][charIndex === 0 ? 0 : (charIndex - 1)] &&
  20395. this.styles[lineIndex][charIndex === 0 ? 0 : (charIndex - 1)].fill) || this.cursorColor;
  20396. },
  20397.  
  20398. /**
  20399. * Returns cursor boundaries (left, top, leftOffset, topOffset)
  20400. * @private
  20401. * @param {Array} chars Array of characters
  20402. * @param {String} typeOfBoundaries
  20403. */
  20404. _getCursorBoundaries: function(chars, typeOfBoundaries) {
  20405.  
  20406. var cursorLocation = this.get2DCursorLocation(),
  20407.  
  20408. textLines = this.text.split(this._reNewline),
  20409.  
  20410. // left/top are left/top of entire text box
  20411. // leftOffset/topOffset are offset from that left/top point of a text box
  20412.  
  20413. left = Math.round(this._getLeftOffset()),
  20414. top = this._getTopOffset(),
  20415.  
  20416. offsets = this._getCursorBoundariesOffsets(
  20417. chars, typeOfBoundaries, cursorLocation, textLines);
  20418.  
  20419. return {
  20420. left: left,
  20421. top: top,
  20422. leftOffset: offsets.left + offsets.lineLeft,
  20423. topOffset: offsets.top
  20424. };
  20425. },
  20426.  
  20427. /**
  20428. * @private
  20429. */
  20430. _getCursorBoundariesOffsets: function(chars, typeOfBoundaries, cursorLocation, textLines) {
  20431.  
  20432. var lineLeftOffset = 0,
  20433.  
  20434. lineIndex = 0,
  20435. charIndex = 0,
  20436.  
  20437. leftOffset = 0,
  20438. topOffset = typeOfBoundaries === 'cursor'
  20439. // selection starts at the very top of the line,
  20440. // whereas cursor starts at the padding created by line height
  20441. ? (this._getHeightOfLine(this.ctx, 0) -
  20442. this.getCurrentCharFontSize(cursorLocation.lineIndex, cursorLocation.charIndex))
  20443. : 0;
  20444.  
  20445. for (var i = 0; i < this.selectionStart; i++) {
  20446. if (chars[i] === '\n') {
  20447. leftOffset = 0;
  20448. var index = lineIndex + (typeOfBoundaries === 'cursor' ? 1 : 0);
  20449. topOffset += this._getCachedLineHeight(index);
  20450.  
  20451. lineIndex++;
  20452. charIndex = 0;
  20453. }
  20454. else {
  20455. leftOffset += this._getWidthOfChar(this.ctx, chars[i], lineIndex, charIndex);
  20456. charIndex++;
  20457. }
  20458.  
  20459. lineLeftOffset = this._getCachedLineOffset(lineIndex, textLines);
  20460. }
  20461.  
  20462. this._clearCache();
  20463.  
  20464. return {
  20465. top: topOffset,
  20466. left: leftOffset,
  20467. lineLeft: lineLeftOffset
  20468. };
  20469. },
  20470.  
  20471. /**
  20472. * @private
  20473. */
  20474. _clearCache: function() {
  20475. this.__lineWidths = { };
  20476. this.__lineHeights = { };
  20477. this.__lineOffsets = { };
  20478. },
  20479.  
  20480. /**
  20481. * @private
  20482. */
  20483. _getCachedLineHeight: function(index) {
  20484. return this.__lineHeights[index] ||
  20485. (this.__lineHeights[index] = this._getHeightOfLine(this.ctx, index));
  20486. },
  20487.  
  20488. /**
  20489. * @private
  20490. */
  20491. _getCachedLineWidth: function(lineIndex, textLines) {
  20492. return this.__lineWidths[lineIndex] ||
  20493. (this.__lineWidths[lineIndex] = this._getWidthOfLine(this.ctx, lineIndex, textLines));
  20494. },
  20495.  
  20496. /**
  20497. * @private
  20498. */
  20499. _getCachedLineOffset: function(lineIndex, textLines) {
  20500. var widthOfLine = this._getCachedLineWidth(lineIndex, textLines);
  20501.  
  20502. return this.__lineOffsets[lineIndex] ||
  20503. (this.__lineOffsets[lineIndex] = this._getLineLeftOffset(widthOfLine));
  20504. },
  20505.  
  20506. /**
  20507. * Renders cursor
  20508. * @param {Object} boundaries
  20509. */
  20510. renderCursor: function(boundaries) {
  20511. var ctx = this.ctx;
  20512.  
  20513. ctx.save();
  20514.  
  20515. var cursorLocation = this.get2DCursorLocation(),
  20516. lineIndex = cursorLocation.lineIndex,
  20517. charIndex = cursorLocation.charIndex,
  20518. charHeight = this.getCurrentCharFontSize(lineIndex, charIndex),
  20519. leftOffset = (lineIndex === 0 && charIndex === 0)
  20520. ? this._getCachedLineOffset(lineIndex, this.text.split(this._reNewline))
  20521. : boundaries.leftOffset;
  20522.  
  20523. ctx.fillStyle = this.getCurrentCharColor(lineIndex, charIndex);
  20524. ctx.globalAlpha = this.__isMousedown ? 1 : this._currentCursorOpacity;
  20525.  
  20526. ctx.fillRect(
  20527. boundaries.left + leftOffset,
  20528. boundaries.top + boundaries.topOffset,
  20529. this.cursorWidth / this.scaleX,
  20530. charHeight);
  20531.  
  20532. ctx.restore();
  20533. },
  20534.  
  20535. /**
  20536. * Renders text selection
  20537. * @param {Array} chars Array of characters
  20538. * @param {Object} boundaries Object with left/top/leftOffset/topOffset
  20539. */
  20540. renderSelection: function(chars, boundaries) {
  20541. var ctx = this.ctx;
  20542.  
  20543. ctx.save();
  20544.  
  20545. ctx.fillStyle = this.selectionColor;
  20546.  
  20547. var start = this.get2DCursorLocation(this.selectionStart),
  20548. end = this.get2DCursorLocation(this.selectionEnd),
  20549. startLine = start.lineIndex,
  20550. endLine = end.lineIndex,
  20551. textLines = this.text.split(this._reNewline);
  20552.  
  20553. for (var i = startLine; i <= endLine; i++) {
  20554. var lineOffset = this._getCachedLineOffset(i, textLines) || 0,
  20555. lineHeight = this._getCachedLineHeight(i),
  20556. boxWidth = 0;
  20557.  
  20558. if (i === startLine) {
  20559. for (var j = 0, len = textLines[i].length; j < len; j++) {
  20560. if (j >= start.charIndex && (i !== endLine || j < end.charIndex)) {
  20561. boxWidth += this._getWidthOfChar(ctx, textLines[i][j], i, j);
  20562. }
  20563. if (j < start.charIndex) {
  20564. lineOffset += this._getWidthOfChar(ctx, textLines[i][j], i, j);
  20565. }
  20566. }
  20567. }
  20568. else if (i > startLine && i < endLine) {
  20569. boxWidth += this._getCachedLineWidth(i, textLines) || 5;
  20570. }
  20571. else if (i === endLine) {
  20572. for (var j2 = 0, j2len = end.charIndex; j2 < j2len; j2++) {
  20573. boxWidth += this._getWidthOfChar(ctx, textLines[i][j2], i, j2);
  20574. }
  20575. }
  20576.  
  20577. ctx.fillRect(
  20578. boundaries.left + lineOffset,
  20579. boundaries.top + boundaries.topOffset,
  20580. boxWidth,
  20581. lineHeight);
  20582.  
  20583. boundaries.topOffset += lineHeight;
  20584. }
  20585. ctx.restore();
  20586. },
  20587.  
  20588. /**
  20589. * @private
  20590. * @param {String} method
  20591. * @param {CanvasRenderingContext2D} ctx Context to render on
  20592. */
  20593. _renderChars: function(method, ctx, line, left, top, lineIndex) {
  20594.  
  20595. if (this.isEmptyStyles()) {
  20596. return this._renderCharsFast(method, ctx, line, left, top);
  20597. }
  20598.  
  20599. this.skipTextAlign = true;
  20600.  
  20601. // set proper box offset
  20602. left -= this.textAlign === 'center'
  20603. ? (this.width / 2)
  20604. : (this.textAlign === 'right')
  20605. ? this.width
  20606. : 0;
  20607.  
  20608. // set proper line offset
  20609. var textLines = this.text.split(this._reNewline),
  20610. lineWidth = this._getWidthOfLine(ctx, lineIndex, textLines),
  20611. lineHeight = this._getHeightOfLine(ctx, lineIndex, textLines),
  20612. lineLeftOffset = this._getLineLeftOffset(lineWidth),
  20613. chars = line.split(''),
  20614. prevStyle,
  20615. charsToRender = '';
  20616.  
  20617. left += lineLeftOffset || 0;
  20618.  
  20619. ctx.save();
  20620.  
  20621. for (var i = 0, len = chars.length; i <= len; i++) {
  20622. prevStyle = prevStyle || this.getCurrentCharStyle(lineIndex, i);
  20623. var thisStyle = this.getCurrentCharStyle(lineIndex, i + 1);
  20624.  
  20625. if (this._hasStyleChanged(prevStyle, thisStyle) || i === len) {
  20626. this._renderChar(method, ctx, lineIndex, i - 1, charsToRender, left, top, lineHeight);
  20627. charsToRender = '';
  20628. prevStyle = thisStyle;
  20629. }
  20630. charsToRender += chars[i];
  20631. }
  20632.  
  20633. ctx.restore();
  20634. },
  20635.  
  20636. /**
  20637. * @private
  20638. * @param {String} method
  20639. * @param {CanvasRenderingContext2D} ctx Context to render on
  20640. * @param {String} line Content of the line
  20641. * @param {Number} left Left coordinate
  20642. * @param {Number} top Top coordinate
  20643. */
  20644. _renderCharsFast: function(method, ctx, line, left, top) {
  20645. this.skipTextAlign = false;
  20646.  
  20647. if (method === 'fillText' && this.fill) {
  20648. this.callSuper('_renderChars', method, ctx, line, left, top);
  20649. }
  20650. if (method === 'strokeText' && this.stroke) {
  20651. this.callSuper('_renderChars', method, ctx, line, left, top);
  20652. }
  20653. },
  20654.  
  20655. /**
  20656. * @private
  20657. * @param {String} method
  20658. * @param {CanvasRenderingContext2D} ctx Context to render on
  20659. * @param {Number} lineIndex
  20660. * @param {Number} i
  20661. * @param {String} _char
  20662. * @param {Number} left Left coordinate
  20663. * @param {Number} top Top coordinate
  20664. * @param {Number} lineHeight Height of the line
  20665. */
  20666. _renderChar: function(method, ctx, lineIndex, i, _char, left, top, lineHeight) {
  20667. var decl, charWidth, charHeight;
  20668.  
  20669. if (this.styles && this.styles[lineIndex] && (decl = this.styles[lineIndex][i])) {
  20670.  
  20671. var shouldStroke = decl.stroke || this.stroke,
  20672. shouldFill = decl.fill || this.fill;
  20673.  
  20674. ctx.save();
  20675. charWidth = this._applyCharStylesGetWidth(ctx, _char, lineIndex, i, decl);
  20676. charHeight = this._getHeightOfChar(ctx, _char, lineIndex, i);
  20677.  
  20678. if (shouldFill) {
  20679. ctx.fillText(_char, left, top);
  20680. }
  20681. if (shouldStroke) {
  20682. ctx.strokeText(_char, left, top);
  20683. }
  20684.  
  20685. this._renderCharDecoration(ctx, decl, left, top, charWidth, lineHeight, charHeight);
  20686. ctx.restore();
  20687.  
  20688. ctx.translate(charWidth, 0);
  20689. }
  20690. else {
  20691. if (method === 'strokeText' && this.stroke) {
  20692. ctx[method](_char, left, top);
  20693. }
  20694. if (method === 'fillText' && this.fill) {
  20695. ctx[method](_char, left, top);
  20696. }
  20697. charWidth = this._applyCharStylesGetWidth(ctx, _char, lineIndex, i);
  20698. this._renderCharDecoration(ctx, null, left, top, charWidth, lineHeight);
  20699.  
  20700. ctx.translate(ctx.measureText(_char).width, 0);
  20701. }
  20702. },
  20703.  
  20704. /**
  20705. * @private
  20706. * @param {Object} prevStyle
  20707. * @param {Object} thisStyle
  20708. */
  20709. _hasStyleChanged: function(prevStyle, thisStyle) {
  20710. return (prevStyle.fill !== thisStyle.fill ||
  20711. prevStyle.fontSize !== thisStyle.fontSize ||
  20712. prevStyle.textBackgroundColor !== thisStyle.textBackgroundColor ||
  20713. prevStyle.textDecoration !== thisStyle.textDecoration ||
  20714. prevStyle.fontFamily !== thisStyle.fontFamily ||
  20715. prevStyle.fontWeight !== thisStyle.fontWeight ||
  20716. prevStyle.fontStyle !== thisStyle.fontStyle ||
  20717. prevStyle.stroke !== thisStyle.stroke ||
  20718. prevStyle.strokeWidth !== thisStyle.strokeWidth
  20719. );
  20720. },
  20721.  
  20722. /**
  20723. * @private
  20724. * @param {CanvasRenderingContext2D} ctx Context to render on
  20725. */
  20726. _renderCharDecoration: function(ctx, styleDeclaration, left, top, charWidth, lineHeight, charHeight) {
  20727.  
  20728. var textDecoration = styleDeclaration
  20729. ? (styleDeclaration.textDecoration || this.textDecoration)
  20730. : this.textDecoration,
  20731.  
  20732. fontSize = (styleDeclaration ? styleDeclaration.fontSize : null) || this.fontSize;
  20733.  
  20734. if (!textDecoration) {
  20735. return;
  20736. }
  20737.  
  20738. if (textDecoration.indexOf('underline') > -1) {
  20739. this._renderCharDecorationAtOffset(
  20740. ctx,
  20741. left,
  20742. top + (this.fontSize / this._fontSizeFraction),
  20743. charWidth,
  20744. 0,
  20745. this.fontSize / 20
  20746. );
  20747. }
  20748. if (textDecoration.indexOf('line-through') > -1) {
  20749. this._renderCharDecorationAtOffset(
  20750. ctx,
  20751. left,
  20752. top + (this.fontSize / this._fontSizeFraction),
  20753. charWidth,
  20754. charHeight / 2,
  20755. fontSize / 20
  20756. );
  20757. }
  20758. if (textDecoration.indexOf('overline') > -1) {
  20759. this._renderCharDecorationAtOffset(
  20760. ctx,
  20761. left,
  20762. top,
  20763. charWidth,
  20764. lineHeight - (this.fontSize / this._fontSizeFraction),
  20765. this.fontSize / 20
  20766. );
  20767. }
  20768. },
  20769.  
  20770. /**
  20771. * @private
  20772. * @param {CanvasRenderingContext2D} ctx Context to render on
  20773. */
  20774. _renderCharDecorationAtOffset: function(ctx, left, top, charWidth, offset, thickness) {
  20775. ctx.fillRect(left, top - offset, charWidth, thickness);
  20776. },
  20777.  
  20778. /**
  20779. * @private
  20780. * @param {String} method
  20781. * @param {CanvasRenderingContext2D} ctx Context to render on
  20782. * @param {String} line
  20783. */
  20784. _renderTextLine: function(method, ctx, line, left, top, lineIndex) {
  20785. // to "cancel" this.fontSize subtraction in fabric.Text#_renderTextLine
  20786. top += this.fontSize / 4;
  20787. this.callSuper('_renderTextLine', method, ctx, line, left, top, lineIndex);
  20788. },
  20789.  
  20790. /**
  20791. * @private
  20792. * @param {CanvasRenderingContext2D} ctx Context to render on
  20793. * @param {Array} textLines
  20794. */
  20795. _renderTextDecoration: function(ctx, textLines) {
  20796. if (this.isEmptyStyles()) {
  20797. return this.callSuper('_renderTextDecoration', ctx, textLines);
  20798. }
  20799. },
  20800.  
  20801. /**
  20802. * @private
  20803. * @param {CanvasRenderingContext2D} ctx Context to render on
  20804. * @param {Array} textLines Array of all text lines
  20805. */
  20806. _renderTextLinesBackground: function(ctx, textLines) {
  20807. if (!this.textBackgroundColor && !this.styles) {
  20808. return;
  20809. }
  20810.  
  20811. ctx.save();
  20812.  
  20813. if (this.textBackgroundColor) {
  20814. ctx.fillStyle = this.textBackgroundColor;
  20815. }
  20816.  
  20817. var lineHeights = 0,
  20818. fractionOfFontSize = this.fontSize / this._fontSizeFraction;
  20819.  
  20820. for (var i = 0, len = textLines.length; i < len; i++) {
  20821.  
  20822. var heightOfLine = this._getHeightOfLine(ctx, i, textLines);
  20823. if (textLines[i] === '') {
  20824. lineHeights += heightOfLine;
  20825. continue;
  20826. }
  20827.  
  20828. var lineWidth = this._getWidthOfLine(ctx, i, textLines),
  20829. lineLeftOffset = this._getLineLeftOffset(lineWidth);
  20830.  
  20831. if (this.textBackgroundColor) {
  20832. ctx.fillStyle = this.textBackgroundColor;
  20833.  
  20834. ctx.fillRect(
  20835. this._getLeftOffset() + lineLeftOffset,
  20836. this._getTopOffset() + lineHeights + fractionOfFontSize,
  20837. lineWidth,
  20838. heightOfLine
  20839. );
  20840. }
  20841. if (this.styles[i]) {
  20842. for (var j = 0, jlen = textLines[i].length; j < jlen; j++) {
  20843. if (this.styles[i] && this.styles[i][j] && this.styles[i][j].textBackgroundColor) {
  20844.  
  20845. var _char = textLines[i][j];
  20846.  
  20847. ctx.fillStyle = this.styles[i][j].textBackgroundColor;
  20848.  
  20849. ctx.fillRect(
  20850. this._getLeftOffset() + lineLeftOffset + this._getWidthOfCharsAt(ctx, i, j, textLines),
  20851. this._getTopOffset() + lineHeights + fractionOfFontSize,
  20852. this._getWidthOfChar(ctx, _char, i, j, textLines) + 1,
  20853. heightOfLine
  20854. );
  20855. }
  20856. }
  20857. }
  20858. lineHeights += heightOfLine;
  20859. }
  20860. ctx.restore();
  20861. },
  20862.  
  20863. /**
  20864. * @private
  20865. */
  20866. _getCacheProp: function(_char, styleDeclaration) {
  20867. return _char +
  20868.  
  20869. styleDeclaration.fontFamily +
  20870. styleDeclaration.fontSize +
  20871. styleDeclaration.fontWeight +
  20872. styleDeclaration.fontStyle +
  20873.  
  20874. styleDeclaration.shadow;
  20875. },
  20876.  
  20877. /**
  20878. * @private
  20879. * @param {CanvasRenderingContext2D} ctx Context to render on
  20880. * @param {String} _char
  20881. * @param {Number} lineIndex
  20882. * @param {Number} charIndex
  20883. * @param {Object} [decl]
  20884. */
  20885. _applyCharStylesGetWidth: function(ctx, _char, lineIndex, charIndex, decl) {
  20886. var styleDeclaration = decl ||
  20887. (this.styles[lineIndex] &&
  20888. this.styles[lineIndex][charIndex]);
  20889.  
  20890. if (styleDeclaration) {
  20891. // cloning so that original style object is not polluted with following font declarations
  20892. styleDeclaration = clone(styleDeclaration);
  20893. }
  20894. else {
  20895. styleDeclaration = { };
  20896. }
  20897.  
  20898. this._applyFontStyles(styleDeclaration);
  20899.  
  20900. var cacheProp = this._getCacheProp(_char, styleDeclaration);
  20901.  
  20902. // short-circuit if no styles
  20903. if (this.isEmptyStyles() && this._charWidthsCache[cacheProp] && this.caching) {
  20904. return this._charWidthsCache[cacheProp];
  20905. }
  20906.  
  20907. if (typeof styleDeclaration.shadow === 'string') {
  20908. styleDeclaration.shadow = new fabric.Shadow(styleDeclaration.shadow);
  20909. }
  20910.  
  20911. var fill = styleDeclaration.fill || this.fill;
  20912. ctx.fillStyle = fill.toLive
  20913. ? fill.toLive(ctx)
  20914. : fill;
  20915.  
  20916. if (styleDeclaration.stroke) {
  20917. ctx.strokeStyle = (styleDeclaration.stroke && styleDeclaration.stroke.toLive)
  20918. ? styleDeclaration.stroke.toLive(ctx)
  20919. : styleDeclaration.stroke;
  20920. }
  20921.  
  20922. ctx.lineWidth = styleDeclaration.strokeWidth || this.strokeWidth;
  20923. ctx.font = this._getFontDeclaration.call(styleDeclaration);
  20924. this._setShadow.call(styleDeclaration, ctx);
  20925.  
  20926. if (!this.caching) {
  20927. return ctx.measureText(_char).width;
  20928. }
  20929.  
  20930. if (!this._charWidthsCache[cacheProp]) {
  20931. this._charWidthsCache[cacheProp] = ctx.measureText(_char).width;
  20932. }
  20933.  
  20934. return this._charWidthsCache[cacheProp];
  20935. },
  20936.  
  20937. /**
  20938. * @private
  20939. * @param {Object} styleDeclaration
  20940. */
  20941. _applyFontStyles: function(styleDeclaration) {
  20942. if (!styleDeclaration.fontFamily) {
  20943. styleDeclaration.fontFamily = this.fontFamily;
  20944. }
  20945. if (!styleDeclaration.fontSize) {
  20946. styleDeclaration.fontSize = this.fontSize;
  20947. }
  20948. if (!styleDeclaration.fontWeight) {
  20949. styleDeclaration.fontWeight = this.fontWeight;
  20950. }
  20951. if (!styleDeclaration.fontStyle) {
  20952. styleDeclaration.fontStyle = this.fontStyle;
  20953. }
  20954. },
  20955.  
  20956. /**
  20957. * @private
  20958. * @param {Number} lineIndex
  20959. * @param {Number} charIndex
  20960. */
  20961. _getStyleDeclaration: function(lineIndex, charIndex) {
  20962. return (this.styles[lineIndex] && this.styles[lineIndex][charIndex])
  20963. ? clone(this.styles[lineIndex][charIndex])
  20964. : { };
  20965. },
  20966.  
  20967. /**
  20968. * @private
  20969. * @param {CanvasRenderingContext2D} ctx Context to render on
  20970. */
  20971. _getWidthOfChar: function(ctx, _char, lineIndex, charIndex) {
  20972. if (this.textAlign === 'justify' && /\s/.test(_char)) {
  20973. return this._getWidthOfSpace(ctx, lineIndex);
  20974. }
  20975.  
  20976. var styleDeclaration = this._getStyleDeclaration(lineIndex, charIndex);
  20977. this._applyFontStyles(styleDeclaration);
  20978. var cacheProp = this._getCacheProp(_char, styleDeclaration);
  20979.  
  20980. if (this._charWidthsCache[cacheProp] && this.caching) {
  20981. return this._charWidthsCache[cacheProp];
  20982. }
  20983. else if (ctx) {
  20984. ctx.save();
  20985. var width = this._applyCharStylesGetWidth(ctx, _char, lineIndex, charIndex);
  20986. ctx.restore();
  20987. return width;
  20988. }
  20989. },
  20990.  
  20991. /**
  20992. * @private
  20993. * @param {CanvasRenderingContext2D} ctx Context to render on
  20994. */
  20995. _getHeightOfChar: function(ctx, _char, lineIndex, charIndex) {
  20996. if (this.styles[lineIndex] && this.styles[lineIndex][charIndex]) {
  20997. return this.styles[lineIndex][charIndex].fontSize || this.fontSize;
  20998. }
  20999. return this.fontSize;
  21000. },
  21001.  
  21002. /**
  21003. * @private
  21004. * @param {CanvasRenderingContext2D} ctx Context to render on
  21005. */
  21006. _getWidthOfCharAt: function(ctx, lineIndex, charIndex, lines) {
  21007. lines = lines || this.text.split(this._reNewline);
  21008. var _char = lines[lineIndex].split('')[charIndex];
  21009. return this._getWidthOfChar(ctx, _char, lineIndex, charIndex);
  21010. },
  21011.  
  21012. /**
  21013. * @private
  21014. * @param {CanvasRenderingContext2D} ctx Context to render on
  21015. */
  21016. _getHeightOfCharAt: function(ctx, lineIndex, charIndex, lines) {
  21017. lines = lines || this.text.split(this._reNewline);
  21018. var _char = lines[lineIndex].split('')[charIndex];
  21019. return this._getHeightOfChar(ctx, _char, lineIndex, charIndex);
  21020. },
  21021.  
  21022. /**
  21023. * @private
  21024. * @param {CanvasRenderingContext2D} ctx Context to render on
  21025. */
  21026. _getWidthOfCharsAt: function(ctx, lineIndex, charIndex, lines) {
  21027. var width = 0;
  21028. for (var i = 0; i < charIndex; i++) {
  21029. width += this._getWidthOfCharAt(ctx, lineIndex, i, lines);
  21030. }
  21031. return width;
  21032. },
  21033.  
  21034. /**
  21035. * @private
  21036. * @param {CanvasRenderingContext2D} ctx Context to render on
  21037. */
  21038. _getWidthOfLine: function(ctx, lineIndex, textLines) {
  21039. // if (!this.styles[lineIndex]) {
  21040. // return this.callSuper('_getLineWidth', ctx, textLines[lineIndex]);
  21041. // }
  21042. return this._getWidthOfCharsAt(ctx, lineIndex, textLines[lineIndex].length, textLines);
  21043. },
  21044.  
  21045. /**
  21046. * @private
  21047. * @param {CanvasRenderingContext2D} ctx Context to render on
  21048. * @param {Number} lineIndex
  21049. */
  21050. _getWidthOfSpace: function (ctx, lineIndex) {
  21051. var lines = this.text.split(this._reNewline),
  21052. line = lines[lineIndex],
  21053. words = line.split(/\s+/),
  21054. wordsWidth = this._getWidthOfWords(ctx, line, lineIndex),
  21055. widthDiff = this.width - wordsWidth,
  21056. numSpaces = words.length - 1,
  21057. width = widthDiff / numSpaces;
  21058.  
  21059. return width;
  21060. },
  21061.  
  21062. /**
  21063. * @private
  21064. * @param {CanvasRenderingContext2D} ctx Context to render on
  21065. * @param {Number} line
  21066. * @param {Number} lineIndex
  21067. */
  21068. _getWidthOfWords: function (ctx, line, lineIndex) {
  21069. var width = 0;
  21070.  
  21071. for (var charIndex = 0; charIndex < line.length; charIndex++) {
  21072. var _char = line[charIndex];
  21073.  
  21074. if (!_char.match(/\s/)) {
  21075. width += this._getWidthOfChar(ctx, _char, lineIndex, charIndex);
  21076. }
  21077. }
  21078.  
  21079. return width;
  21080. },
  21081.  
  21082. /**
  21083. * @private
  21084. * @param {CanvasRenderingContext2D} ctx Context to render on
  21085. */
  21086. _getTextWidth: function(ctx, textLines) {
  21087.  
  21088. if (this.isEmptyStyles()) {
  21089. return this.callSuper('_getTextWidth', ctx, textLines);
  21090. }
  21091.  
  21092. var maxWidth = this._getWidthOfLine(ctx, 0, textLines);
  21093.  
  21094. for (var i = 1, len = textLines.length; i < len; i++) {
  21095. var currentLineWidth = this._getWidthOfLine(ctx, i, textLines);
  21096. if (currentLineWidth > maxWidth) {
  21097. maxWidth = currentLineWidth;
  21098. }
  21099. }
  21100. return maxWidth;
  21101. },
  21102.  
  21103. /**
  21104. * @private
  21105. * @param {CanvasRenderingContext2D} ctx Context to render on
  21106. */
  21107. _getHeightOfLine: function(ctx, lineIndex, textLines) {
  21108.  
  21109. textLines = textLines || this.text.split(this._reNewline);
  21110.  
  21111. var maxHeight = this._getHeightOfChar(ctx, textLines[lineIndex][0], lineIndex, 0),
  21112. line = textLines[lineIndex],
  21113. chars = line.split('');
  21114.  
  21115. for (var i = 1, len = chars.length; i < len; i++) {
  21116. var currentCharHeight = this._getHeightOfChar(ctx, chars[i], lineIndex, i);
  21117. if (currentCharHeight > maxHeight) {
  21118. maxHeight = currentCharHeight;
  21119. }
  21120. }
  21121.  
  21122. return maxHeight * this.lineHeight;
  21123. },
  21124.  
  21125. /**
  21126. * @private
  21127. * @param {CanvasRenderingContext2D} ctx Context to render on
  21128. * @param {Array} textLines Array of all text lines
  21129. */
  21130. _getTextHeight: function(ctx, textLines) {
  21131. var height = 0;
  21132. for (var i = 0, len = textLines.length; i < len; i++) {
  21133. height += this._getHeightOfLine(ctx, i, textLines);
  21134. }
  21135. return height;
  21136. },
  21137.  
  21138. /**
  21139. * @private
  21140. */
  21141. _getTopOffset: function() {
  21142. var topOffset = fabric.Text.prototype._getTopOffset.call(this);
  21143. return topOffset - (this.fontSize / this._fontSizeFraction);
  21144. },
  21145.  
  21146. /**
  21147. * This method is overwritten to account for different top offset
  21148. * @private
  21149. */
  21150. _renderTextBoxBackground: function(ctx) {
  21151. if (!this.backgroundColor) {
  21152. return;
  21153. }
  21154.  
  21155. ctx.save();
  21156. ctx.fillStyle = this.backgroundColor;
  21157.  
  21158. ctx.fillRect(
  21159. this._getLeftOffset(),
  21160. this._getTopOffset() + (this.fontSize / this._fontSizeFraction),
  21161. this.width,
  21162. this.height
  21163. );
  21164.  
  21165. ctx.restore();
  21166. },
  21167.  
  21168. /**
  21169. * Returns object representation of an instance
  21170. * @method toObject
  21171. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  21172. * @return {Object} object representation of an instance
  21173. */
  21174. toObject: function(propertiesToInclude) {
  21175. return fabric.util.object.extend(this.callSuper('toObject', propertiesToInclude), {
  21176. styles: clone(this.styles)
  21177. });
  21178. }
  21179. });
  21180.  
  21181. /**
  21182. * Returns fabric.IText instance from an object representation
  21183. * @static
  21184. * @memberOf fabric.IText
  21185. * @param {Object} object Object to create an instance from
  21186. * @return {fabric.IText} instance of fabric.IText
  21187. */
  21188. fabric.IText.fromObject = function(object) {
  21189. return new fabric.IText(object.text, clone(object));
  21190. };
  21191.  
  21192. /**
  21193. * Contains all fabric.IText objects that have been created
  21194. * @static
  21195. * @memberof fabric.IText
  21196. * @type Array
  21197. */
  21198. fabric.IText.instances = [ ];
  21199.  
  21200. })();
  21201.  
  21202.  
  21203. (function() {
  21204.  
  21205. var clone = fabric.util.object.clone;
  21206.  
  21207. fabric.util.object.extend(fabric.IText.prototype, /** @lends fabric.IText.prototype */ {
  21208.  
  21209. /**
  21210. * Initializes all the interactive behavior of IText
  21211. */
  21212. initBehavior: function() {
  21213. this.initAddedHandler();
  21214. this.initCursorSelectionHandlers();
  21215. this.initDoubleClickSimulation();
  21216. },
  21217.  
  21218. /**
  21219. * Initializes "selected" event handler
  21220. */
  21221. initSelectedHandler: function() {
  21222. this.on('selected', function() {
  21223.  
  21224. var _this = this;
  21225. setTimeout(function() {
  21226. _this.selected = true;
  21227. }, 100);
  21228. });
  21229. },
  21230.  
  21231. /**
  21232. * Initializes "added" event handler
  21233. */
  21234. initAddedHandler: function() {
  21235. this.on('added', function() {
  21236. if (this.canvas && !this.canvas._hasITextHandlers) {
  21237. this.canvas._hasITextHandlers = true;
  21238. this._initCanvasHandlers();
  21239. }
  21240. });
  21241. },
  21242.  
  21243. /**
  21244. * @private
  21245. */
  21246. _initCanvasHandlers: function() {
  21247. this.canvas.on('selection:cleared', function() {
  21248. fabric.IText.prototype.exitEditingOnOthers.call();
  21249. });
  21250.  
  21251. this.canvas.on('mouse:up', function() {
  21252. fabric.IText.instances.forEach(function(obj) {
  21253. obj.__isMousedown = false;
  21254. });
  21255. });
  21256.  
  21257. this.canvas.on('object:selected', function(options) {
  21258. fabric.IText.prototype.exitEditingOnOthers.call(options.target);
  21259. });
  21260. },
  21261.  
  21262. /**
  21263. * @private
  21264. */
  21265. _tick: function() {
  21266. if (this._abortCursorAnimation) {
  21267. return;
  21268. }
  21269.  
  21270. var _this = this;
  21271.  
  21272. this.animate('_currentCursorOpacity', 1, {
  21273.  
  21274. duration: this.cursorDuration,
  21275.  
  21276. onComplete: function() {
  21277. _this._onTickComplete();
  21278. },
  21279.  
  21280. onChange: function() {
  21281. _this.canvas && _this.canvas.renderAll();
  21282. },
  21283.  
  21284. abort: function() {
  21285. return _this._abortCursorAnimation;
  21286. }
  21287. });
  21288. },
  21289.  
  21290. /**
  21291. * @private
  21292. */
  21293. _onTickComplete: function() {
  21294. if (this._abortCursorAnimation) {
  21295. return;
  21296. }
  21297.  
  21298. var _this = this;
  21299. if (this._cursorTimeout1) {
  21300. clearTimeout(this._cursorTimeout1);
  21301. }
  21302. this._cursorTimeout1 = setTimeout(function() {
  21303. _this.animate('_currentCursorOpacity', 0, {
  21304. duration: this.cursorDuration / 2,
  21305. onComplete: function() {
  21306. _this._tick();
  21307. },
  21308. onChange: function() {
  21309. _this.canvas && _this.canvas.renderAll();
  21310. },
  21311. abort: function() {
  21312. return _this._abortCursorAnimation;
  21313. }
  21314. });
  21315. }, 100);
  21316. },
  21317.  
  21318. /**
  21319. * Initializes delayed cursor
  21320. */
  21321. initDelayedCursor: function(restart) {
  21322. var _this = this,
  21323. delay = restart ? 0 : this.cursorDelay;
  21324.  
  21325. if (restart) {
  21326. this._abortCursorAnimation = true;
  21327. clearTimeout(this._cursorTimeout1);
  21328. this._currentCursorOpacity = 1;
  21329. this.canvas && this.canvas.renderAll();
  21330. }
  21331. if (this._cursorTimeout2) {
  21332. clearTimeout(this._cursorTimeout2);
  21333. }
  21334. this._cursorTimeout2 = setTimeout(function() {
  21335. _this._abortCursorAnimation = false;
  21336. _this._tick();
  21337. }, delay);
  21338. },
  21339.  
  21340. /**
  21341. * Aborts cursor animation and clears all timeouts
  21342. */
  21343. abortCursorAnimation: function() {
  21344. this._abortCursorAnimation = true;
  21345.  
  21346. clearTimeout(this._cursorTimeout1);
  21347. clearTimeout(this._cursorTimeout2);
  21348.  
  21349. this._currentCursorOpacity = 0;
  21350. this.canvas && this.canvas.renderAll();
  21351.  
  21352. var _this = this;
  21353. setTimeout(function() {
  21354. _this._abortCursorAnimation = false;
  21355. }, 10);
  21356. },
  21357.  
  21358. /**
  21359. * Selects entire text
  21360. */
  21361. selectAll: function() {
  21362. this.selectionStart = 0;
  21363. this.selectionEnd = this.text.length;
  21364. this.fire('selection:changed');
  21365. this.canvas && this.canvas.fire('text:selection:changed', { target: this });
  21366. },
  21367.  
  21368. /**
  21369. * Returns selected text
  21370. * @return {String}
  21371. */
  21372. getSelectedText: function() {
  21373. return this.text.slice(this.selectionStart, this.selectionEnd);
  21374. },
  21375.  
  21376. /**
  21377. * Find new selection index representing start of current word according to current selection index
  21378. * @param {Number} startFrom Surrent selection index
  21379. * @return {Number} New selection index
  21380. */
  21381. findWordBoundaryLeft: function(startFrom) {
  21382. var offset = 0, index = startFrom - 1;
  21383.  
  21384. // remove space before cursor first
  21385. if (this._reSpace.test(this.text.charAt(index))) {
  21386. while (this._reSpace.test(this.text.charAt(index))) {
  21387. offset++;
  21388. index--;
  21389. }
  21390. }
  21391. while (/\S/.test(this.text.charAt(index)) && index > -1) {
  21392. offset++;
  21393. index--;
  21394. }
  21395.  
  21396. return startFrom - offset;
  21397. },
  21398.  
  21399. /**
  21400. * Find new selection index representing end of current word according to current selection index
  21401. * @param {Number} startFrom Current selection index
  21402. * @return {Number} New selection index
  21403. */
  21404. findWordBoundaryRight: function(startFrom) {
  21405. var offset = 0, index = startFrom;
  21406.  
  21407. // remove space after cursor first
  21408. if (this._reSpace.test(this.text.charAt(index))) {
  21409. while (this._reSpace.test(this.text.charAt(index))) {
  21410. offset++;
  21411. index++;
  21412. }
  21413. }
  21414. while (/\S/.test(this.text.charAt(index)) && index < this.text.length) {
  21415. offset++;
  21416. index++;
  21417. }
  21418.  
  21419. return startFrom + offset;
  21420. },
  21421.  
  21422. /**
  21423. * Find new selection index representing start of current line according to current selection index
  21424. * @param {Number} startFrom Current selection index
  21425. * @return {Number} New selection index
  21426. */
  21427. findLineBoundaryLeft: function(startFrom) {
  21428. var offset = 0, index = startFrom - 1;
  21429.  
  21430. while (!/\n/.test(this.text.charAt(index)) && index > -1) {
  21431. offset++;
  21432. index--;
  21433. }
  21434.  
  21435. return startFrom - offset;
  21436. },
  21437.  
  21438. /**
  21439. * Find new selection index representing end of current line according to current selection index
  21440. * @param {Number} startFrom Current selection index
  21441. * @return {Number} New selection index
  21442. */
  21443. findLineBoundaryRight: function(startFrom) {
  21444. var offset = 0, index = startFrom;
  21445.  
  21446. while (!/\n/.test(this.text.charAt(index)) && index < this.text.length) {
  21447. offset++;
  21448. index++;
  21449. }
  21450.  
  21451. return startFrom + offset;
  21452. },
  21453.  
  21454. /**
  21455. * Returns number of newlines in selected text
  21456. * @return {Number} Number of newlines in selected text
  21457. */
  21458. getNumNewLinesInSelectedText: function() {
  21459. var selectedText = this.getSelectedText(),
  21460. numNewLines = 0;
  21461.  
  21462. for (var i = 0, chars = selectedText.split(''), len = chars.length; i < len; i++) {
  21463. if (chars[i] === '\n') {
  21464. numNewLines++;
  21465. }
  21466. }
  21467. return numNewLines;
  21468. },
  21469.  
  21470. /**
  21471. * Finds index corresponding to beginning or end of a word
  21472. * @param {Number} selectionStart Index of a character
  21473. * @param {Number} direction: 1 or -1
  21474. * @return {Number} Index of the beginning or end of a word
  21475. */
  21476. searchWordBoundary: function(selectionStart, direction) {
  21477. var index = this._reSpace.test(this.text.charAt(selectionStart)) ? selectionStart - 1 : selectionStart,
  21478. _char = this.text.charAt(index),
  21479. reNonWord = /[ \n\.,;!\?\-]/;
  21480.  
  21481. while (!reNonWord.test(_char) && index > 0 && index < this.text.length) {
  21482. index += direction;
  21483. _char = this.text.charAt(index);
  21484. }
  21485. if (reNonWord.test(_char) && _char !== '\n') {
  21486. index += direction === 1 ? 0 : 1;
  21487. }
  21488. return index;
  21489. },
  21490.  
  21491. /**
  21492. * Selects a word based on the index
  21493. * @param {Number} selectionStart Index of a character
  21494. */
  21495. selectWord: function(selectionStart) {
  21496. var newSelectionStart = this.searchWordBoundary(selectionStart, -1), /* search backwards */
  21497. newSelectionEnd = this.searchWordBoundary(selectionStart, 1); /* search forward */
  21498.  
  21499. this.setSelectionStart(newSelectionStart);
  21500. this.setSelectionEnd(newSelectionEnd);
  21501. this.initDelayedCursor(true);
  21502. },
  21503.  
  21504. /**
  21505. * Selects a line based on the index
  21506. * @param {Number} selectionStart Index of a character
  21507. */
  21508. selectLine: function(selectionStart) {
  21509. var newSelectionStart = this.findLineBoundaryLeft(selectionStart),
  21510. newSelectionEnd = this.findLineBoundaryRight(selectionStart);
  21511.  
  21512. this.setSelectionStart(newSelectionStart);
  21513. this.setSelectionEnd(newSelectionEnd);
  21514. this.initDelayedCursor(true);
  21515. },
  21516.  
  21517. /**
  21518. * Enters editing state
  21519. * @return {fabric.IText} thisArg
  21520. * @chainable
  21521. */
  21522. enterEditing: function() {
  21523. if (this.isEditing || !this.editable) {
  21524. return;
  21525. }
  21526.  
  21527. this.exitEditingOnOthers();
  21528.  
  21529. this.isEditing = true;
  21530.  
  21531. this.initHiddenTextarea();
  21532. this._updateTextarea();
  21533. this._saveEditingProps();
  21534. this._setEditingProps();
  21535.  
  21536. this._tick();
  21537. this.canvas && this.canvas.renderAll();
  21538.  
  21539. this.fire('editing:entered');
  21540. this.canvas && this.canvas.fire('text:editing:entered', { target: this });
  21541.  
  21542. return this;
  21543. },
  21544.  
  21545. exitEditingOnOthers: function() {
  21546. fabric.IText.instances.forEach(function(obj) {
  21547. obj.selected = false;
  21548. if (obj.isEditing) {
  21549. obj.exitEditing();
  21550. }
  21551. }, this);
  21552. },
  21553.  
  21554. /**
  21555. * @private
  21556. */
  21557. _setEditingProps: function() {
  21558. this.hoverCursor = 'text';
  21559.  
  21560. if (this.canvas) {
  21561. this.canvas.defaultCursor = this.canvas.moveCursor = 'text';
  21562. }
  21563.  
  21564. this.borderColor = this.editingBorderColor;
  21565.  
  21566. this.hasControls = this.selectable = false;
  21567. this.lockMovementX = this.lockMovementY = true;
  21568. },
  21569.  
  21570. /**
  21571. * @private
  21572. */
  21573. _updateTextarea: function() {
  21574. if (!this.hiddenTextarea) {
  21575. return;
  21576. }
  21577.  
  21578. this.hiddenTextarea.value = this.text;
  21579. this.hiddenTextarea.selectionStart = this.selectionStart;
  21580. },
  21581.  
  21582. /**
  21583. * @private
  21584. */
  21585. _saveEditingProps: function() {
  21586. this._savedProps = {
  21587. hasControls: this.hasControls,
  21588. borderColor: this.borderColor,
  21589. lockMovementX: this.lockMovementX,
  21590. lockMovementY: this.lockMovementY,
  21591. hoverCursor: this.hoverCursor,
  21592. defaultCursor: this.canvas && this.canvas.defaultCursor,
  21593. moveCursor: this.canvas && this.canvas.moveCursor
  21594. };
  21595. },
  21596.  
  21597. /**
  21598. * @private
  21599. */
  21600. _restoreEditingProps: function() {
  21601. if (!this._savedProps) {
  21602. return;
  21603. }
  21604.  
  21605. this.hoverCursor = this._savedProps.overCursor;
  21606. this.hasControls = this._savedProps.hasControls;
  21607. this.borderColor = this._savedProps.borderColor;
  21608. this.lockMovementX = this._savedProps.lockMovementX;
  21609. this.lockMovementY = this._savedProps.lockMovementY;
  21610.  
  21611. if (this.canvas) {
  21612. this.canvas.defaultCursor = this._savedProps.defaultCursor;
  21613. this.canvas.moveCursor = this._savedProps.moveCursor;
  21614. }
  21615. },
  21616.  
  21617. /**
  21618. * Exits from editing state
  21619. * @return {fabric.IText} thisArg
  21620. * @chainable
  21621. */
  21622. exitEditing: function() {
  21623.  
  21624. this.selected = false;
  21625. this.isEditing = false;
  21626. this.selectable = true;
  21627.  
  21628. this.selectionEnd = this.selectionStart;
  21629. this.hiddenTextarea && this.canvas && this.hiddenTextarea.parentNode.removeChild(this.hiddenTextarea);
  21630. this.hiddenTextarea = null;
  21631.  
  21632. this.abortCursorAnimation();
  21633. this._restoreEditingProps();
  21634. this._currentCursorOpacity = 0;
  21635.  
  21636. this.fire('editing:exited');
  21637. this.canvas && this.canvas.fire('text:editing:exited', { target: this });
  21638.  
  21639. return this;
  21640. },
  21641.  
  21642. /**
  21643. * @private
  21644. */
  21645. _removeExtraneousStyles: function() {
  21646. var textLines = this.text.split(this._reNewline);
  21647. for (var prop in this.styles) {
  21648. if (!textLines[prop]) {
  21649. delete this.styles[prop];
  21650. }
  21651. }
  21652. },
  21653.  
  21654. /**
  21655. * @private
  21656. */
  21657. _removeCharsFromTo: function(start, end) {
  21658.  
  21659. var i = end;
  21660. while (i !== start) {
  21661.  
  21662. var prevIndex = this.get2DCursorLocation(i).charIndex;
  21663. i--;
  21664.  
  21665. var index = this.get2DCursorLocation(i).charIndex,
  21666. isNewline = index > prevIndex;
  21667.  
  21668. if (isNewline) {
  21669. this.removeStyleObject(isNewline, i + 1);
  21670. }
  21671. else {
  21672. this.removeStyleObject(this.get2DCursorLocation(i).charIndex === 0, i);
  21673. }
  21674.  
  21675. }
  21676.  
  21677. this.text = this.text.slice(0, start) +
  21678. this.text.slice(end);
  21679. },
  21680.  
  21681. /**
  21682. * Inserts a character where cursor is (replacing selection if one exists)
  21683. * @param {String} _chars Characters to insert
  21684. */
  21685. insertChars: function(_chars) {
  21686. var isEndOfLine = this.text.slice(this.selectionStart, this.selectionStart + 1) === '\n';
  21687.  
  21688. this.text = this.text.slice(0, this.selectionStart) +
  21689. _chars +
  21690. this.text.slice(this.selectionEnd);
  21691.  
  21692. if (this.selectionStart === this.selectionEnd) {
  21693. this.insertStyleObjects(_chars, isEndOfLine, this.copiedStyles);
  21694. }
  21695. // else if (this.selectionEnd - this.selectionStart > 1) {
  21696. // TODO: replace styles properly
  21697. // console.log('replacing MORE than 1 char');
  21698. // }
  21699.  
  21700. this.selectionStart += _chars.length;
  21701. this.selectionEnd = this.selectionStart;
  21702.  
  21703. if (this.canvas) {
  21704. // TODO: double renderAll gets rid of text box shift happenning sometimes
  21705. // need to find out what exactly causes it and fix it
  21706. this.canvas.renderAll().renderAll();
  21707. }
  21708.  
  21709. this.setCoords();
  21710. this.fire('changed');
  21711. this.canvas && this.canvas.fire('text:changed', { target: this });
  21712. },
  21713.  
  21714. /**
  21715. * Inserts new style object
  21716. * @param {Number} lineIndex Index of a line
  21717. * @param {Number} charIndex Index of a char
  21718. * @param {Boolean} isEndOfLine True if it's end of line
  21719. */
  21720. insertNewlineStyleObject: function(lineIndex, charIndex, isEndOfLine) {
  21721.  
  21722. this.shiftLineStyles(lineIndex, +1);
  21723.  
  21724. if (!this.styles[lineIndex + 1]) {
  21725. this.styles[lineIndex + 1] = { };
  21726. }
  21727.  
  21728. var currentCharStyle = this.styles[lineIndex][charIndex - 1],
  21729. newLineStyles = { };
  21730.  
  21731. // if there's nothing after cursor,
  21732. // we clone current char style onto the next (otherwise empty) line
  21733. if (isEndOfLine) {
  21734. newLineStyles[0] = clone(currentCharStyle);
  21735. this.styles[lineIndex + 1] = newLineStyles;
  21736. }
  21737. // otherwise we clone styles of all chars
  21738. // after cursor onto the next line, from the beginning
  21739. else {
  21740. for (var index in this.styles[lineIndex]) {
  21741. if (parseInt(index, 10) >= charIndex) {
  21742. newLineStyles[parseInt(index, 10) - charIndex] = this.styles[lineIndex][index];
  21743. // remove lines from the previous line since they're on a new line now
  21744. delete this.styles[lineIndex][index];
  21745. }
  21746. }
  21747. this.styles[lineIndex + 1] = newLineStyles;
  21748. }
  21749. },
  21750.  
  21751. /**
  21752. * Inserts style object for a given line/char index
  21753. * @param {Number} lineIndex Index of a line
  21754. * @param {Number} charIndex Index of a char
  21755. * @param {Object} [style] Style object to insert, if given
  21756. */
  21757. insertCharStyleObject: function(lineIndex, charIndex, style) {
  21758.  
  21759. var currentLineStyles = this.styles[lineIndex],
  21760. currentLineStylesCloned = clone(currentLineStyles);
  21761.  
  21762. if (charIndex === 0 && !style) {
  21763. charIndex = 1;
  21764. }
  21765.  
  21766. // shift all char styles by 1 forward
  21767. // 0,1,2,3 -> (charIndex=2) -> 0,1,3,4 -> (insert 2) -> 0,1,2,3,4
  21768. for (var index in currentLineStylesCloned) {
  21769. var numericIndex = parseInt(index, 10);
  21770. if (numericIndex >= charIndex) {
  21771. currentLineStyles[numericIndex + 1] = currentLineStylesCloned[numericIndex];
  21772. //delete currentLineStyles[index];
  21773. }
  21774. }
  21775.  
  21776. this.styles[lineIndex][charIndex] =
  21777. style || clone(currentLineStyles[charIndex - 1]);
  21778. },
  21779.  
  21780. /**
  21781. * Inserts style object(s)
  21782. * @param {String} _chars Characters at the location where style is inserted
  21783. * @param {Boolean} isEndOfLine True if it's end of line
  21784. * @param {Array} [styles] Styles to insert
  21785. */
  21786. insertStyleObjects: function(_chars, isEndOfLine, styles) {
  21787.  
  21788. // short-circuit
  21789. if (this.isEmptyStyles()) {
  21790. return;
  21791. }
  21792.  
  21793. var cursorLocation = this.get2DCursorLocation(),
  21794. lineIndex = cursorLocation.lineIndex,
  21795. charIndex = cursorLocation.charIndex;
  21796.  
  21797. if (!this.styles[lineIndex]) {
  21798. this.styles[lineIndex] = { };
  21799. }
  21800.  
  21801. if (_chars === '\n') {
  21802. this.insertNewlineStyleObject(lineIndex, charIndex, isEndOfLine);
  21803. }
  21804. else {
  21805. if (styles) {
  21806. this._insertStyles(styles);
  21807. }
  21808. else {
  21809. // TODO: support multiple style insertion if _chars.length > 1
  21810. this.insertCharStyleObject(lineIndex, charIndex);
  21811. }
  21812. }
  21813. },
  21814.  
  21815. /**
  21816. * @private
  21817. */
  21818. _insertStyles: function(styles) {
  21819. for (var i = 0, len = styles.length; i < len; i++) {
  21820.  
  21821. var cursorLocation = this.get2DCursorLocation(this.selectionStart + i),
  21822. lineIndex = cursorLocation.lineIndex,
  21823. charIndex = cursorLocation.charIndex;
  21824.  
  21825. this.insertCharStyleObject(lineIndex, charIndex, styles[i]);
  21826. }
  21827. },
  21828.  
  21829. /**
  21830. * Shifts line styles up or down
  21831. * @param {Number} lineIndex Index of a line
  21832. * @param {Number} offset Can be -1 or +1
  21833. */
  21834. shiftLineStyles: function(lineIndex, offset) {
  21835. // shift all line styles by 1 upward
  21836. var clonedStyles = clone(this.styles);
  21837. for (var line in this.styles) {
  21838. var numericLine = parseInt(line, 10);
  21839. if (numericLine > lineIndex) {
  21840. this.styles[numericLine + offset] = clonedStyles[numericLine];
  21841. }
  21842. }
  21843. },
  21844.  
  21845. /**
  21846. * Removes style object
  21847. * @param {Boolean} isBeginningOfLine True if cursor is at the beginning of line
  21848. * @param {Number} [index] Optional index. When not given, current selectionStart is used.
  21849. */
  21850. removeStyleObject: function(isBeginningOfLine, index) {
  21851.  
  21852. var cursorLocation = this.get2DCursorLocation(index),
  21853. lineIndex = cursorLocation.lineIndex,
  21854. charIndex = cursorLocation.charIndex;
  21855.  
  21856. if (isBeginningOfLine) {
  21857.  
  21858. var textLines = this.text.split(this._reNewline),
  21859. textOnPreviousLine = textLines[lineIndex - 1],
  21860. newCharIndexOnPrevLine = textOnPreviousLine
  21861. ? textOnPreviousLine.length
  21862. : 0;
  21863.  
  21864. if (!this.styles[lineIndex - 1]) {
  21865. this.styles[lineIndex - 1] = { };
  21866. }
  21867.  
  21868. for (charIndex in this.styles[lineIndex]) {
  21869. this.styles[lineIndex - 1][parseInt(charIndex, 10) + newCharIndexOnPrevLine]
  21870. = this.styles[lineIndex][charIndex];
  21871. }
  21872.  
  21873. this.shiftLineStyles(lineIndex, -1);
  21874. }
  21875. else {
  21876. var currentLineStyles = this.styles[lineIndex];
  21877.  
  21878. if (currentLineStyles) {
  21879. var offset = this.selectionStart === this.selectionEnd ? -1 : 0;
  21880. delete currentLineStyles[charIndex + offset];
  21881. // console.log('deleting', lineIndex, charIndex + offset);
  21882. }
  21883.  
  21884. var currentLineStylesCloned = clone(currentLineStyles);
  21885.  
  21886. // shift all styles by 1 backwards
  21887. for (var i in currentLineStylesCloned) {
  21888. var numericIndex = parseInt(i, 10);
  21889. if (numericIndex >= charIndex && numericIndex !== 0) {
  21890. currentLineStyles[numericIndex - 1] = currentLineStylesCloned[numericIndex];
  21891. delete currentLineStyles[numericIndex];
  21892. }
  21893. }
  21894. }
  21895. },
  21896.  
  21897. /**
  21898. * Inserts new line
  21899. */
  21900. insertNewline: function() {
  21901. this.insertChars('\n');
  21902. }
  21903. });
  21904. })();
  21905.  
  21906.  
  21907. fabric.util.object.extend(fabric.IText.prototype, /** @lends fabric.IText.prototype */ {
  21908. /**
  21909. * Initializes "dbclick" event handler
  21910. */
  21911. initDoubleClickSimulation: function() {
  21912.  
  21913. // for double click
  21914. this.__lastClickTime = +new Date();
  21915.  
  21916. // for triple click
  21917. this.__lastLastClickTime = +new Date();
  21918.  
  21919. this.__lastPointer = { };
  21920.  
  21921. this.on('mousedown', this.onMouseDown.bind(this));
  21922. },
  21923.  
  21924. onMouseDown: function(options) {
  21925.  
  21926. this.__newClickTime = +new Date();
  21927. var newPointer = this.canvas.getPointer(options.e);
  21928.  
  21929. if (this.isTripleClick(newPointer)) {
  21930. this.fire('tripleclick', options);
  21931. this._stopEvent(options.e);
  21932. }
  21933. else if (this.isDoubleClick(newPointer)) {
  21934. this.fire('dblclick', options);
  21935. this._stopEvent(options.e);
  21936. }
  21937.  
  21938. this.__lastLastClickTime = this.__lastClickTime;
  21939. this.__lastClickTime = this.__newClickTime;
  21940. this.__lastPointer = newPointer;
  21941. this.__lastIsEditing = this.isEditing;
  21942. this.__lastSelected = this.selected;
  21943. },
  21944.  
  21945. isDoubleClick: function(newPointer) {
  21946. return this.__newClickTime - this.__lastClickTime < 500 &&
  21947. this.__lastPointer.x === newPointer.x &&
  21948. this.__lastPointer.y === newPointer.y && this.__lastIsEditing;
  21949. },
  21950.  
  21951. isTripleClick: function(newPointer) {
  21952. return this.__newClickTime - this.__lastClickTime < 500 &&
  21953. this.__lastClickTime - this.__lastLastClickTime < 500 &&
  21954. this.__lastPointer.x === newPointer.x &&
  21955. this.__lastPointer.y === newPointer.y;
  21956. },
  21957.  
  21958. /**
  21959. * @private
  21960. */
  21961. _stopEvent: function(e) {
  21962. e.preventDefault && e.preventDefault();
  21963. e.stopPropagation && e.stopPropagation();
  21964. },
  21965.  
  21966. /**
  21967. * Initializes event handlers related to cursor or selection
  21968. */
  21969. initCursorSelectionHandlers: function() {
  21970. this.initSelectedHandler();
  21971. this.initMousedownHandler();
  21972. this.initMousemoveHandler();
  21973. this.initMouseupHandler();
  21974. this.initClicks();
  21975. },
  21976.  
  21977. /**
  21978. * Initializes double and triple click event handlers
  21979. */
  21980. initClicks: function() {
  21981. this.on('dblclick', function(options) {
  21982. this.selectWord(this.getSelectionStartFromPointer(options.e));
  21983. });
  21984. this.on('tripleclick', function(options) {
  21985. this.selectLine(this.getSelectionStartFromPointer(options.e));
  21986. });
  21987. },
  21988.  
  21989. /**
  21990. * Initializes "mousedown" event handler
  21991. */
  21992. initMousedownHandler: function() {
  21993. this.on('mousedown', function(options) {
  21994.  
  21995. var pointer = this.canvas.getPointer(options.e);
  21996.  
  21997. this.__mousedownX = pointer.x;
  21998. this.__mousedownY = pointer.y;
  21999. this.__isMousedown = true;
  22000.  
  22001. if (this.hiddenTextarea && this.canvas) {
  22002. this.canvas.wrapperEl.appendChild(this.hiddenTextarea);
  22003. }
  22004.  
  22005. if (this.selected) {
  22006. this.setCursorByClick(options.e);
  22007. }
  22008.  
  22009. if (this.isEditing) {
  22010. this.__selectionStartOnMouseDown = this.selectionStart;
  22011. this.initDelayedCursor(true);
  22012. }
  22013. });
  22014. },
  22015.  
  22016. /**
  22017. * Initializes "mousemove" event handler
  22018. */
  22019. initMousemoveHandler: function() {
  22020. this.on('mousemove', function(options) {
  22021. if (!this.__isMousedown || !this.isEditing) {
  22022. return;
  22023. }
  22024.  
  22025. var newSelectionStart = this.getSelectionStartFromPointer(options.e);
  22026.  
  22027. if (newSelectionStart >= this.__selectionStartOnMouseDown) {
  22028. this.setSelectionStart(this.__selectionStartOnMouseDown);
  22029. this.setSelectionEnd(newSelectionStart);
  22030. }
  22031. else {
  22032. this.setSelectionStart(newSelectionStart);
  22033. this.setSelectionEnd(this.__selectionStartOnMouseDown);
  22034. }
  22035. });
  22036. },
  22037.  
  22038. /**
  22039. * @private
  22040. */
  22041. _isObjectMoved: function(e) {
  22042. var pointer = this.canvas.getPointer(e);
  22043.  
  22044. return this.__mousedownX !== pointer.x ||
  22045. this.__mousedownY !== pointer.y;
  22046. },
  22047.  
  22048. /**
  22049. * Initializes "mouseup" event handler
  22050. */
  22051. initMouseupHandler: function() {
  22052. this.on('mouseup', function(options) {
  22053. this.__isMousedown = false;
  22054. if (this._isObjectMoved(options.e)) {
  22055. return;
  22056. }
  22057.  
  22058. if (this.__lastSelected) {
  22059. this.enterEditing();
  22060. this.initDelayedCursor(true);
  22061. }
  22062. this.selected = true;
  22063. });
  22064. },
  22065.  
  22066. /**
  22067. * Changes cursor location in a text depending on passed pointer (x/y) object
  22068. * @param {Event} e Event object
  22069. */
  22070. setCursorByClick: function(e) {
  22071. var newSelectionStart = this.getSelectionStartFromPointer(e);
  22072.  
  22073. if (e.shiftKey) {
  22074. if (newSelectionStart < this.selectionStart) {
  22075. this.setSelectionEnd(this.selectionStart);
  22076. this.setSelectionStart(newSelectionStart);
  22077. }
  22078. else {
  22079. this.setSelectionEnd(newSelectionStart);
  22080. }
  22081. }
  22082. else {
  22083. this.setSelectionStart(newSelectionStart);
  22084. this.setSelectionEnd(newSelectionStart);
  22085. }
  22086. },
  22087.  
  22088. /**
  22089. * @private
  22090. * @param {Event} e Event object
  22091. * @return {Object} Coordinates of a pointer (x, y)
  22092. */
  22093. _getLocalRotatedPointer: function(e) {
  22094. var pointer = this.canvas.getPointer(e),
  22095.  
  22096. pClicked = new fabric.Point(pointer.x, pointer.y),
  22097. pLeftTop = new fabric.Point(this.left, this.top),
  22098.  
  22099. rotated = fabric.util.rotatePoint(
  22100. pClicked, pLeftTop, fabric.util.degreesToRadians(-this.angle));
  22101.  
  22102. return this.getLocalPointer(e, rotated);
  22103. },
  22104.  
  22105. /**
  22106. * Returns index of a character corresponding to where an object was clicked
  22107. * @param {Event} e Event object
  22108. * @return {Number} Index of a character
  22109. */
  22110. getSelectionStartFromPointer: function(e) {
  22111. var mouseOffset = this._getLocalRotatedPointer(e),
  22112. textLines = this.text.split(this._reNewline),
  22113. prevWidth = 0,
  22114. width = 0,
  22115. height = 0,
  22116. charIndex = 0,
  22117. newSelectionStart;
  22118.  
  22119. for (var i = 0, len = textLines.length; i < len; i++) {
  22120.  
  22121. height += this._getHeightOfLine(this.ctx, i) * this.scaleY;
  22122.  
  22123. var widthOfLine = this._getWidthOfLine(this.ctx, i, textLines),
  22124. lineLeftOffset = this._getLineLeftOffset(widthOfLine);
  22125.  
  22126. width = lineLeftOffset * this.scaleX;
  22127.  
  22128. if (this.flipX) {
  22129. // when oject is horizontally flipped we reverse chars
  22130. textLines[i] = textLines[i].split('').reverse().join('');
  22131. }
  22132.  
  22133. for (var j = 0, jlen = textLines[i].length; j < jlen; j++) {
  22134.  
  22135. var _char = textLines[i][j];
  22136. prevWidth = width;
  22137.  
  22138. width += this._getWidthOfChar(this.ctx, _char, i, this.flipX ? jlen - j : j) *
  22139. this.scaleX;
  22140.  
  22141. if (height <= mouseOffset.y || width <= mouseOffset.x) {
  22142. charIndex++;
  22143. continue;
  22144. }
  22145.  
  22146. return this._getNewSelectionStartFromOffset(
  22147. mouseOffset, prevWidth, width, charIndex + i, jlen);
  22148. }
  22149.  
  22150. if (mouseOffset.y < height) {
  22151. return this._getNewSelectionStartFromOffset(
  22152. mouseOffset, prevWidth, width, charIndex + i, jlen);
  22153. }
  22154. }
  22155.  
  22156. // clicked somewhere after all chars, so set at the end
  22157. if (typeof newSelectionStart === 'undefined') {
  22158. return this.text.length;
  22159. }
  22160. },
  22161.  
  22162. /**
  22163. * @private
  22164. */
  22165. _getNewSelectionStartFromOffset: function(mouseOffset, prevWidth, width, index, jlen) {
  22166.  
  22167. var distanceBtwLastCharAndCursor = mouseOffset.x - prevWidth,
  22168. distanceBtwNextCharAndCursor = width - mouseOffset.x,
  22169. offset = distanceBtwNextCharAndCursor > distanceBtwLastCharAndCursor ? 0 : 1,
  22170. newSelectionStart = index + offset;
  22171.  
  22172. // if object is horizontally flipped, mirror cursor location from the end
  22173. if (this.flipX) {
  22174. newSelectionStart = jlen - newSelectionStart;
  22175. }
  22176.  
  22177. if (newSelectionStart > this.text.length) {
  22178. newSelectionStart = this.text.length;
  22179. }
  22180.  
  22181. return newSelectionStart;
  22182. }
  22183. });
  22184.  
  22185.  
  22186. fabric.util.object.extend(fabric.IText.prototype, /** @lends fabric.IText.prototype */ {
  22187.  
  22188. /**
  22189. * Initializes hidden textarea (needed to bring up keyboard in iOS)
  22190. */
  22191. initHiddenTextarea: function() {
  22192. this.hiddenTextarea = fabric.document.createElement('textarea');
  22193.  
  22194. this.hiddenTextarea.setAttribute('autocapitalize', 'off');
  22195. this.hiddenTextarea.style.cssText = 'position: absolute; top: 0; left: -9999px';
  22196.  
  22197. fabric.document.body.appendChild(this.hiddenTextarea);
  22198.  
  22199. fabric.util.addListener(this.hiddenTextarea, 'keydown', this.onKeyDown.bind(this));
  22200. fabric.util.addListener(this.hiddenTextarea, 'keypress', this.onKeyPress.bind(this));
  22201. fabric.util.addListener(this.hiddenTextarea, 'copy', this.copy.bind(this));
  22202. fabric.util.addListener(this.hiddenTextarea, 'paste', this.paste.bind(this));
  22203.  
  22204. if (!this._clickHandlerInitialized && this.canvas) {
  22205. fabric.util.addListener(this.canvas.upperCanvasEl, 'click', this.onClick.bind(this));
  22206. this._clickHandlerInitialized = true;
  22207. }
  22208. },
  22209.  
  22210. /**
  22211. * @private
  22212. */
  22213. _keysMap: {
  22214. 8: 'removeChars',
  22215. 9: 'exitEditing',
  22216. 27: 'exitEditing',
  22217. 13: 'insertNewline',
  22218. 33: 'moveCursorUp',
  22219. 34: 'moveCursorDown',
  22220. 35: 'moveCursorRight',
  22221. 36: 'moveCursorLeft',
  22222. 37: 'moveCursorLeft',
  22223. 38: 'moveCursorUp',
  22224. 39: 'moveCursorRight',
  22225. 40: 'moveCursorDown',
  22226. 46: 'forwardDelete'
  22227. },
  22228.  
  22229. /**
  22230. * @private
  22231. */
  22232. _ctrlKeysMap: {
  22233. 65: 'selectAll',
  22234. 88: 'cut'
  22235. },
  22236.  
  22237. onClick: function() {
  22238. // No need to trigger click event here, focus is enough to have the keyboard appear on Android
  22239. this.hiddenTextarea && this.hiddenTextarea.focus();
  22240. },
  22241.  
  22242. /**
  22243. * Handles keyup event
  22244. * @param {Event} e Event object
  22245. */
  22246. onKeyDown: function(e) {
  22247. if (!this.isEditing) {
  22248. return;
  22249. }
  22250.  
  22251. if (e.keyCode in this._keysMap) {
  22252. this[this._keysMap[e.keyCode]](e);
  22253. }
  22254. else if ((e.keyCode in this._ctrlKeysMap) && (e.ctrlKey || e.metaKey)) {
  22255. this[this._ctrlKeysMap[e.keyCode]](e);
  22256. }
  22257. else {
  22258. return;
  22259. }
  22260.  
  22261. e.stopImmediatePropagation();
  22262. e.preventDefault();
  22263.  
  22264. this.canvas && this.canvas.renderAll();
  22265. },
  22266.  
  22267. /**
  22268. * Forward delete
  22269. */
  22270. forwardDelete: function(e) {
  22271. if (this.selectionStart === this.selectionEnd) {
  22272. this.moveCursorRight(e);
  22273. }
  22274. this.removeChars(e);
  22275. },
  22276.  
  22277. /**
  22278. * Copies selected text
  22279. * @param {Event} e Event object
  22280. */
  22281. copy: function(e) {
  22282. var selectedText = this.getSelectedText(),
  22283. clipboardData = this._getClipboardData(e);
  22284.  
  22285. // Check for backward compatibility with old browsers
  22286. if (clipboardData) {
  22287. clipboardData.setData('text', selectedText);
  22288. }
  22289.  
  22290. this.copiedText = selectedText;
  22291. this.copiedStyles = this.getSelectionStyles(
  22292. this.selectionStart,
  22293. this.selectionEnd);
  22294. },
  22295.  
  22296. /**
  22297. * Pastes text
  22298. * @param {Event} e Event object
  22299. */
  22300. paste: function(e) {
  22301. var copiedText = null,
  22302. clipboardData = this._getClipboardData(e);
  22303.  
  22304. // Check for backward compatibility with old browsers
  22305. if (clipboardData) {
  22306. copiedText = clipboardData.getData('text');
  22307. }
  22308. else {
  22309. copiedText = this.copiedText;
  22310. }
  22311.  
  22312. if (copiedText) {
  22313. this.insertChars(copiedText);
  22314. }
  22315. },
  22316.  
  22317. /**
  22318. * Cuts text
  22319. * @param {Event} e Event object
  22320. */
  22321. cut: function(e) {
  22322. if (this.selectionStart === this.selectionEnd) {
  22323. return;
  22324. }
  22325.  
  22326. this.copy();
  22327. this.removeChars(e);
  22328. },
  22329.  
  22330. /**
  22331. * @private
  22332. * @param {Event} e Event object
  22333. * @return {Object} Clipboard data object
  22334. */
  22335. _getClipboardData: function(e) {
  22336. return e && (e.clipboardData || fabric.window.clipboardData);
  22337. },
  22338.  
  22339. /**
  22340. * Handles keypress event
  22341. * @param {Event} e Event object
  22342. */
  22343. onKeyPress: function(e) {
  22344. if (!this.isEditing || e.metaKey || e.ctrlKey) {
  22345. return;
  22346. }
  22347. if (e.which !== 0) {
  22348. this.insertChars(String.fromCharCode(e.which));
  22349. }
  22350. e.stopPropagation();
  22351. },
  22352.  
  22353. /**
  22354. * Gets start offset of a selection
  22355. * @param {Event} e Event object
  22356. * @param {Boolean} isRight
  22357. * @return {Number}
  22358. */
  22359. getDownCursorOffset: function(e, isRight) {
  22360. var selectionProp = isRight ? this.selectionEnd : this.selectionStart,
  22361. textLines = this.text.split(this._reNewline),
  22362. _char,
  22363. lineLeftOffset,
  22364.  
  22365. textBeforeCursor = this.text.slice(0, selectionProp),
  22366. textAfterCursor = this.text.slice(selectionProp),
  22367.  
  22368. textOnSameLineBeforeCursor = textBeforeCursor.slice(textBeforeCursor.lastIndexOf('\n') + 1),
  22369. textOnSameLineAfterCursor = textAfterCursor.match(/(.*)\n?/)[1],
  22370. textOnNextLine = (textAfterCursor.match(/.*\n(.*)\n?/) || { })[1] || '',
  22371.  
  22372. cursorLocation = this.get2DCursorLocation(selectionProp);
  22373.  
  22374. // if on last line, down cursor goes to end of line
  22375. if (cursorLocation.lineIndex === textLines.length - 1 || e.metaKey || e.keyCode === 34) {
  22376.  
  22377. // move to the end of a text
  22378. return this.text.length - selectionProp;
  22379. }
  22380.  
  22381. var widthOfSameLineBeforeCursor = this._getWidthOfLine(this.ctx, cursorLocation.lineIndex, textLines);
  22382. lineLeftOffset = this._getLineLeftOffset(widthOfSameLineBeforeCursor);
  22383.  
  22384. var widthOfCharsOnSameLineBeforeCursor = lineLeftOffset,
  22385. lineIndex = cursorLocation.lineIndex;
  22386.  
  22387. for (var i = 0, len = textOnSameLineBeforeCursor.length; i < len; i++) {
  22388. _char = textOnSameLineBeforeCursor[i];
  22389. widthOfCharsOnSameLineBeforeCursor += this._getWidthOfChar(this.ctx, _char, lineIndex, i);
  22390. }
  22391.  
  22392. var indexOnNextLine = this._getIndexOnNextLine(
  22393. cursorLocation, textOnNextLine, widthOfCharsOnSameLineBeforeCursor, textLines);
  22394.  
  22395. return textOnSameLineAfterCursor.length + 1 + indexOnNextLine;
  22396. },
  22397.  
  22398. /**
  22399. * @private
  22400. */
  22401. _getIndexOnNextLine: function(cursorLocation, textOnNextLine, widthOfCharsOnSameLineBeforeCursor, textLines) {
  22402. var lineIndex = cursorLocation.lineIndex + 1,
  22403. widthOfNextLine = this._getWidthOfLine(this.ctx, lineIndex, textLines),
  22404. lineLeftOffset = this._getLineLeftOffset(widthOfNextLine),
  22405. widthOfCharsOnNextLine = lineLeftOffset,
  22406. indexOnNextLine = 0,
  22407. foundMatch;
  22408.  
  22409. for (var j = 0, jlen = textOnNextLine.length; j < jlen; j++) {
  22410.  
  22411. var _char = textOnNextLine[j],
  22412. widthOfChar = this._getWidthOfChar(this.ctx, _char, lineIndex, j);
  22413.  
  22414. widthOfCharsOnNextLine += widthOfChar;
  22415.  
  22416. if (widthOfCharsOnNextLine > widthOfCharsOnSameLineBeforeCursor) {
  22417.  
  22418. foundMatch = true;
  22419.  
  22420. var leftEdge = widthOfCharsOnNextLine - widthOfChar,
  22421. rightEdge = widthOfCharsOnNextLine,
  22422. offsetFromLeftEdge = Math.abs(leftEdge - widthOfCharsOnSameLineBeforeCursor),
  22423. offsetFromRightEdge = Math.abs(rightEdge - widthOfCharsOnSameLineBeforeCursor);
  22424.  
  22425. indexOnNextLine = offsetFromRightEdge < offsetFromLeftEdge ? j + 1 : j;
  22426.  
  22427. break;
  22428. }
  22429. }
  22430.  
  22431. // reached end
  22432. if (!foundMatch) {
  22433. indexOnNextLine = textOnNextLine.length;
  22434. }
  22435.  
  22436. return indexOnNextLine;
  22437. },
  22438.  
  22439. /**
  22440. * Moves cursor down
  22441. * @param {Event} e Event object
  22442. */
  22443. moveCursorDown: function(e) {
  22444. this.abortCursorAnimation();
  22445. this._currentCursorOpacity = 1;
  22446.  
  22447. var offset = this.getDownCursorOffset(e, this._selectionDirection === 'right');
  22448.  
  22449. if (e.shiftKey) {
  22450. this.moveCursorDownWithShift(offset);
  22451. }
  22452. else {
  22453. this.moveCursorDownWithoutShift(offset);
  22454. }
  22455.  
  22456. this.initDelayedCursor();
  22457. },
  22458.  
  22459. /**
  22460. * Moves cursor down without keeping selection
  22461. * @param {Number} offset
  22462. */
  22463. moveCursorDownWithoutShift: function(offset) {
  22464. this._selectionDirection = 'right';
  22465. this.selectionStart += offset;
  22466.  
  22467. if (this.selectionStart > this.text.length) {
  22468. this.selectionStart = this.text.length;
  22469. }
  22470. this.selectionEnd = this.selectionStart;
  22471. },
  22472.  
  22473. /**
  22474. * private
  22475. */
  22476. swapSelectionPoints: function() {
  22477. var swapSel = this.selectionEnd;
  22478. this.selectionEnd = this.selectionStart;
  22479. this.selectionStart = swapSel;
  22480. },
  22481.  
  22482. /**
  22483. * Moves cursor down while keeping selection
  22484. * @param {Number} offset
  22485. */
  22486. moveCursorDownWithShift: function(offset) {
  22487. if (this.selectionEnd === this.selectionStart) {
  22488. this._selectionDirection = 'right';
  22489. }
  22490. var prop = this._selectionDirection === 'right' ? 'selectionEnd' : 'selectionStart';
  22491. this[prop] += offset;
  22492. if (this.selectionEnd < this.selectionStart && this._selectionDirection === 'left') {
  22493. this.swapSelectionPoints();
  22494. this._selectionDirection = 'right';
  22495. }
  22496. if (this.selectionEnd > this.text.length) {
  22497. this.selectionEnd = this.text.length;
  22498. }
  22499. },
  22500.  
  22501. /**
  22502. * @param {Event} e Event object
  22503. * @param {Boolean} isRight
  22504. * @return {Number}
  22505. */
  22506. getUpCursorOffset: function(e, isRight) {
  22507. var selectionProp = isRight ? this.selectionEnd : this.selectionStart,
  22508. cursorLocation = this.get2DCursorLocation(selectionProp);
  22509. // if on first line, up cursor goes to start of line
  22510. if (cursorLocation.lineIndex === 0 || e.metaKey || e.keyCode === 33) {
  22511. return selectionProp;
  22512. }
  22513.  
  22514. var textBeforeCursor = this.text.slice(0, selectionProp),
  22515. textOnSameLineBeforeCursor = textBeforeCursor.slice(textBeforeCursor.lastIndexOf('\n') + 1),
  22516. textOnPreviousLine = (textBeforeCursor.match(/\n?(.*)\n.*$/) || {})[1] || '',
  22517. textLines = this.text.split(this._reNewline),
  22518. _char,
  22519. widthOfSameLineBeforeCursor = this._getWidthOfLine(this.ctx, cursorLocation.lineIndex, textLines),
  22520. lineLeftOffset = this._getLineLeftOffset(widthOfSameLineBeforeCursor),
  22521. widthOfCharsOnSameLineBeforeCursor = lineLeftOffset,
  22522. lineIndex = cursorLocation.lineIndex;
  22523.  
  22524. for (var i = 0, len = textOnSameLineBeforeCursor.length; i < len; i++) {
  22525. _char = textOnSameLineBeforeCursor[i];
  22526. widthOfCharsOnSameLineBeforeCursor += this._getWidthOfChar(this.ctx, _char, lineIndex, i);
  22527. }
  22528.  
  22529. var indexOnPrevLine = this._getIndexOnPrevLine(
  22530. cursorLocation, textOnPreviousLine, widthOfCharsOnSameLineBeforeCursor, textLines);
  22531.  
  22532. return textOnPreviousLine.length - indexOnPrevLine + textOnSameLineBeforeCursor.length;
  22533. },
  22534.  
  22535. /**
  22536. * @private
  22537. */
  22538. _getIndexOnPrevLine: function(cursorLocation, textOnPreviousLine, widthOfCharsOnSameLineBeforeCursor, textLines) {
  22539.  
  22540. var lineIndex = cursorLocation.lineIndex - 1,
  22541. widthOfPreviousLine = this._getWidthOfLine(this.ctx, lineIndex, textLines),
  22542. lineLeftOffset = this._getLineLeftOffset(widthOfPreviousLine),
  22543. widthOfCharsOnPreviousLine = lineLeftOffset,
  22544. indexOnPrevLine = 0,
  22545. foundMatch;
  22546.  
  22547. for (var j = 0, jlen = textOnPreviousLine.length; j < jlen; j++) {
  22548.  
  22549. var _char = textOnPreviousLine[j],
  22550. widthOfChar = this._getWidthOfChar(this.ctx, _char, lineIndex, j);
  22551.  
  22552. widthOfCharsOnPreviousLine += widthOfChar;
  22553.  
  22554. if (widthOfCharsOnPreviousLine > widthOfCharsOnSameLineBeforeCursor) {
  22555.  
  22556. foundMatch = true;
  22557.  
  22558. var leftEdge = widthOfCharsOnPreviousLine - widthOfChar,
  22559. rightEdge = widthOfCharsOnPreviousLine,
  22560. offsetFromLeftEdge = Math.abs(leftEdge - widthOfCharsOnSameLineBeforeCursor),
  22561. offsetFromRightEdge = Math.abs(rightEdge - widthOfCharsOnSameLineBeforeCursor);
  22562.  
  22563. indexOnPrevLine = offsetFromRightEdge < offsetFromLeftEdge ? j : (j - 1);
  22564.  
  22565. break;
  22566. }
  22567. }
  22568.  
  22569. // reached end
  22570. if (!foundMatch) {
  22571. indexOnPrevLine = textOnPreviousLine.length - 1;
  22572. }
  22573.  
  22574. return indexOnPrevLine;
  22575. },
  22576.  
  22577. /**
  22578. * Moves cursor up
  22579. * @param {Event} e Event object
  22580. */
  22581. moveCursorUp: function(e) {
  22582.  
  22583. this.abortCursorAnimation();
  22584. this._currentCursorOpacity = 1;
  22585.  
  22586. var offset = this.getUpCursorOffset(e, this._selectionDirection === 'right');
  22587. if (e.shiftKey) {
  22588. this.moveCursorUpWithShift(offset);
  22589. }
  22590. else {
  22591. this.moveCursorUpWithoutShift(offset);
  22592. }
  22593.  
  22594. this.initDelayedCursor();
  22595. },
  22596.  
  22597. /**
  22598. * Moves cursor up with shift
  22599. * @param {Number} offset
  22600. */
  22601. moveCursorUpWithShift: function(offset) {
  22602. if (this.selectionEnd === this.selectionStart) {
  22603. this._selectionDirection = 'left';
  22604. }
  22605. var prop = this._selectionDirection === 'right' ? 'selectionEnd' : 'selectionStart';
  22606. this[prop] -= offset;
  22607. if (this.selectionEnd < this.selectionStart && this._selectionDirection === 'right') {
  22608. this.swapSelectionPoints();
  22609. this._selectionDirection = 'left';
  22610. }
  22611. if (this.selectionStart < 0) {
  22612. this.selectionStart = 0;
  22613. }
  22614. },
  22615.  
  22616. /**
  22617. * Moves cursor up without shift
  22618. * @param {Number} offset
  22619. */
  22620. moveCursorUpWithoutShift: function(offset) {
  22621. if (this.selectionStart === this.selectionEnd) {
  22622. this.selectionStart -= offset;
  22623. }
  22624. if (this.selectionStart < 0) {
  22625. this.selectionStart = 0;
  22626. }
  22627. this.selectionEnd = this.selectionStart;
  22628.  
  22629. this._selectionDirection = 'left';
  22630. },
  22631.  
  22632. /**
  22633. * Moves cursor left
  22634. * @param {Event} e Event object
  22635. */
  22636. moveCursorLeft: function(e) {
  22637. if (this.selectionStart === 0 && this.selectionEnd === 0) {
  22638. return;
  22639. }
  22640.  
  22641. this.abortCursorAnimation();
  22642. this._currentCursorOpacity = 1;
  22643.  
  22644. if (e.shiftKey) {
  22645. this.moveCursorLeftWithShift(e);
  22646. }
  22647. else {
  22648. this.moveCursorLeftWithoutShift(e);
  22649. }
  22650.  
  22651. this.initDelayedCursor();
  22652. },
  22653.  
  22654. /**
  22655. * @private
  22656. */
  22657. _move: function(e, prop, direction) {
  22658. if (e.altKey) {
  22659. this[prop] = this['findWordBoundary' + direction](this[prop]);
  22660. }
  22661. else if (e.metaKey || e.keyCode === 35 || e.keyCode === 36 ) {
  22662. this[prop] = this['findLineBoundary' + direction](this[prop]);
  22663. }
  22664. else {
  22665. this[prop] += (direction === 'Left' ? -1 : 1);
  22666. }
  22667. },
  22668.  
  22669. /**
  22670. * @private
  22671. */
  22672. _moveLeft: function(e, prop) {
  22673. this._move(e, prop, 'Left');
  22674. },
  22675.  
  22676. /**
  22677. * @private
  22678. */
  22679. _moveRight: function(e, prop) {
  22680. this._move(e, prop, 'Right');
  22681. },
  22682.  
  22683. /**
  22684. * Moves cursor left without keeping selection
  22685. * @param {Event} e
  22686. */
  22687. moveCursorLeftWithoutShift: function(e) {
  22688. this._selectionDirection = 'left';
  22689.  
  22690. // only move cursor when there is no selection,
  22691. // otherwise we discard it, and leave cursor on same place
  22692. if (this.selectionEnd === this.selectionStart) {
  22693. this._moveLeft(e, 'selectionStart');
  22694. }
  22695. this.selectionEnd = this.selectionStart;
  22696. },
  22697.  
  22698. /**
  22699. * Moves cursor left while keeping selection
  22700. * @param {Event} e
  22701. */
  22702. moveCursorLeftWithShift: function(e) {
  22703. if (this._selectionDirection === 'right' && this.selectionStart !== this.selectionEnd) {
  22704. this._moveLeft(e, 'selectionEnd');
  22705. }
  22706. else {
  22707. this._selectionDirection = 'left';
  22708. this._moveLeft(e, 'selectionStart');
  22709.  
  22710. // increase selection by one if it's a newline
  22711. if (this.text.charAt(this.selectionStart) === '\n') {
  22712. this.selectionStart--;
  22713. }
  22714. if (this.selectionStart < 0) {
  22715. this.selectionStart = 0;
  22716. }
  22717. }
  22718. },
  22719.  
  22720. /**
  22721. * Moves cursor right
  22722. * @param {Event} e Event object
  22723. */
  22724. moveCursorRight: function(e) {
  22725. if (this.selectionStart >= this.text.length && this.selectionEnd >= this.text.length) {
  22726. return;
  22727. }
  22728.  
  22729. this.abortCursorAnimation();
  22730. this._currentCursorOpacity = 1;
  22731.  
  22732. if (e.shiftKey) {
  22733. this.moveCursorRightWithShift(e);
  22734. }
  22735. else {
  22736. this.moveCursorRightWithoutShift(e);
  22737. }
  22738.  
  22739. this.initDelayedCursor();
  22740. },
  22741.  
  22742. /**
  22743. * Moves cursor right while keeping selection
  22744. * @param {Event} e
  22745. */
  22746. moveCursorRightWithShift: function(e) {
  22747. if (this._selectionDirection === 'left' && this.selectionStart !== this.selectionEnd) {
  22748. this._moveRight(e, 'selectionStart');
  22749. }
  22750. else {
  22751. this._selectionDirection = 'right';
  22752. this._moveRight(e, 'selectionEnd');
  22753.  
  22754. // increase selection by one if it's a newline
  22755. if (this.text.charAt(this.selectionEnd - 1) === '\n') {
  22756. this.selectionEnd++;
  22757. }
  22758. if (this.selectionEnd > this.text.length) {
  22759. this.selectionEnd = this.text.length;
  22760. }
  22761. }
  22762. },
  22763.  
  22764. /**
  22765. * Moves cursor right without keeping selection
  22766. * @param {Event} e Event object
  22767. */
  22768. moveCursorRightWithoutShift: function(e) {
  22769. this._selectionDirection = 'right';
  22770.  
  22771. if (this.selectionStart === this.selectionEnd) {
  22772. this._moveRight(e, 'selectionStart');
  22773. this.selectionEnd = this.selectionStart;
  22774. }
  22775. else {
  22776. this.selectionEnd += this.getNumNewLinesInSelectedText();
  22777. if (this.selectionEnd > this.text.length) {
  22778. this.selectionEnd = this.text.length;
  22779. }
  22780. this.selectionStart = this.selectionEnd;
  22781. }
  22782. },
  22783.  
  22784. /**
  22785. * Inserts a character where cursor is (replacing selection if one exists)
  22786. * @param {Event} e Event object
  22787. */
  22788. removeChars: function(e) {
  22789. if (this.selectionStart === this.selectionEnd) {
  22790. this._removeCharsNearCursor(e);
  22791. }
  22792. else {
  22793. this._removeCharsFromTo(this.selectionStart, this.selectionEnd);
  22794. }
  22795.  
  22796. this.selectionEnd = this.selectionStart;
  22797.  
  22798. this._removeExtraneousStyles();
  22799.  
  22800. if (this.canvas) {
  22801. // TODO: double renderAll gets rid of text box shift happenning sometimes
  22802. // need to find out what exactly causes it and fix it
  22803. this.canvas.renderAll().renderAll();
  22804. }
  22805.  
  22806. this.setCoords();
  22807. this.fire('changed');
  22808. this.canvas && this.canvas.fire('text:changed', { target: this });
  22809. },
  22810.  
  22811. /**
  22812. * @private
  22813. * @param {Event} e Event object
  22814. */
  22815. _removeCharsNearCursor: function(e) {
  22816. if (this.selectionStart !== 0) {
  22817.  
  22818. if (e.metaKey) {
  22819. // remove all till the start of current line
  22820. var leftLineBoundary = this.findLineBoundaryLeft(this.selectionStart);
  22821.  
  22822. this._removeCharsFromTo(leftLineBoundary, this.selectionStart);
  22823. this.selectionStart = leftLineBoundary;
  22824. }
  22825. else if (e.altKey) {
  22826. // remove all till the start of current word
  22827. var leftWordBoundary = this.findWordBoundaryLeft(this.selectionStart);
  22828.  
  22829. this._removeCharsFromTo(leftWordBoundary, this.selectionStart);
  22830. this.selectionStart = leftWordBoundary;
  22831. }
  22832. else {
  22833. var isBeginningOfLine = this.text.slice(this.selectionStart - 1, this.selectionStart) === '\n';
  22834. this.removeStyleObject(isBeginningOfLine);
  22835.  
  22836. this.selectionStart--;
  22837. this.text = this.text.slice(0, this.selectionStart) +
  22838. this.text.slice(this.selectionStart + 1);
  22839. }
  22840. }
  22841. }
  22842. });
  22843.  
  22844.  
  22845. /* _TO_SVG_START_ */
  22846. fabric.util.object.extend(fabric.IText.prototype, /** @lends fabric.IText.prototype */ {
  22847.  
  22848. /**
  22849. * @private
  22850. */
  22851. _setSVGTextLineText: function(textLine, lineIndex, textSpans, lineHeight, lineTopOffsetMultiplier, textBgRects) {
  22852. if (!this.styles[lineIndex]) {
  22853. this.callSuper('_setSVGTextLineText',
  22854. textLine, lineIndex, textSpans, lineHeight, lineTopOffsetMultiplier);
  22855. }
  22856. else {
  22857. this._setSVGTextLineChars(
  22858. textLine, lineIndex, textSpans, lineHeight, lineTopOffsetMultiplier, textBgRects);
  22859. }
  22860. },
  22861.  
  22862. /**
  22863. * @private
  22864. */
  22865. _setSVGTextLineChars: function(textLine, lineIndex, textSpans, lineHeight, lineTopOffsetMultiplier, textBgRects) {
  22866.  
  22867. var yProp = lineIndex === 0 || this.useNative ? 'y' : 'dy',
  22868. chars = textLine.split(''),
  22869. charOffset = 0,
  22870. lineLeftOffset = this._getSVGLineLeftOffset(lineIndex),
  22871. lineTopOffset = this._getSVGLineTopOffset(lineIndex),
  22872. heightOfLine = this._getHeightOfLine(this.ctx, lineIndex);
  22873.  
  22874. for (var i = 0, len = chars.length; i < len; i++) {
  22875. var styleDecl = this.styles[lineIndex][i] || { };
  22876.  
  22877. textSpans.push(
  22878. this._createTextCharSpan(
  22879. chars[i], styleDecl, lineLeftOffset, lineTopOffset, yProp, charOffset));
  22880.  
  22881. var charWidth = this._getWidthOfChar(this.ctx, chars[i], lineIndex, i);
  22882.  
  22883. if (styleDecl.textBackgroundColor) {
  22884. textBgRects.push(
  22885. this._createTextCharBg(
  22886. styleDecl, lineLeftOffset, lineTopOffset, heightOfLine, charWidth, charOffset));
  22887. }
  22888.  
  22889. charOffset += charWidth;
  22890. }
  22891. },
  22892.  
  22893. /**
  22894. * @private
  22895. */
  22896. _getSVGLineLeftOffset: function(lineIndex) {
  22897. return (this._boundaries && this._boundaries[lineIndex])
  22898. ? fabric.util.toFixed(this._boundaries[lineIndex].left, 2)
  22899. : 0;
  22900. },
  22901.  
  22902. /**
  22903. * @private
  22904. */
  22905. _getSVGLineTopOffset: function(lineIndex) {
  22906. var lineTopOffset = 0;
  22907. for (var j = 0; j <= lineIndex; j++) {
  22908. lineTopOffset += this._getHeightOfLine(this.ctx, j);
  22909. }
  22910. return lineTopOffset - this.height / 2;
  22911. },
  22912.  
  22913. /**
  22914. * @private
  22915. */
  22916. _createTextCharBg: function(styleDecl, lineLeftOffset, lineTopOffset, heightOfLine, charWidth, charOffset) {
  22917. return [
  22918. //jscs:disable validateIndentation
  22919. '<rect fill="', styleDecl.textBackgroundColor,
  22920. '" transform="translate(',
  22921. -this.width / 2, ' ',
  22922. -this.height + heightOfLine, ')',
  22923. '" x="', lineLeftOffset + charOffset,
  22924. '" y="', lineTopOffset + heightOfLine,
  22925. '" width="', charWidth,
  22926. '" height="', heightOfLine,
  22927. '"></rect>'
  22928. //jscs:enable validateIndentation
  22929. ].join('');
  22930. },
  22931.  
  22932. /**
  22933. * @private
  22934. */
  22935. _createTextCharSpan: function(_char, styleDecl, lineLeftOffset, lineTopOffset, yProp, charOffset) {
  22936.  
  22937. var fillStyles = this.getSvgStyles.call(fabric.util.object.extend({
  22938. visible: true,
  22939. fill: this.fill,
  22940. stroke: this.stroke,
  22941. type: 'text'
  22942. }, styleDecl));
  22943.  
  22944. return [
  22945. //jscs:disable validateIndentation
  22946. '<tspan x="', lineLeftOffset + charOffset, '" ',
  22947. yProp, '="', lineTopOffset, '" ',
  22948.  
  22949. (styleDecl.fontFamily ? 'font-family="' + styleDecl.fontFamily.replace(/"/g, '\'') + '" ': ''),
  22950. (styleDecl.fontSize ? 'font-size="' + styleDecl.fontSize + '" ': ''),
  22951. (styleDecl.fontStyle ? 'font-style="' + styleDecl.fontStyle + '" ': ''),
  22952. (styleDecl.fontWeight ? 'font-weight="' + styleDecl.fontWeight + '" ': ''),
  22953. (styleDecl.textDecoration ? 'text-decoration="' + styleDecl.textDecoration + '" ': ''),
  22954. 'style="', fillStyles, '">',
  22955.  
  22956. fabric.util.string.escapeXml(_char),
  22957. '</tspan>'
  22958. //jscs:enable validateIndentation
  22959. ].join('');
  22960. }
  22961. });
  22962. /* _TO_SVG_END_ */
  22963.  
  22964.  
  22965. (function() {
  22966.  
  22967. if (typeof document !== 'undefined' && typeof window !== 'undefined') {
  22968. return;
  22969. }
  22970.  
  22971. var DOMParser = require('xmldom').DOMParser,
  22972. URL = require('url'),
  22973. HTTP = require('http'),
  22974. HTTPS = require('https'),
  22975.  
  22976. Canvas = require('canvas'),
  22977. Image = require('canvas').Image;
  22978.  
  22979. /** @private */
  22980. function request(url, encoding, callback) {
  22981. var oURL = URL.parse(url);
  22982.  
  22983. // detect if http or https is used
  22984. if ( !oURL.port ) {
  22985. oURL.port = ( oURL.protocol.indexOf('https:') === 0 ) ? 443 : 80;
  22986. }
  22987.  
  22988. // assign request handler based on protocol
  22989. var reqHandler = ( oURL.port === 443 ) ? HTTPS : HTTP,
  22990. req = reqHandler.request({
  22991. hostname: oURL.hostname,
  22992. port: oURL.port,
  22993. path: oURL.path,
  22994. method: 'GET'
  22995. }, function(response) {
  22996. var body = '';
  22997. if (encoding) {
  22998. response.setEncoding(encoding);
  22999. }
  23000. response.on('end', function () {
  23001. callback(body);
  23002. });
  23003. response.on('data', function (chunk) {
  23004. if (response.statusCode === 200) {
  23005. body += chunk;
  23006. }
  23007. });
  23008. });
  23009.  
  23010. req.on('error', function(err) {
  23011. if (err.errno === process.ECONNREFUSED) {
  23012. fabric.log('ECONNREFUSED: connection refused to ' + oURL.hostname + ':' + oURL.port);
  23013. }
  23014. else {
  23015. fabric.log(err.message);
  23016. }
  23017. });
  23018.  
  23019. req.end();
  23020. }
  23021.  
  23022. /** @private */
  23023. function requestFs(path, callback) {
  23024. var fs = require('fs');
  23025. fs.readFile(path, function (err, data) {
  23026. if (err) {
  23027. fabric.log(err);
  23028. throw err;
  23029. }
  23030. else {
  23031. callback(data);
  23032. }
  23033. });
  23034. }
  23035.  
  23036. fabric.util.loadImage = function(url, callback, context) {
  23037. function createImageAndCallBack(data) {
  23038. img.src = new Buffer(data, 'binary');
  23039. // preserving original url, which seems to be lost in node-canvas
  23040. img._src = url;
  23041. callback && callback.call(context, img);
  23042. }
  23043. var img = new Image();
  23044. if (url && (url instanceof Buffer || url.indexOf('data') === 0)) {
  23045. img.src = img._src = url;
  23046. callback && callback.call(context, img);
  23047. }
  23048. else if (url && url.indexOf('http') !== 0) {
  23049. requestFs(url, createImageAndCallBack);
  23050. }
  23051. else if (url) {
  23052. request(url, 'binary', createImageAndCallBack);
  23053. }
  23054. else {
  23055. callback && callback.call(context, url);
  23056. }
  23057. };
  23058.  
  23059. fabric.loadSVGFromURL = function(url, callback, reviver) {
  23060. url = url.replace(/^\n\s*/, '').replace(/\?.*$/, '').trim();
  23061. if (url.indexOf('http') !== 0) {
  23062. requestFs(url, function(body) {
  23063. fabric.loadSVGFromString(body.toString(), callback, reviver);
  23064. });
  23065. }
  23066. else {
  23067. request(url, '', function(body) {
  23068. fabric.loadSVGFromString(body, callback, reviver);
  23069. });
  23070. }
  23071. };
  23072.  
  23073. fabric.loadSVGFromString = function(string, callback, reviver) {
  23074. var doc = new DOMParser().parseFromString(string);
  23075. fabric.parseSVGDocument(doc.documentElement, function(results, options) {
  23076. callback && callback(results, options);
  23077. }, reviver);
  23078. };
  23079.  
  23080. fabric.util.getScript = function(url, callback) {
  23081. request(url, '', function(body) {
  23082. eval(body);
  23083. callback && callback();
  23084. });
  23085. };
  23086.  
  23087. fabric.Image.fromObject = function(object, callback) {
  23088. fabric.util.loadImage(object.src, function(img) {
  23089. var oImg = new fabric.Image(img);
  23090.  
  23091. oImg._initConfig(object);
  23092. oImg._initFilters(object, function(filters) {
  23093. oImg.filters = filters || [ ];
  23094. callback && callback(oImg);
  23095. });
  23096. });
  23097. };
  23098.  
  23099. /**
  23100. * Only available when running fabric on node.js
  23101. * @param {Number} width Canvas width
  23102. * @param {Number} height Canvas height
  23103. * @param {Object} [options] Options to pass to FabricCanvas.
  23104. * @param {Object} [nodeCanvasOptions] Options to pass to NodeCanvas.
  23105. * @return {Object} wrapped canvas instance
  23106. */
  23107. fabric.createCanvasForNode = function(width, height, options, nodeCanvasOptions) {
  23108. nodeCanvasOptions = nodeCanvasOptions || options;
  23109.  
  23110. var canvasEl = fabric.document.createElement('canvas'),
  23111. nodeCanvas = new Canvas(width || 600, height || 600, nodeCanvasOptions);
  23112.  
  23113. // jsdom doesn't create style on canvas element, so here be temp. workaround
  23114. canvasEl.style = { };
  23115.  
  23116. canvasEl.width = nodeCanvas.width;
  23117. canvasEl.height = nodeCanvas.height;
  23118.  
  23119. var FabricCanvas = fabric.Canvas || fabric.StaticCanvas,
  23120. fabricCanvas = new FabricCanvas(canvasEl, options);
  23121.  
  23122. fabricCanvas.contextContainer = nodeCanvas.getContext('2d');
  23123. fabricCanvas.nodeCanvas = nodeCanvas;
  23124. fabricCanvas.Font = Canvas.Font;
  23125.  
  23126. return fabricCanvas;
  23127. };
  23128.  
  23129. /** @ignore */
  23130. fabric.StaticCanvas.prototype.createPNGStream = function() {
  23131. return this.nodeCanvas.createPNGStream();
  23132. };
  23133.  
  23134. fabric.StaticCanvas.prototype.createJPEGStream = function(opts) {
  23135. return this.nodeCanvas.createJPEGStream(opts);
  23136. };
  23137.  
  23138. var origSetWidth = fabric.StaticCanvas.prototype.setWidth;
  23139. fabric.StaticCanvas.prototype.setWidth = function(width, options) {
  23140. origSetWidth.call(this, width, options);
  23141. this.nodeCanvas.width = width;
  23142. return this;
  23143. };
  23144. if (fabric.Canvas) {
  23145. fabric.Canvas.prototype.setWidth = fabric.StaticCanvas.prototype.setWidth;
  23146. }
  23147.  
  23148. var origSetHeight = fabric.StaticCanvas.prototype.setHeight;
  23149. fabric.StaticCanvas.prototype.setHeight = function(height, options) {
  23150. origSetHeight.call(this, height, options);
  23151. this.nodeCanvas.height = height;
  23152. return this;
  23153. };
  23154. if (fabric.Canvas) {
  23155. fabric.Canvas.prototype.setHeight = fabric.StaticCanvas.prototype.setHeight;
  23156. }
  23157.  
  23158. })();
  23159.  
  23160.  
  23161. /* Footer for requirejs AMD support */
  23162.  
  23163. window.fabric = fabric;
  23164.  
  23165. // make sure exports.fabric is always defined when used as 'global' later scopes
  23166. var exports = exports || {};
  23167. exports.fabric = fabric;
  23168.  
  23169. if (typeof define === 'function' && define.amd) {
  23170. define([], function() { return fabric });
  23171. }
  23172.  
  23173.