You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@openmeetings.apache.org by so...@apache.org on 2020/12/24 17:17:04 UTC
[openmeetings] branch master updated: [OPENMEETINGS-2000] moving JS
code to npm (incomplete, broken)
This is an automated email from the ASF dual-hosted git repository.
solomax pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/openmeetings.git
The following commit(s) were added to refs/heads/master by this push:
new f0052b5 [OPENMEETINGS-2000] moving JS code to npm (incomplete, broken)
f0052b5 is described below
commit f0052b57f187f21b9cd1d52c163f79f416bf45f4
Author: Maxim Solodovnik <so...@gmail.com>
AuthorDate: Fri Dec 25 00:16:46 2020 +0700
[OPENMEETINGS-2000] moving JS code to npm (incomplete, broken)
---
.../src/main/assembly/components/templates.xml | 1 -
openmeetings-web/pom.xml | 79 +-
openmeetings-web/src/main/front/chat/src/chat.js | 6 +-
openmeetings-web/src/main/front/room/src/room.js | 2 +-
openmeetings-web/src/main/front/wb/package.json | 21 +
openmeetings-web/src/main/front/wb/src/index.js | 6 +
.../src/main/front/wb/src/interview-area.js | 86 +
.../web/room/wb => front/wb/src}/raw-player.js | 0
.../room/wb => front/wb/src}/raw-tool-apointer.js | 0
.../web/room/wb => front/wb/src}/raw-tool-arrow.js | 0
.../web/room/wb => front/wb/src}/raw-tool-base.js | 0
.../room/wb => front/wb/src}/raw-tool-clipart.js | 0
.../room/wb => front/wb/src}/raw-tool-ellipse.js | 0
.../web/room/wb => front/wb/src}/raw-tool-line.js | 0
.../web/room/wb => front/wb/src}/raw-tool-math.js | 0
.../web/room/wb => front/wb/src}/raw-tool-paint.js | 0
.../room/wb => front/wb/src}/raw-tool-pointer.js | 0
.../web/room/wb => front/wb/src}/raw-tool-rect.js | 0
.../wb => front/wb/src}/raw-tool-shape-base.js | 0
.../web/room/wb => front/wb/src}/raw-tool-shape.js | 0
.../web/room/wb => front/wb/src}/raw-tool-text.js | 0
.../room/wb => front/wb/src}/raw-tool-textbox.js | 0
.../web/room/wb => front/wb/src}/raw-tool-uline.js | 0
.../web/room/wb => front/wb/src}/raw-tool-util.js | 0
.../room/wb => front/wb/src}/raw-tool-whiteout.js | 0
.../src/main/front/wb/src/wb-area-base.js | 28 +
openmeetings-web/src/main/front/wb/src/wb-area.js | 460 +
openmeetings-web/src/main/front/wb/src/wb-role.js | 6 +
openmeetings-web/src/main/front/wb/src/wb-tools.js | 362 +
openmeetings-web/src/main/front/wb/src/wb-utils.js | 9 +
openmeetings-web/src/main/front/wb/src/wb-zoom.js | 162 +
openmeetings-web/src/main/front/wb/src/wb.js | 519 +
.../apache/openmeetings/web/room/RoomPanel.java | 3 +-
.../openmeetings/web/room/wb/InterviewWbPanel.java | 3 -
.../org/apache/openmeetings/web/room/wb/fabric.js | 29648 -------------------
.../openmeetings/web/room/wb/raw-interview-area.js | 99 -
.../openmeetings/web/room/wb/raw-wb-area-base.js | 22 -
.../apache/openmeetings/web/room/wb/raw-wb-area.js | 456 -
.../openmeetings/web/room/wb/raw-wb-board.js | 955 -
pom.xml | 2 +-
40 files changed, 1683 insertions(+), 31252 deletions(-)
diff --git a/openmeetings-server/src/main/assembly/components/templates.xml b/openmeetings-server/src/main/assembly/components/templates.xml
index ef3defe..c9d89f7 100644
--- a/openmeetings-server/src/main/assembly/components/templates.xml
+++ b/openmeetings-server/src/main/assembly/components/templates.xml
@@ -33,7 +33,6 @@
<excludes>
<exclude>**/raw-*.css</exclude>
<exclude>**/raw-*.js</exclude>
- <exclude>**/fabric.js</exclude>
<exclude>**/MathJax*.js</exclude>
</excludes>
</fileSet>
diff --git a/openmeetings-web/pom.xml b/openmeetings-web/pom.xml
index e35439d..d399dd9 100644
--- a/openmeetings-web/pom.xml
+++ b/openmeetings-web/pom.xml
@@ -156,6 +156,24 @@
</environmentVariables>
</configuration>
</execution>
+ <execution>
+ <id>wb-install</id>
+ <goals><goal>npm</goal></goals>
+ <configuration>
+ <workingDirectory>src/main/front/wb</workingDirectory>
+ </configuration>
+ </execution>
+ <execution>
+ <id>wb</id>
+ <goals><goal>npm</goal></goals>
+ <configuration>
+ <arguments>run build</arguments>
+ <workingDirectory>src/main/front/wb</workingDirectory>
+ <environmentVariables>
+ <outDir>${project.build.directory}/generated-sources/js/org/apache/openmeetings/web/room/wb/</outDir>
+ </environmentVariables>
+ </configuration>
+ </execution>
</executions>
</plugin>
<plugin>
@@ -198,62 +216,6 @@
</configuration>
</execution>
<execution>
- <id>interview-wb-js</id>
- <goals>
- <goal>minify</goal>
- </goals>
- <configuration>
- <charset>UTF-8</charset>
- <jsSourceDir>../java/org/apache/openmeetings/web/room/wb</jsSourceDir>
- <jsSourceFiles>
- <jsSourceFile>raw-wb-area-base.js</jsSourceFile>
- <jsSourceFile>raw-interview-area.js</jsSourceFile>
- </jsSourceFiles>
- <jsFinalFile>interviewwb.js</jsFinalFile>
- <jsTargetDir>../generated-sources/js/org/apache/openmeetings/web/room/wb/</jsTargetDir>
- <jsEngine>CLOSURE</jsEngine>
- </configuration>
- </execution>
- <execution>
- <id>wb-js</id>
- <goals>
- <goal>minify</goal>
- </goals>
- <configuration>
- <charset>UTF-8</charset>
- <jsSourceDir>../java/org/apache/openmeetings/web/room/wb</jsSourceDir>
- <jsSourceFiles>
- <jsSourceFile>fabric.js</jsSourceFile>
- <jsSourceFile>MathJax-config.js</jsSourceFile>
- <jsSourceFile>MathJax.js</jsSourceFile>
- <jsSourceFile>raw-wb-area-base.js</jsSourceFile>
- <jsSourceFile>raw-tool-util.js</jsSourceFile>
- <jsSourceFile>raw-player.js</jsSourceFile>
- <jsSourceFile>raw-tool-base.js</jsSourceFile>
- <jsSourceFile>raw-tool-pointer.js</jsSourceFile>
- <jsSourceFile>raw-tool-apointer.js</jsSourceFile>
- <jsSourceFile>raw-tool-shape-base.js</jsSourceFile>
- <jsSourceFile>raw-tool-text.js</jsSourceFile>
- <jsSourceFile>raw-tool-whiteout.js</jsSourceFile>
- <jsSourceFile>raw-tool-textbox.js</jsSourceFile>
- <jsSourceFile>raw-tool-math.js</jsSourceFile>
- <jsSourceFile>raw-tool-paint.js</jsSourceFile>
- <jsSourceFile>raw-tool-shape.js</jsSourceFile>
- <jsSourceFile>raw-tool-line.js</jsSourceFile>
- <jsSourceFile>raw-tool-uline.js</jsSourceFile>
- <jsSourceFile>raw-tool-rect.js</jsSourceFile>
- <jsSourceFile>raw-tool-ellipse.js</jsSourceFile>
- <jsSourceFile>raw-tool-arrow.js</jsSourceFile>
- <jsSourceFile>raw-tool-clipart.js</jsSourceFile>
- <jsSourceFile>raw-wb-board.js</jsSourceFile>
- <jsSourceFile>raw-wb-area.js</jsSourceFile>
- </jsSourceFiles>
- <jsFinalFile>wb.js</jsFinalFile>
- <jsTargetDir>../generated-sources/js/org/apache/openmeetings/web/room/wb/</jsTargetDir>
- <jsEngine>CLOSURE</jsEngine>
- </configuration>
- </execution>
- <execution>
<id>nettest-js</id>
<goals>
<goal>minify</goal>
@@ -280,13 +242,11 @@
**/*.class,
**/raw-*.css,
**/raw-*.js,
- **/fabric.js,
**/MathJax*.js,
</packagingExcludes>
<warSourceExcludes>
**/raw-*.css,
**/raw-*.js,
- **/fabric.js,
**/MathJax*.js,
</warSourceExcludes>
<filteringDeploymentDescriptors>true</filteringDeploymentDescriptors>
@@ -303,7 +263,6 @@
</includes>
<excludes>
<exclude>**/raw-*.js</exclude>
- <exclude>**/fabric.js</exclude>
<exclude>**/MathJax*.js</exclude>
</excludes>
</webResource>
@@ -416,7 +375,6 @@
<excludes>
<exclude>**/raw-*.css</exclude>
<exclude>**/raw-*.js</exclude>
- <exclude>**/fabric.js</exclude>
<exclude>**/MathJax*.js</exclude>
<exclude>**/network.js</exclude>
</excludes>
@@ -447,7 +405,6 @@
<excludes>
<exclude>**/raw-*.css</exclude>
<exclude>**/raw-*.js</exclude>
- <exclude>**/fabric.js</exclude>
<exclude>**/MathJax*.js</exclude>
<exclude>**/network.js</exclude>
</excludes>
diff --git a/openmeetings-web/src/main/front/chat/src/chat.js b/openmeetings-web/src/main/front/chat/src/chat.js
index 24f74f1..74c9d33 100644
--- a/openmeetings-web/src/main/front/chat/src/chat.js
+++ b/openmeetings-web/src/main/front/chat/src/chat.js
@@ -189,11 +189,11 @@ function _reinit(opts) {
typingTimer = setTimeout(doneTyping, doneTypingInterval);
}
});
- $('#chat .chat-toolbar .link-field').off().on('keypress', function() {
- if (event.keyCode === 13) {
+ $('#chat .chat-toolbar .link-field').off().on('keypress', function(evt) {
+ if (evt.keyCode === 13) {
$(this).parent().find('button').trigger('click');
}
- return event.keyCode !== 13;
+ return evt.keyCode !== 13;
});
inited = true;
}
diff --git a/openmeetings-web/src/main/front/room/src/room.js b/openmeetings-web/src/main/front/room/src/room.js
index 5ce9675..6e603b6 100644
--- a/openmeetings-web/src/main/front/room/src/room.js
+++ b/openmeetings-web/src/main/front/room/src/room.js
@@ -12,7 +12,7 @@ let options, menuHeight, sb, dock, noSleep;
function _init(_options) {
options = _options;
- window.WbArea = options.interview ? InterviewWbArea() : DrawWbArea();
+ window.WbArea = options.interview ? new InterviewWbArea() : new DrawWbArea();
const menu = $('.room-block .room-container .menu');
sb = $('.room-block .sidebar');
sb.width(sb.width()); // this is required to 'fix' the width so it will not depend on CSS var
diff --git a/openmeetings-web/src/main/front/wb/package.json b/openmeetings-web/src/main/front/wb/package.json
new file mode 100644
index 0000000..13c30a5
--- /dev/null
+++ b/openmeetings-web/src/main/front/wb/package.json
@@ -0,0 +1,21 @@
+{
+ "name": "wb",
+ "version": "1.0.0",
+ "description": "Methods for WB",
+ "main": "src/index.js",
+ "scripts": {
+ "build-dev": "browserify src/index.js --transform-key=staging -o ${outDir}${npm_package_name}.js",
+ "build-prod": "browserify src/index.js --transform-key=production -p tinyify -o ${outDir}${npm_package_name}.min.js",
+ "build": "npm run build-dev && npm run build-prod"
+ },
+ "author": "",
+ "license": "Apache-2.0",
+ "rat-license": "Licensed under the Apache License, Version 2.0 (the \"License\") http://www.apache.org/licenses/LICENSE-2.0",
+ "devDependencies": {
+ "browserify": "^17.0.0",
+ "tinyify": "^3.0.0"
+ },
+ "dependencies": {
+ "fabric": "^4.3.0"
+ }
+}
diff --git a/openmeetings-web/src/main/front/wb/src/index.js b/openmeetings-web/src/main/front/wb/src/index.js
new file mode 100644
index 0000000..1c51ebe
--- /dev/null
+++ b/openmeetings-web/src/main/front/wb/src/index.js
@@ -0,0 +1,6 @@
+/* Licensed under the Apache License, Version 2.0 (the "License") http://www.apache.org/licenses/LICENSE-2.0 */
+
+Object.assign(window, {
+ InterviewWbArea: require('./interview-area')
+ , DrawWbArea: require('./wb-area')
+});
diff --git a/openmeetings-web/src/main/front/wb/src/interview-area.js b/openmeetings-web/src/main/front/wb/src/interview-area.js
new file mode 100644
index 0000000..b9eba47
--- /dev/null
+++ b/openmeetings-web/src/main/front/wb/src/interview-area.js
@@ -0,0 +1,86 @@
+/* Licensed under the Apache License, Version 2.0 (the "License") http://www.apache.org/licenses/LICENSE-2.0 */
+const WbAreaBase = require('./wb-area-base');
+
+module.exports = class InterviewWbArea extends WbAreaBase {
+ constructor() {
+ super();
+ let container, area, pArea, _inited = false, rec;
+
+ function _updateAreaClass() {
+ const count = pArea.find('.pod:not(.ui-helper,.ui-sortable-placeholder)').length
+ , empt = pArea.find('.empty');
+ if (count < 2) {
+ empt.length === 0 && pArea.append($('<div class="empty"></div>'));
+ } else {
+ empt.remove();
+ }
+ const cls = 'pod-area max' +
+ [2, 3, 5, 9, 13, 17, 25, 33].find((el) => {
+ return count < el;
+ });
+ pArea.attr('class', cls);
+ }
+ this.init = () => {
+ super.init();
+ container = $(".room-block .wb-block");
+ area = container.find(".wb-area");
+ pArea = area.find(".pod-area");
+ rec = area.find('.rec-btn');
+ rec.attr('title', rec.data('title-start'));
+ rec.button({
+ disabled: true
+ , showLabel: false
+ , icon: 'record'
+ }).click(function() {
+ OmUtil.wbAction({action: $(this).data('mode') === 'rec' ? 'startRecording' : 'stopRecording'});
+ });
+ pArea.find('.pod-big').droppable({
+ accept: '.pod'
+ , activeClass: 'ui-hightlight'
+ , drop: function(_, ui) {
+ const big = $(this)
+ , vid = ui.draggable.find('.ui-dialog-content')
+ , cvid = big.find('.ui-dialog-content');
+ if (cvid.length === 0) {
+ vid.dialog('option', 'appendTo', big);
+ ui.draggable.remove();
+ } else {
+ cvid.dialog('option', 'appendTo', ui.draggable);
+ cvid.data().reattachStream();
+ vid.dialog('option', 'appendTo', big);
+ }
+ vid.data().reattachStream();
+ pArea.find('.ui-sortable-placeholder.pod').hide();
+ _updateAreaClass();
+ }
+ });
+ pArea.sortable({
+ items: '.pod'
+ , handle: '.ui-dialog-titlebar'
+ , stop: function(_, ui) {
+ const vid = ui.item.find('.ui-dialog-content');
+ if (vid.length === 1) {
+ vid.data().reattachStream();
+ }
+ }
+ });
+ _updateAreaClass();
+ _inited = true;
+ };
+ this.setRecEnabled = (en) => {
+ if (!_inited) {
+ return;
+ }
+ rec.data('mode', 'rec').button('option', {disabled: !en, icon: 'record'});
+ };
+ this.setRecStarted = (started) => {
+ if (!_inited) {
+ return;
+ }
+ rec.data('mode', started ? 'stop' : 'rec')
+ .attr('title', rec.data(started ? 'title-stop' : 'title-start'))
+ .button('option', {icon: started ? 'stop' : 'record'});
+ };
+ this.updateAreaClass = _updateAreaClass;
+ }
+};
diff --git a/openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-player.js b/openmeetings-web/src/main/front/wb/src/raw-player.js
similarity index 100%
rename from openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-player.js
rename to openmeetings-web/src/main/front/wb/src/raw-player.js
diff --git a/openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-tool-apointer.js b/openmeetings-web/src/main/front/wb/src/raw-tool-apointer.js
similarity index 100%
rename from openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-tool-apointer.js
rename to openmeetings-web/src/main/front/wb/src/raw-tool-apointer.js
diff --git a/openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-tool-arrow.js b/openmeetings-web/src/main/front/wb/src/raw-tool-arrow.js
similarity index 100%
rename from openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-tool-arrow.js
rename to openmeetings-web/src/main/front/wb/src/raw-tool-arrow.js
diff --git a/openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-tool-base.js b/openmeetings-web/src/main/front/wb/src/raw-tool-base.js
similarity index 100%
rename from openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-tool-base.js
rename to openmeetings-web/src/main/front/wb/src/raw-tool-base.js
diff --git a/openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-tool-clipart.js b/openmeetings-web/src/main/front/wb/src/raw-tool-clipart.js
similarity index 100%
rename from openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-tool-clipart.js
rename to openmeetings-web/src/main/front/wb/src/raw-tool-clipart.js
diff --git a/openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-tool-ellipse.js b/openmeetings-web/src/main/front/wb/src/raw-tool-ellipse.js
similarity index 100%
rename from openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-tool-ellipse.js
rename to openmeetings-web/src/main/front/wb/src/raw-tool-ellipse.js
diff --git a/openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-tool-line.js b/openmeetings-web/src/main/front/wb/src/raw-tool-line.js
similarity index 100%
rename from openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-tool-line.js
rename to openmeetings-web/src/main/front/wb/src/raw-tool-line.js
diff --git a/openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-tool-math.js b/openmeetings-web/src/main/front/wb/src/raw-tool-math.js
similarity index 100%
rename from openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-tool-math.js
rename to openmeetings-web/src/main/front/wb/src/raw-tool-math.js
diff --git a/openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-tool-paint.js b/openmeetings-web/src/main/front/wb/src/raw-tool-paint.js
similarity index 100%
rename from openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-tool-paint.js
rename to openmeetings-web/src/main/front/wb/src/raw-tool-paint.js
diff --git a/openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-tool-pointer.js b/openmeetings-web/src/main/front/wb/src/raw-tool-pointer.js
similarity index 100%
rename from openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-tool-pointer.js
rename to openmeetings-web/src/main/front/wb/src/raw-tool-pointer.js
diff --git a/openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-tool-rect.js b/openmeetings-web/src/main/front/wb/src/raw-tool-rect.js
similarity index 100%
rename from openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-tool-rect.js
rename to openmeetings-web/src/main/front/wb/src/raw-tool-rect.js
diff --git a/openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-tool-shape-base.js b/openmeetings-web/src/main/front/wb/src/raw-tool-shape-base.js
similarity index 100%
rename from openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-tool-shape-base.js
rename to openmeetings-web/src/main/front/wb/src/raw-tool-shape-base.js
diff --git a/openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-tool-shape.js b/openmeetings-web/src/main/front/wb/src/raw-tool-shape.js
similarity index 100%
rename from openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-tool-shape.js
rename to openmeetings-web/src/main/front/wb/src/raw-tool-shape.js
diff --git a/openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-tool-text.js b/openmeetings-web/src/main/front/wb/src/raw-tool-text.js
similarity index 100%
rename from openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-tool-text.js
rename to openmeetings-web/src/main/front/wb/src/raw-tool-text.js
diff --git a/openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-tool-textbox.js b/openmeetings-web/src/main/front/wb/src/raw-tool-textbox.js
similarity index 100%
rename from openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-tool-textbox.js
rename to openmeetings-web/src/main/front/wb/src/raw-tool-textbox.js
diff --git a/openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-tool-uline.js b/openmeetings-web/src/main/front/wb/src/raw-tool-uline.js
similarity index 100%
rename from openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-tool-uline.js
rename to openmeetings-web/src/main/front/wb/src/raw-tool-uline.js
diff --git a/openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-tool-util.js b/openmeetings-web/src/main/front/wb/src/raw-tool-util.js
similarity index 100%
rename from openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-tool-util.js
rename to openmeetings-web/src/main/front/wb/src/raw-tool-util.js
diff --git a/openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-tool-whiteout.js b/openmeetings-web/src/main/front/wb/src/raw-tool-whiteout.js
similarity index 100%
rename from openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/raw-tool-whiteout.js
rename to openmeetings-web/src/main/front/wb/src/raw-tool-whiteout.js
diff --git a/openmeetings-web/src/main/front/wb/src/wb-area-base.js b/openmeetings-web/src/main/front/wb/src/wb-area-base.js
new file mode 100644
index 0000000..179a051
--- /dev/null
+++ b/openmeetings-web/src/main/front/wb/src/wb-area-base.js
@@ -0,0 +1,28 @@
+/* Licensed under the Apache License, Version 2.0 (the "License") http://www.apache.org/licenses/LICENSE-2.0 */
+module.exports = class WbAreaBase {
+ constructor() {
+ function _wbWsHandler(_, msg) {
+ try {
+ if (msg instanceof Blob) {
+ return; //ping
+ }
+ const m = JSON.parse(msg);
+ if (m && 'wb' === m.type && typeof(WbArea) !== 'undefined' && !!m.func) {
+ WbArea[m.func](m.param);
+ }
+ } catch (err) {
+ //no-op
+ }
+ }
+
+ this.init = () => {
+ Wicket.Event.subscribe("/websocket/message", _wbWsHandler);
+ };
+ this.destroy = () => {
+ Wicket.Event.unsubscribe("/websocket/message", _wbWsHandler);
+ };
+ this.setRole = () => {};
+ this.addDeleteHandler = () => {};
+ this.removeDeleteHandler = () => {};
+ }
+};
diff --git a/openmeetings-web/src/main/front/wb/src/wb-area.js b/openmeetings-web/src/main/front/wb/src/wb-area.js
new file mode 100644
index 0000000..d29f088
--- /dev/null
+++ b/openmeetings-web/src/main/front/wb/src/wb-area.js
@@ -0,0 +1,460 @@
+/* Licensed under the Apache License, Version 2.0 (the "License") http://www.apache.org/licenses/LICENSE-2.0 */
+const WbAreaBase = require('./wb-area-base');
+const Role = require('./wb-role');
+const Wb = require('./wb');
+const fabric = require('fabric');
+
+const arrowImg = new Image(), delImg = new Image();
+
+arrowImg.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAICAYAAADqSp8ZAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAAygAAAMoBawMUsgAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAFsSURBVCiRrdI/SEJRFMfx37lPGxqKoGwxKJoaImhpCf8NEUFL9WgLUrPnIyEIa6reVEPQn0GeWDS4NDQETQ2JT4waojUoHBqCoJKWINB3720yIhGl+q7ncj5nuIQ6jWiaq1xmU4IwBACQ5GCAU5D8IECRAkUQzt8V++wmlSrX20e1BoFIrFdwHidIIQhH5O68sgzD/vnOF4m0QyijJGgMQIHZtJdJJ4oNg6qqNr20dKwBaOWKvZFPpZ7qXV3JH4wNSMbjJHGZ7XIlYRiiFkiBsL4CphwLwbck5E7uwMw3ClXD2iRImY [...]
+delImg.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAMAAAGgrv1cAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADNQTFRFAAAA4j094j094j094j094j094j094j094j094j094j094j094j094j094j094j094j09hIdAxgAAABB0Uk5TABAgMEBQYHCAj5+vv8/f7yMagooAAADXSURBVBgZBcEBYoQgDACw1DJETmz//9olwGn6AAAbBxoiSACTpCTtJd02smg+MPoef7UgnpPQeVM42Vg02kl+qAPeE2B19wYAgO83xi6ggRMoBfuvsUSxp+vPjag98VqwC8oI9ozC5rMnUVbw5ITID94Fo4D4umsAwN/+urvfOwDg6d8FiFUnALPnkwCs6zvg+UKcSmD3ZBWyL4hTye4J3s16AXG6J+D+uD/A7vtUAutF [...]
+;
+
+// Fabric overrides (should be kept up-to-date on fabric.js updates)
+if ('function' !== typeof(window.originalDrawControl)) {
+ window.originalDrawControl = fabric.Object.prototype._drawControl;
+ window.originalGetRotatedCornerCursor = fabric.Canvas.prototype._getRotatedCornerCursor;
+ window.originalGetActionFromCorner = fabric.Canvas.prototype._getActionFromCorner;
+ window.originalGetCornerCursor = fabric.Canvas.prototype.getCornerCursor;
+ fabric.Object.prototype._drawControl = function(control, ctx, methodName, left, top, styleOverride) {
+ switch (control) {
+ case 'mtr':
+ {
+ const x = left + (this.cornerSize - arrowImg.width) / 2
+ , y = top + (this.cornerSize - arrowImg.height) / 2;
+ ctx.drawImage(arrowImg, x, y);
+ }
+ break;
+ case 'tr':
+ {
+ if (role === Role.PRESENTER) {
+ const x = left + (this.cornerSize - delImg.width) / 2
+ , y = top + (this.cornerSize - delImg.height) / 2;
+ ctx.drawImage(delImg, x, y);
+ } else {
+ window.originalDrawControl.call(this, control, ctx, methodName, left, top, styleOverride);
+ }
+ }
+ break;
+ default:
+ window.originalDrawControl.call(this, control, ctx, methodName, left, top, styleOverride);
+ break;
+ }
+ };
+ fabric.Canvas.prototype._getRotatedCornerCursor = function(corner, target, e) {
+ if (role === Role.PRESENTER && 'tr' === corner) {
+ return 'pointer';
+ }
+ return window.originalGetRotatedCornerCursor.call(this, corner, target, e);
+ };
+ fabric.Canvas.prototype._getActionFromCorner = function(alreadySelected, corner, e) {
+ if (role === Role.PRESENTER && 'tr' === corner) {
+ _performDelete();
+ return 'none';
+ }
+ return window.originalGetActionFromCorner.call(this, alreadySelected, corner, e);
+ };
+ fabric.Canvas.prototype.getCornerCursor = function(corner, target, e) {
+ if (role === Role.PRESENTER && 'tr' === corner) {
+ return 'pointer';
+ }
+ return window.originalGetCornerCursor.call(this, corner, target, e);
+ }
+}
+
+function __getWbTabId(id) {
+ return 'wb-tab-' + id;
+}
+function __getWbContentId(id) {
+ return 'wb-content-' + id;
+}
+function _getWbTab(wbId) {
+ return $('#' + __getWbTabId(wbId));
+}
+function _getWbContent(wbId) {
+ return $('#' + __getWbContentId(wbId));
+}
+function _getWb(id) {
+ return _getWbContent(id).data();
+}
+function _setTabName(link, name) {
+ return link.attr('title', name)
+ .find('span').text(name)
+}
+function _renameTab(obj) {
+ _setTabName(_getWbTab(obj.wbId), obj.name);
+}
+function _getActive() {
+ const tab = $('.room-block .wb-block .tabs .wb-tab-content .wb-tab.active');
+ if (tab.length === 1) {
+ return tab;
+ }
+ return null;
+}
+function _getImage(cnv) {
+ return cnv.toDataURL({
+ format: 'image/png'
+ , width: cnv.width
+ , height: cnv.height
+ , multiplier: 1. / cnv.getZoom()
+ , left: 0
+ , top: 0
+ });
+}
+function _videoStatus(json) {
+ _getWb(json.wbId).videoStatus(json);
+}
+function _initVideos(arr) {
+ for (let i = 0; i < arr.length; ++i) {
+ _videoStatus(arr[i]);
+ }
+}
+function _actionActivateWb(_wbId) {
+ OmUtil.wbAction({action: 'activateWb', data: {wbId: _wbId}});
+}
+
+
+module.exports = class DrawWbArea extends WbAreaBase {
+ constructor() {
+ super();
+ let scroll, role = Role.NONE, _inited = false;
+
+ function _performDelete() {
+ const wb = _getActive().data()
+ , canvas = wb.getCanvas();
+ if (role !== Role.PRESENTER || !canvas) {
+ return true;
+ }
+ const arr = [], objs = canvas.getActiveObjects();
+ for (let i = 0; i < objs.length; ++i) {
+ arr.push({
+ uid: objs[i].uid
+ , slide: objs[i].slide
+ });
+ }
+ OmUtil.wbAction({action: 'deleteObj', data: {
+ wbId: wb.id
+ , obj: arr
+ }});
+ return false;
+ }
+ function _deleteHandler(e) {
+ if ('BODY' === e.target.tagName) {
+ switch (e.which) {
+ case 8: // backspace
+ case 46: // delete
+ e.preventDefault();
+ e.stopImmediatePropagation();
+ return _performDelete();
+ default:
+ //no-op
+ }
+ }
+ }
+ function _activateTab(wbId) {
+ const link = _getWbTab(wbId);
+ if (link.length > 0) {
+ link.tab('show');
+ if (role !== Role.PRESENTER) {
+ $('.wb-tabbar ul.nav-tabs a.nav-link').removeClass('active');
+ link.addClass('active');
+ $('.wb-tab-content .wb-tab').removeClass('active');
+ $('#' + link.attr('aria-controls')).addClass('active');
+ }
+ link[0].scrollIntoView();
+ }
+ }
+ function _addCloseBtn(li) {
+ if (role !== Role.PRESENTER || li.find('button').length > 0) {
+ return;
+ }
+ const link = li.find('a')
+ , wbId = link.data('wb-id');
+ // Apply right click menu only to the text item
+ li.find(".nav-link").find("span").first().contextmenu(
+ function(e) {
+ e.preventDefault();
+ $('#wb-rename-menu').show().data('wb-id', wbId)
+ .position({my: 'left top', collision: 'none', of: _getWbTab(wbId)});
+ });
+ link.append(OmUtil.tmpl('#wb-tab-close'));
+ li.find('button')
+ .confirmation({
+ confirmationEvent: 'bla'
+ , onConfirm: function() {
+ OmUtil.wbAction({action: 'removeWb', data: {wbId: wbId}});
+ }
+ });
+ }
+ function __initTab(elems) {
+ const links = elems.find('a');
+ if (role === Role.PRESENTER) {
+ elems.each(function() {
+ _addCloseBtn($(this));
+ });
+ links.prop('disabled', false).removeClass('disabled');
+ } else {
+ links.prop('disabled', true).addClass('disabled');
+ elems.find('button').remove();
+ }
+ links.off()
+ .click(function(e) {
+ e.preventDefault();
+ if (role === Role.PRESENTER) {
+ _actionActivateWb($(this).data('wb-id'));
+ }
+ });
+ }
+ function _doInit(callback) {
+ const tabs = $('.room-block .wb-block .tabs');
+ if (tabs.length === 0) {
+ setTimeout(_doInit, 100, callback);
+ return;
+ }
+ scroll = tabs.find('.scroll-container');
+ $('.room-block .wb-block .tabs ul.nav-tabs').sortable({
+ axis: 'x'
+ });
+ _inited = true;
+ this.setRole(role);
+ if (typeof(callback) === 'function') {
+ callback();
+ }
+ $('#wb-rename-menu').menu().find('.wb-rename').click(function() {
+ const textSpan = _getWbTab($(this).parent().data('wb-id')).find('.wb-nav-tab-text').first();
+ textSpan.trigger('dblclick');
+ });
+ }
+
+ this.init = (callback) => {
+ super.init();
+ _doInit(callback);
+ };
+ //FIXME TODO self.getWb = _getWb;
+ this.setRole = (_role) => {
+ if (!_inited) {
+ return;
+ }
+ role = _role;
+ const tabs = $('.room-block .wb-block .tabs');
+ const tabsNav = tabs.find('ul.nav-tabs');
+ tabsNav.sortable(role === Role.PRESENTER ? 'enable' : 'disable');
+ const prev = tabs.find('.prev.om-icon'), next = tabs.find('.next.om-icon');
+ if (role === Role.PRESENTER) {
+ if (prev.length === 0) {
+ const cc = tabs.find('.wb-tabbar .scroll-container')
+ , left = OmUtil.tmpl('#wb-tabbar-ctrls-left')
+ , right = OmUtil.tmpl('#wb-tabbar-ctrls-right');
+ cc.before(left).after(right);
+ tabs.find('.add.om-icon').click(function() {
+ OmUtil.wbAction({action: 'createWb'});
+ });
+ tabs.find('.prev.om-icon').click(function() {
+ scroll.scrollLeft(scroll.scrollLeft() - 30);
+ });
+ tabs.find('.next.om-icon').click(function() {
+ scroll.scrollLeft(scroll.scrollLeft() + 30);
+ });
+ this.addDeleteHandler();
+ }
+ } else {
+ if (prev.length > 0) {
+ prev.parent().remove();
+ next.parent().remove();
+ }
+ this.removeDeleteHandler();
+ }
+ __initTab(tabsNav.find('li'));
+ tabs.find('.wb-tab-content .wb-tab').each(function() {
+ $(this).data().setRole(role);
+ });
+ };
+ this.destroy = () => {
+ super.destroy();
+ this.removeDeleteHandler();
+ };
+ this.create = (obj) => {
+ if (!_inited) {
+ return;
+ }
+ const tid = __getWbTabId(obj.wbId)
+ , tcid = __getWbContentId(obj.wbId)
+ , wb = OmUtil.tmpl('#wb-area', tcid).attr('aria-labelledby', tid)
+ , li = OmUtil.tmpl('#wb-area-tab')
+ , link = li.find('a');
+ link.attr('id', tid).attr('data-wb-id', obj.wbId).attr('href', '#' + tcid).attr('aria-controls', tcid);
+ _setTabName(link, obj.name)
+ .dblclick(function() {
+ if (role !== Role.PRESENTER) {
+ return;
+ }
+ const editor = $('<input class="newName" name="newName" type="text"/>')
+ , name = $(this).hide().after(editor.val(obj.name))
+ , renameWbTab = function() {
+ const newName = editor.val();
+ if (newName !== '') {
+ OmUtil.wbAction({action: 'renameWb', data: {wbId: obj.wbId, name: newName}});
+ }
+ editor.remove();
+ name.show();
+ };
+ editor.focus()
+ .blur(renameWbTab)
+ .keyup(function(evt) {
+ if (evt.which === 13) {
+ renameWbTab();
+ }
+ });
+ });
+
+ const tabs = $('.room-block .wb-block .tabs');
+ tabs.find('ul.nav-tabs').append(li);
+ tabs.find('.wb-tab-content').append(wb);
+ __initTab(li);
+
+ const wbo = new Wb(obj, tcid, role);
+ wb.on('remove', wbo.destroy);
+ wb.data(wbo);
+ };
+ this.createWb = (obj) => {
+ if (!_inited) {
+ return;
+ }
+ this.create(obj);
+ _activateTab(obj.wbId);
+ _actionActivateWb(obj.wbId);
+ };
+ this.activateWb = (obj) => {
+ if (!_inited) {
+ return;
+ }
+ _activateTab(obj.wbId);
+ };
+ this.renameWb = (obj) => {
+ if (!_inited) {
+ return;
+ }
+ _renameTab(obj);
+ };
+ this.removeWb = (obj) => {
+ if (!_inited) {
+ return;
+ }
+ _getWbTab(obj.wbId).parent().remove();
+ _getWbContent(obj.wbId).remove();
+ _actionActivateWb(_getActive().data().id);
+ };
+ this.load = (json) => {
+ if (!_inited) {
+ return;
+ }
+ _getWb(json.wbId).load(json.obj);
+ };
+ this.setSlide = (json) => {
+ if (!_inited) {
+ return;
+ }
+ _getWb(json.wbId).setSlide(json.slide);
+ };
+ this.createObj = (json) => {
+ if (!_inited) {
+ return;
+ }
+ _getWb(json.wbId).createObj(json.obj);
+ };
+ this.modifyObj = (json) => {
+ if (!_inited) {
+ return;
+ }
+ _getWb(json.wbId).modifyObj(json.obj);
+ };
+ this.deleteObj = (json) => {
+ if (!_inited) {
+ return;
+ }
+ _getWb(json.wbId).removeObj(json.obj);
+ };
+ this.clearAll = (json) => {
+ if (!_inited) {
+ return;
+ }
+ _getWb(json.wbId).clearAll();
+ };
+ this.clearSlide = (json) => {
+ if (!_inited) {
+ return;
+ }
+ _getWb(json.wbId).clearSlide(json.slide);
+ };
+ this.setSize = (json) => {
+ if (!_inited) {
+ return;
+ }
+ _getWb(json.wbId).setSize(json);
+ };
+ this.download = (fmt) => {
+ if (!_inited) {
+ return;
+ }
+ const wb = _getActive().data()
+ , url = location.pathname.substring(0, location.pathname.indexOf('/', 1)) + '/services/wb/uploadwb/'
+ , arr = [];
+ let type;
+ if ('pdf' === fmt) {
+ wb.eachCanvas(function(cnv) {
+ arr.push(_getImage(cnv));
+ });
+ type = 'pdf';
+ } else {
+ const cnv = wb.getCanvas();
+ arr.push(_getImage(cnv));
+ type = 'png';
+ }
+ $.ajax({
+ type: "POST"
+ , url: url + type + '?sid=' + Room.getOptions().sid
+ , data: {data: JSON.stringify(arr)}
+ , dataType: 'json'
+ , cache: false
+ }).done(function(res) {
+ if ('SUCCESS' === res.serviceResult.type) {
+ OmUtil.wbAction({action: 'download', data: {
+ type: type
+ , fuid: res.serviceResult.message
+ }});
+ } else {
+ OmUtil.error(res.serviceResult.message);
+ }
+ }).fail(function(err) {
+ OmUtil.error(err);
+ });
+ }
+ this.videoStatus = _videoStatus;
+ this.loadVideos = () => {
+ if (!_inited) {
+ return;
+ }
+ OmUtil.wbAction({action: 'loadVideos'});
+ };
+ this.initVideos = _initVideos;
+ this.addDeleteHandler = () => {
+ if (role === Role.PRESENTER) {
+ $(window).keyup(_deleteHandler);
+ }
+ };
+ this.removeDeleteHandler = () => {
+ $(window).off('keyup', _deleteHandler);
+ };
+ this.updateAreaClass = () => {};
+ this.doCleanAll = () => {
+ if (!_inited) {
+ return;
+ }
+ $('.room-block .wb-block .tabs li a').each(function() {
+ const wbId = $(this).data('wb-id');
+ _getWbTab(wbId).remove();
+ _getWbContent(wbId).remove();
+ });
+ };
+ }
+};
diff --git a/openmeetings-web/src/main/front/wb/src/wb-role.js b/openmeetings-web/src/main/front/wb/src/wb-role.js
new file mode 100644
index 0000000..d016024
--- /dev/null
+++ b/openmeetings-web/src/main/front/wb/src/wb-role.js
@@ -0,0 +1,6 @@
+/* Licensed under the Apache License, Version 2.0 (the "License") http://www.apache.org/licenses/LICENSE-2.0 */
+module.exports = {
+ NONE: 'NONE'
+ , PRESENTER: 'PRESENTER'
+ , WHITEBOARD: 'WHITEBOARD'
+};
diff --git a/openmeetings-web/src/main/front/wb/src/wb-tools.js b/openmeetings-web/src/main/front/wb/src/wb-tools.js
new file mode 100644
index 0000000..c03d225
--- /dev/null
+++ b/openmeetings-web/src/main/front/wb/src/wb-tools.js
@@ -0,0 +1,362 @@
+/* Licensed under the Apache License, Version 2.0 (the "License") http://www.apache.org/licenses/LICENSE-2.0 */
+const Role = require('./wb-role');
+const WbUtils = require('./wb-utils');
+
+const ACTIVE = 'active';
+
+function __validBtn(btn) {
+ return !!btn && btn.length === 1
+ && typeof(btn.data) === 'function'
+ && typeof(btn.data()) === 'object'
+ && typeof(btn.data().deactivate) === 'function';
+}
+function _setCurrent(c, _cur) {
+ const hndl = c.find('a')
+ , cur = _cur || c.find('div.om-icon.big:first')
+ c.attr('title', cur.attr('title'));
+ hndl.find('.om-icon').remove();
+ hndl.prepend(cur.clone().addClass('stub').data('toolType', cur.data('toolType')));
+}
+function _initGroup(__id, e) {
+ const c = OmUtil.tmpl(__id);
+ e.after(c);
+ c.find('.om-icon').each(function() {
+ const cur = $(this);
+ cur.click(function() {
+ _setCurrent(c, cur);
+ });
+ });
+ return c;
+}
+function __destroySettings() {
+ $('#wb-settings').modal('dispose');
+}
+
+module.exports = class WbTools {
+ constructor(wbEl) {
+ let tools, settings, math;
+
+ function _initGroupHandle(c) {
+ c.find('a').off().click(function(e) {
+ e.stopImmediatePropagation()
+ const stub = $(this).find('.stub');
+ if (stub.hasClass(ACTIVE)) {
+ $(this).dropdown('toggle')
+ } else {
+ _btnClick(stub.data('toolType'));
+ stub.addClass(ACTIVE);
+ }
+ });
+ _setCurrent(c);
+ }
+ function _getBtn(m) {
+ return !!tools ? tools.find('.om-icon.' + (m || mode) + ':not(.stub)') : null;
+ }
+ function _cleanActive() {
+ !!tools && tools.find('.om-icon.' + ACTIVE).removeClass(ACTIVE);
+ }
+ function _setActive() {
+ !!tools && tools.find('.om-icon.' + mode).addClass(ACTIVE);
+ }
+ function _btnClick(toolType) {
+ const b = _getBtn();
+ if (__validBtn(b)) {
+ b.data().deactivate();
+ }
+ _cleanActive();
+ _getBtn('string' === typeof(toolType) && !!toolType ? toolType : $(this).data('toolType')).data().activate();
+ _setActive();
+ }
+ function _initToolBtn(m, def, obj) {
+ const btn = _getBtn(m);
+ if (!btn || btn.length === 0) {
+ return;
+ }
+ btn.data({
+ obj: obj
+ , toolType: m
+ , activate: function() {
+ if (!btn.hasClass(ACTIVE)) {
+ mode = m;
+ obj.activate();
+ }
+ }
+ , deactivate: function() {
+ obj.deactivate();
+ }
+ }).click(_btnClick);
+ if (def) {
+ btn.data().activate();
+ }
+ }
+ function _initTexts(sBtn) {
+ const c = _initGroup('#wb-area-texts', _getBtn('apointer'));
+ _initToolBtn('text', false, Text(wb, settings, sBtn));
+ _initToolBtn('textbox', false, Textbox(wb, settings, sBtn));
+ _initGroupHandle(c, tools);
+ }
+ function _initDrawings(sBtn) {
+ const c = _initGroup('#wb-area-drawings', tools.find('.texts'));
+ _initToolBtn('eraser', false, Whiteout(wb, settings, sBtn));
+ _initToolBtn('paint', false, Paint(wb, settings, sBtn));
+ _initToolBtn('line', false, Line(wb, settings, sBtn));
+ _initToolBtn('uline', false, ULine(wb, settings, sBtn));
+ _initToolBtn('rect', false, Rect(wb, settings, sBtn));
+ _initToolBtn('ellipse', false, Ellipse(wb, settings, sBtn));
+ _initToolBtn('arrow', false, Arrow(wb, settings, sBtn));
+ _initGroupHandle(c, tools);
+ }
+ function _initCliparts(sBtn) {
+ const c = OmUtil.tmpl('#wb-area-cliparts');
+ tools.find('.drawings').after(c);
+ c.find('.om-icon.clipart').each(function() {
+ const cur = $(this);
+ cur.css('background-image', 'url(' + cur.data('image') + ')')
+ .click(function() {
+ _setCurrent(c, cur);
+ });
+ _initToolBtn(cur.data('mode'), false, Clipart(wb, cur, settings, sBtn));
+ });
+ _initGroupHandle(c, tools);
+ }
+ function _initSettings() {
+ function setStyle(canvas, styleName, value) {
+ const o = canvas.getActiveObject();
+ if (o.setSelectionStyles && o.isEditing) {
+ const style = {};
+ style[styleName] = value;
+ o.setSelectionStyles(style);
+ } else {
+ o[styleName] = value;
+ }
+ canvas.requestRenderAll();
+ }
+ settings.find('.wb-prop-b, .wb-prop-i')
+ .button()
+ .click(function() {
+ $(this).toggleClass('ui-state-active selected');
+ const btn = _getBtn()
+ , isB = $(this).hasClass('wb-prop-b')
+ , style = isB ? 'bold' : 'italic'
+ , v = $(this).hasClass('selected')
+ , val = v ? style : '';
+ btn.data().obj.style[style] = v;
+ wb.eachCanvas(function(canvas) {
+ setStyle(canvas, isB ? 'fontWeight' : 'fontStyle', val)
+ });
+ });
+ settings.find('.wb-prop-lock-color, .wb-prop-lock-fill')
+ .button({icon: 'ui-icon-locked', showLabel: false})
+ .click(function() {
+ const btn = _getBtn()
+ , isColor = $(this).hasClass('wb-prop-lock-color')
+ , c = settings.find(isColor ? '.wb-prop-color' : '.wb-prop-fill')
+ , enabled = $(this).button('option', 'icon') === 'ui-icon-locked';
+ $(this).button('option', 'icon', enabled ? 'ui-icon-unlocked' : 'ui-icon-locked');
+ c.prop('disabled', !enabled);
+ btn.data().obj[isColor ? 'stroke' : 'fill'].enabled = enabled;
+ });
+ settings.find('.wb-prop-color').change(function() {
+ const btn = _getBtn();
+ if (btn.length === 1) {
+ const v = $(this).val();
+ btn.data().obj.stroke.color = v;
+ wb.eachCanvas(function(canvas) {
+ if ('paint' === mode) {
+ canvas.freeDrawingBrush.color = v;
+ } else {
+ setStyle(canvas, 'stroke', v)
+ }
+ });
+ }
+ });
+ settings.find('.wb-prop-width').change(function() {
+ const btn = _getBtn();
+ if (btn.length === 1) {
+ const v = 1 * $(this).val();
+ btn.data().obj.stroke.width = v;
+ wb.eachCanvas(function(canvas) {
+ if ('paint' === mode) {
+ canvas.freeDrawingBrush.width = v;
+ } else {
+ setStyle(canvas, 'strokeWidth', v)
+ }
+ });
+ }
+ });
+ settings.find('.wb-prop-fill').change(function() {
+ const btn = _getBtn();
+ if (btn.length === 1) {
+ const v = $(this).val();
+ btn.data().obj.fill.color = v;
+ wb.eachCanvas(function(canvas) {
+ setStyle(canvas, 'fill', v)
+ });
+ }
+ });
+ settings.find('.wb-prop-opacity').change(function() {
+ const btn = _getBtn();
+ if (btn.length === 1) {
+ const v = (1 * $(this).val()) / 100;
+ btn.data().obj.opacity = v;
+ wb.eachCanvas(function(canvas) {
+ if ('paint' === mode) {
+ canvas.freeDrawingBrush.opacity = v;
+ } else {
+ setStyle(canvas, 'opacity', v)
+ }
+ });
+ }
+ });
+ settings.find('.ui-dialog-titlebar-close').click(function() {
+ settings.hide();
+ });
+ settings.draggable({
+ scroll: false
+ , handle: '.ui-dialog-titlebar'
+ , containment: 'body'
+ , start: function() {
+ if (!!settings.css('bottom')) {
+ settings.css('bottom', '').css(Settings.isRtl ? 'left' : 'right', '');
+ }
+ }
+ , drag: function() {
+ if (settings.position().x + settings.width() >= settings.parent().width()) {
+ return false;
+ }
+ }
+ });
+ }
+ function _initMath() {
+ math.find('.ui-dialog-titlebar-close').click(function() {
+ math.hide();
+ });
+ math.find('.update-btn').button().click(function() {
+ const o = _findObject({
+ uid: $(this).data('uid')
+ , slide: $(this).data('slide')
+ });
+ const json = toOmJson(o);
+ json.formula = math.find('textarea').val();
+ const cnvs = canvases[o.slide];
+ StaticTMath.create(json, cnvs
+ , function(obj) {
+ _removeHandler(o);
+ cnvs.trigger('object:modified', {target: obj});
+ }
+ , function(msg) {
+ const err = math.find('.status');
+ err.text(msg);
+ StaticTMath.highlight(err);
+ });
+ }).parent().css('text-align', Settings.isRtl ? 'left' : 'right');
+ math.draggable({
+ scroll: false
+ , handle: '.ui-dialog-titlebar'
+ , containment: 'body'
+ , start: function() {
+ if (!!math.css('bottom')) {
+ math.css('bottom', '').css(Settings.isRtl ? 'left' : 'right', '');
+ }
+ }
+ , drag: function() {
+ if (math.position().x + math.width() >= math.parent().width()) {
+ return false;
+ }
+ }
+ });
+ math.resizable({
+ minHeight: 140
+ , minWidth: 255
+ });
+ }
+
+ this.setRole = (role) => {
+ const btn = _getBtn();
+ if (__validBtn(btn)) {
+ btn.data().deactivate();
+ }
+ wbEl.find('.tools>div').remove();
+ wbEl.find('.wb-tool-settings').remove();
+ WbUtils.safeRemove(tools);
+ WbUtils.safeRemove(settings);
+ WbUtils.safeRemove(math);
+ if (role === Role.NONE) {
+ __destroySettings();
+ tools = !!Room.getOptions().questions ? OmUtil.tmpl('#wb-tools-readonly') : wbEl.find('invalid-wb-element');
+ } else {
+ tools = OmUtil.tmpl('#wb-tools');
+ settings = OmUtil.tmpl('#wb-tool-settings');
+ settings[0].style.display = 'none';
+ settings[0].style.bottom = '100px';
+ settings[0].style[(Settings.isRtl ? 'left' : 'right')] = '100px';
+ math = OmUtil.tmpl('#wb-formula');
+ math[0].style.display = 'none';
+ math[0].style.bottom = '100px';
+ math[0].style[(Settings.isRtl ? 'left' : 'right')] = '100px';
+ wbEl.append(settings, math);
+ }
+ wbEl.find('.tools').append(tools);
+ tools = wbEl.find('.tools>div');
+ settings = wbEl.find('.wb-tool-settings');
+
+ const clearAll = tools.find('.om-icon.clear-all')
+ , sBtn = tools.find('.om-icon.settings');;
+ let _firstToolItem = true;
+ switch (role) {
+ case Role.PRESENTER:
+ clearAll.confirmation({
+ confirmationEvent: 'om-clear-all'
+ , onConfirm: () => OmUtil.wbAction({action: 'clearAll', data: {wbId: wb.id}})
+ }).removeClass('disabled');
+ case Role.WHITEBOARD:
+ if (role === Role.WHITEBOARD) {
+ clearAll.addClass('disabled');
+ }
+ _initToolBtn('pointer', _firstToolItem, Pointer(wb, settings, sBtn));
+ _firstToolItem = false;
+ _initTexts(sBtn);
+ _initDrawings(sBtn);
+ _initToolBtn('math', _firstToolItem, TMath(wb, settings, sBtn));
+ _initCliparts(sBtn);
+ tools.find('.om-icon.settings').click(function() {
+ settings.show();
+ });
+ tools.find('.om-icon.math').click(function() {
+ math.show();
+ });
+ tools.find('.om-icon.clear-slide')
+ .confirmation({
+ confirmationEvent: 'om-clear-slide'
+ , onConfirm: function() {
+ OmUtil.wbAction({action: 'clearSlide', data: {wbId: wb.id, slide: slide}});
+ }
+ });
+ tools.find('.om-icon.save').click(function() {
+ OmUtil.wbAction({action: 'save', data: {wbId: wb.id}});
+ });
+ tools.find('.om-icon.undo').click(function() {
+ OmUtil.wbAction({action: 'undo', data: {wbId: wb.id}});
+ });
+ _initSettings();
+ _initMath();
+ case Role.NONE:
+ _initToolBtn('apointer', _firstToolItem, APointer(wb, settings, sBtn));
+ default:
+ //no-op
+ }
+ };
+ this.updateCoordinates = (o) => {
+ settings.find('.wb-dim-x').val(o.left);
+ settings.find('.wb-dim-y').val(o.top);
+ settings.find('.wb-dim-w').val(o.width);
+ settings.find('.wb-dim-h').val(o.height);
+ };
+ this.destroy = () => {
+ __destroySettings();
+ };
+ this.getMath = () => {
+ return math;
+ };
+ }
+};
diff --git a/openmeetings-web/src/main/front/wb/src/wb-utils.js b/openmeetings-web/src/main/front/wb/src/wb-utils.js
new file mode 100644
index 0000000..1ccb1b2
--- /dev/null
+++ b/openmeetings-web/src/main/front/wb/src/wb-utils.js
@@ -0,0 +1,9 @@
+/* Licensed under the Apache License, Version 2.0 (the "License") http://www.apache.org/licenses/LICENSE-2.0 */
+
+module.exports = {
+ safeRemove: (e) => {
+ if (typeof(e) === 'object') {
+ e.remove();
+ }
+ }
+};
diff --git a/openmeetings-web/src/main/front/wb/src/wb-zoom.js b/openmeetings-web/src/main/front/wb/src/wb-zoom.js
new file mode 100644
index 0000000..7a9ca16
--- /dev/null
+++ b/openmeetings-web/src/main/front/wb/src/wb-zoom.js
@@ -0,0 +1,162 @@
+/* Licensed under the Apache License, Version 2.0 (the "License") http://www.apache.org/licenses/LICENSE-2.0 */
+const area = $('.room-block .wb-block .wb-area .tabs')
+ , bar = area.find('.wb-tabbar')
+
+module.exports = class WbZoom {
+ constructor(wbEl, wbObj) {
+ this.zoom = 1.;
+ this.zoomMode = 'PAGE_WIDTH';
+
+ let zoomBar;
+ function _sendSetSize() {
+ wbObj.doSetSize();
+ OmUtil.wbAction({action: 'setSize', data: {
+ wbId: wbObj.id
+ , zoom: this.zoom
+ , zoomMode: this.zoomMode
+ , width: wbObj.width
+ , height: wbObj.height
+ }});
+ }
+
+ this.init = (wbo) => {
+ this.zoom = wbo.zoom;
+ this.zoomMode = wbo.zoomMode;
+ };
+ this.update = (role, ccount) => {
+ if (ccount > 1 && role === Role.PRESENTER) {
+ zoomBar.find('.doc-group input').prop("disabled", false);
+ zoomBar.find('.doc-group button').prop("disabled", false);
+ zoomBar.find('.doc-group .curr-slide').removeClass("text-muted");
+ zoomBar.find('.doc-group .curr-slide').addClass("text-dark");
+ zoomBar.find('.doc-group .input-group-text').removeClass("text-muted");
+ const ns = 1 * slide;
+ zoomBar.find('.doc-group .curr-slide').val(ns + 1).attr('max', ccount);
+ zoomBar.find('.doc-group .up').prop('disabled', ns < 1);
+ zoomBar.find('.doc-group .down').prop('disabled', ns > ccount - 2);
+ zoomBar.find('.doc-group .last-page').text(ccount);
+ } else {
+ zoomBar.find('.doc-group .curr-slide').val(0);
+ zoomBar.find('.doc-group .last-page').text("-");
+ zoomBar.find('.doc-group .curr-slide').addClass("text-muted");
+ zoomBar.find('.doc-group .curr-slide').removeClass("text-dark");
+ zoomBar.find('.doc-group .input-group-text').addClass("text-muted");
+ zoomBar.find('.doc-group input').prop("disabled", true);
+ zoomBar.find('.doc-group button').prop("disabled", true);
+ }
+ };
+ this.setRole = (role) => {
+ wbEl.find('.wb-zoom').remove();
+ zoomBar = OmUtil.tmpl('#wb-zoom');
+ wbEl.find('.wb-zoom-block').append(zoomBar);
+
+ switch (role) {
+ case Role.PRESENTER:
+ zoomBar.find('.curr-slide').change(function() {
+ _setSlide($(this).val() - 1);
+ showCurrentSlide();
+ });
+ zoomBar.find('.doc-group .up').click(function () {
+ _setSlide(1 * slide - 1);
+ showCurrentSlide();
+ });
+ zoomBar.find('.doc-group .down').click(function () {
+ _setSlide(1 * slide + 1);
+ showCurrentSlide();
+ });
+ zoomBar.find('.settings-group').show().find('.settings').click(function () {
+ const wbs = $('#wb-settings')
+ , wbsw = wbs.find('.wbs-width').val(width)
+ , wbsh = wbs.find('.wbs-height').val(height);
+ function isNumeric(n) {
+ return !isNaN(parseInt(n)) && isFinite(n);
+ }
+ wbs.modal('show');
+ wbs.find('.btn-ok').off().click(function() {
+ const __w = wbsw.val(), __h = wbsh.val();
+ if (isNumeric(__w) && isNumeric(__h)) {
+ width = parseInt(__w);
+ height = parseInt(__h);
+ _sendSetSize();
+ }
+ wbs.modal('hide');
+ })
+ });
+ case Role.WHITEBOARD:
+ // fallthrough
+ case Role.NONE:
+ zoomBar.update(role, canvases.length);
+ zoomBar.find('.zoom-out').click(function() {
+ this.zoom -= .2;
+ if (this.zoom < .1) {
+ this.zoom = .1;
+ }
+ this.zoomMode = 'ZOOM';
+ _sendSetSize();
+ });
+ zoomBar.find('.zoom-in').click(function() {
+ this.zoom += .2;
+ this.zoomMode = 'ZOOM';
+ _sendSetSize();
+ });
+ zoomBar.find('.zoom').change(function() {
+ const zzz = $(this).val();
+ this.zoomMode = 'ZOOM';
+ if (isNaN(zzz)) {
+ switch (zzz) {
+ case 'FULL_FIT':
+ case 'PAGE_WIDTH':
+ this.zoomMode = zzz;
+ break;
+ case 'custom':
+ this.zoom = 1. * $(this).data('custom-val');
+ break;
+ default:
+ //no-op
+ }
+ } else {
+ this.zoom = 1. * zzz;
+ }
+ _sendSetSize();
+ });
+ default:
+ //no-op
+ }
+ };
+ this.setSize = () => {
+ switch (this.zoomMode) {
+ case 'FULL_FIT':
+ this.zoom = Math.min((area.width() - 30) / wbObj.width, (area.height() - bar.height() - 30) / wbObj.height);
+ zoomBar.find('.zoom').val(this.zoomMode);
+ break;
+ case 'PAGE_WIDTH':
+ this.zoom = (area.width() - 30 - 40) / wbObj.width; // bumper + toolbar
+ zoomBar.find('.zoom').val(this.zoomMode);
+ break;
+ default:
+ {
+ const oo = zoomBar.find('.zoom').find('option[value="' + this.zoom.toFixed(2) + '"]');
+ if (oo.length === 1) {
+ oo.prop('selected', true);
+ } else {
+ zoomBar
+ .find('.zoom')
+ .data('custom-val', this.zoom)
+ .find('option[value=custom]')
+ .text((100. * this.zoom).toFixed(0) + '%')
+ .prop('selected', true);
+ }
+ }
+ break;
+ }
+ };
+ }
+
+ get zoom() {
+ return this.zoom;
+ }
+
+ get mode() {
+ return this.zoomMode;
+ }
+};
diff --git a/openmeetings-web/src/main/front/wb/src/wb.js b/openmeetings-web/src/main/front/wb/src/wb.js
new file mode 100644
index 0000000..d0357b6
--- /dev/null
+++ b/openmeetings-web/src/main/front/wb/src/wb.js
@@ -0,0 +1,519 @@
+/* Licensed under the Apache License, Version 2.0 (the "License") http://www.apache.org/licenses/LICENSE-2.0 */
+const Role = require('./wb-role');
+const Tools = require('./wb-tools');
+const WbZoom = require('./wb-zoom');
+const fabric = require('fabric');
+
+const BUMPER = 100
+ , extraProps = ['uid', 'fileId', 'fileType', 'count', 'slide', 'omType', '_src', 'formula'];
+
+
+module.exports = class Wb {
+ constructor(wbo, tcid, _role) {
+ this.id = wbo.wbId;
+ this.title = wbo.name;
+ this.width = wbo.width;
+ this.height = wbo.height;
+ const canvases = [];
+ let wbEl, tools, zoomBar, mode, slide = 0
+ , role = null, scrollTimeout = null;
+
+ function _setSlide(_sld) {
+ const sld = 1 * _sld;
+ if (sld < 0 || sld > canvases.length - 1) {
+ return;
+ }
+ slide = _sld;
+ OmUtil.wbAction({action: 'setSlide', data: {
+ wbId: this.id
+ , slide: _sld
+ }});
+ zoomBar.update(role, canvases.length);
+ }
+ function _findObject(o) {
+ let _o = null;
+ const cnvs = canvases[o.slide];
+ if (!!cnvs) {
+ cnvs.forEachObject(function(__o) {
+ if (!!__o && o.uid === __o.uid) {
+ _o = __o;
+ return false;
+ }
+ });
+ }
+ return _o;
+ }
+ function _removeHandler(o) {
+ const __o = _findObject(o);
+ if (!!__o) {
+ const cnvs = canvases[o.slide];
+ if (!!cnvs) {
+ if ('Video' === __o.omType) {
+ $('#wb-video-' + __o.uid).remove();
+ }
+ cnvs.remove(__o);
+ }
+ }
+ }
+ function _modifyHandler(_o) {
+ _removeHandler(_o);
+ _createHandler(_o);
+ }
+ function _createHandler(_o) {
+ switch (_o.fileType) {
+ case 'VIDEO':
+ case 'RECORDING':
+ //no-op
+ break;
+ case 'PRESENTATION':
+ {
+ const ccount = canvases.length;
+ for (let i = 0; i < _o.count; ++i) {
+ if (canvases.length < i + 1) {
+ addCanvas();
+ }
+ const canvas = canvases[i];
+ if (_o.deleted) {
+ ToolUtil.addDeletedItem(canvas, _o);
+ } else {
+ let scale = this.width / _o.width;
+ scale = scale < 1 ? 1 : scale;
+ canvas.setBackgroundImage(_o._src + '&slide=' + i, canvas.renderAll.bind(canvas)
+ , {scaleX: scale, scaleY: scale});
+ }
+ }
+ zoomBar.update(role, canvases.length);
+ if (ccount !== canvases.length) {
+ const b = _getBtn();
+ if (__validBtn(b)) {
+ b.data().deactivate();
+ b.data().activate();
+ }
+ showCurrentSlide();
+ }
+ }
+ break;
+ default:
+ {
+ const canvas = canvases[_o.slide];
+ if (!!canvas) {
+ _o.selectable = canvas.selection;
+ _o.editable = ('text' === mode || 'textbox' === mode);
+ canvas.add(_o);
+ }
+ }
+ break;
+ }
+ }
+ function _createObject(arr, handler) {
+ fabric.util.enlivenObjects(arr, function(objects) {
+ this.eachCanvas(function(canvas) {
+ canvas.renderOnAddRemove = false;
+ });
+
+ for (let i = 0; i < objects.length; ++i) {
+ const _o = objects[i];
+ _o.loaded = true;
+ handler(_o);
+ }
+
+ this.eachCanvas(function(canvas) {
+ canvas.renderOnAddRemove = true;
+ canvas.requestRenderAll();
+ });
+ });
+ }
+
+ function toOmJson(o) {
+ const r = o.toJSON(extraProps);
+ switch (o.omType) {
+ case 'Video':
+ delete r.objects;
+ break;
+ case 'Math':
+ delete r.objects;
+ break;
+ default:
+ //no-op
+ }
+ return r;
+ }
+ //events
+ function objCreatedHandler(o) {
+ if (role === Role.NONE && o.omType !== 'pointer') {
+ return;
+ }
+ let json;
+ switch(o.omType) {
+ case 'pointer':
+ json = o;
+ break;
+ default:
+ o.includeDefaultValues = false;
+ json = toOmJson(o);
+ break;
+ }
+ OmUtil.wbAction({action: 'createObj', data: {
+ wbId: this.id
+ , obj: json
+ }});
+ }
+ function objAddedHandler(e) {
+ const o = e.target;
+ if (o.loaded === true) {
+ return;
+ }
+ switch(o.omType) {
+ case 'textbox':
+ case 'i-text':
+ o.uid = uuidv4();
+ o.slide = this.slide;
+ objCreatedHandler(o);
+ break;
+ default:
+ o.selectable = this.selection;
+ break;
+ }
+ }
+ function objModifiedHandler(e) {
+ const o = e.target, items = [];
+ if (role === Role.NONE && o.omType !== 'pointer') {
+ return;
+ }
+ o.includeDefaultValues = false;
+ if ('activeSelection' === o.type) {
+ o.clone(function(_o) {
+ // ungrouping
+ _o.includeDefaultValues = false;
+ const _items = _o.destroy().getObjects();
+ for (let i = 0; i < _items.length; ++i) {
+ items.push(toOmJson(_items[i]));
+ }
+ }, extraProps);
+ } else {
+ items.push(toOmJson(o));
+ }
+ OmUtil.wbAction({action: 'modifyObj', data: {
+ wbId: this.id
+ , obj: items
+ }});
+ }
+ function objSelectedHandler(e) {
+ tools.updateCoordinates(e.target);
+ }
+ function selectionCleared(e) {
+ const o = e.target;
+ if (!o || '' !== o.text) {
+ return;
+ }
+ if ('textbox' === o.omType || 'i-text' === o.omType) {
+ OmUtil.wbAction({action: 'deleteObj', data: {
+ wbId: this.id
+ , obj: [{
+ uid: o.uid
+ , slide: o.slide
+ }]
+ }});
+ }
+ }
+ function pathCreatedHandler(o) {
+ o.path.uid = uuidv4();
+ o.path.slide = this.slide;
+ o.path.omType = 'freeDraw';
+ objCreatedHandler(o.path);
+ }
+ function scrollHandler() {
+ if (scrollTimeout !== null) {
+ clearTimeout(scrollTimeout);
+ }
+ scrollTimeout = setTimeout(function() {
+ const sc = wbEl.find('.scroll-container')
+ , canvases = sc.find('.canvas-container');
+ if (Math.round(sc.height() + sc[0].scrollTop) === sc[0].scrollHeight) {
+ if (slide !== canvases.length - 1) {
+ _setSlide(canvases.length - 1);
+ }
+ return false;
+ }
+ canvases.each(function(idx) {
+ const h = $(this).height(), pos = $(this).position();
+ if (slide !== idx && pos.top > BUMPER - h && pos.top < BUMPER) {
+ _setSlide(idx);
+ return false;
+ }
+ });
+ }, 100);
+ }
+ function showCurrentSlide() {
+ wbEl.find('.scroll-container .canvas-container').each(function(idx) {
+ if (role === Role.PRESENTER) {
+ $(this).show();
+ const cclist = wbEl.find('.scroll-container .canvas-container');
+ if (cclist.length > slide) {
+ cclist[slide].scrollIntoView();
+ }
+ } else {
+ if (idx === slide) {
+ $(this).show();
+ } else {
+ $(this).hide();
+ }
+ }
+ });
+ }
+ /*TODO interactive text change
+ var textEditedHandler = function (e) {
+ var obj = e.target;
+ OmUtil.log('Text Edit Exit', obj);
+ };
+ var textChangedHandler = function (e) {
+ var obj = e.target;
+ OmUtil.log('Text Changed', obj);
+ };*/
+ function setHandlers(canvas) {
+ // off everything first to prevent duplicates
+ canvas.off({
+ 'wb:object:created': objCreatedHandler
+ , 'object:modified': objModifiedHandler
+ , 'object:added': objAddedHandler
+ , 'object:selected': objSelectedHandler
+ , 'path:created': pathCreatedHandler
+ //, 'text:editing:exited': textEditedHandler
+ //, 'text:changed': textChangedHandler
+ , 'before:selection:cleared': selectionCleared
+ });
+ canvas.on({
+ 'wb:object:created': objCreatedHandler
+ , 'object:modified': objModifiedHandler
+ });
+ if (role !== Role.NONE) {
+ canvas.on({
+ 'object:added': objAddedHandler
+ , 'object:selected': objSelectedHandler
+ , 'path:created': pathCreatedHandler
+ , 'before:selection:cleared': selectionCleared
+ //, 'text:editing:exited': textEditedHandler
+ //, 'text:changed': textChangedHandler
+ });
+ }
+ }
+ function addCanvas() {
+ const sl = canvases.length
+ , cid = 'can-' + this.id + '-slide-' + sl
+ , c = $('<canvas></canvas>').attr('id', cid);
+ wbEl.find('.canvases').append(c);
+ const canvas = new fabric.Canvas(c.attr('id'), {
+ preserveObjectStacking: true
+ });
+ canvas.wbId = this.id;
+ canvas.slide = sl;
+ canvases.push(canvas);
+ const cc = $('#' + cid).closest('.canvas-container');
+ if (role === Role.NONE) {
+ if (sl === slide) {
+ cc.show();
+ } else {
+ cc.hide();
+ }
+ }
+ __setSize(canvas);
+ setHandlers(canvas);
+ }
+ function __setSize(_cnv) {
+ _cnv.setWidth(zoomBar.zoom * this.width)
+ .setHeight(zoomBar.zoom * this.height)
+ .setZoom(zoomBar.zoom);
+ }
+ function _setSize() {
+ zoomBar.setSize();
+ this.eachCanvas(function(canvas) {
+ __setSize(canvas);
+ });
+ _setSlide(slide);
+ }
+ function _videoStatus(json) {
+ const g = _findObject(json);
+ if (!!g) {
+ g.videoStatus(json.status);
+ }
+ }
+
+ this.setRole = (_role) => {
+ if (role !== _role) {
+ role = _role;
+ const sc = wbEl.find('.scroll-container');
+ if (role === Role.NONE) {
+ sc.off('scroll', scrollHandler);
+ } else {
+ sc.on('scroll', scrollHandler);
+ }
+ showCurrentSlide();
+ this.eachCanvas(function(canvas) {
+ setHandlers(canvas);
+ canvas.forEachObject(function(__o) {
+ if (!!__o && __o.omType === 'Video') {
+ __o.setPlayable(role);
+ }
+ });
+ });
+ tools.setRole(role);
+ zoomBar.setRole(role);
+ _setSize();
+ }
+ };
+ this.setSize = (wbo) => {
+ this.width = wbo.width;
+ this.height = wbo.height;
+ zoomBar.init(wbo);
+ _setSize();
+ };
+ this.doSetSize = _setSize;
+ this.resize = () => {
+ if (zoomBar.mode !== 'ZOOM') {
+ _setSize();
+ }
+ };
+ this.setSlide = (_sl) => {
+ slide = _sl;
+ showCurrentSlide();
+ };
+ this.createObj = (obj) => {
+ const arr = [], del = [], _arr = Array.isArray(obj) ? obj : [obj];
+ for (let i = 0; i < _arr.length; ++i) {
+ const o = _arr[i];
+ if (!!o.deleted && 'PRESENTATION' !== o.fileType) {
+ del.push(o);
+ continue;
+ }
+ switch(o.omType) {
+ case 'pointer':
+ APointer(wb).create(canvases[o.slide], o);
+ break;
+ case 'Video':
+ Player.create(canvases[o.slide], o, wb);
+ break;
+ case 'Math':
+ StaticTMath.create(o, canvases[o.slide]);
+ break;
+ default:
+ {
+ const __o = _findObject(o);
+ if (!__o) {
+ arr.push(o);
+ }
+ }
+ break;
+ }
+ }
+ if (arr.length > 0) {
+ _createObject(arr, _createHandler);
+ }
+ for (let i = 0; i < del.length; ++i) {
+ const o = del[i];
+ ToolUtil.addDeletedItem(canvases[o.slide], o);
+ }
+ };
+ this.load = this.createObj;
+ this.modifyObj = (obj) => { //TODO need to be unified
+ const arr = [], _arr = Array.isArray(obj) ? obj : [obj];
+ for (let i = 0; i < _arr.length; ++i) {
+ const o = _arr[i];
+ switch(o.omType) {
+ case 'pointer':
+ _modifyHandler(APointer(wb).create(canvases[o.slide], o));
+ break;
+ case 'Video':
+ {
+ const g = _findObject(o);
+ if (!!g) {
+ Player.modify(g, o);
+ }
+ }
+ break;
+ case 'Math':
+ {
+ _removeHandler(o);
+ StaticTMath.create(o, canvases[o.slide]);
+ }
+ break;
+ default:
+ arr.push(o);
+ break;
+ }
+ }
+ if (arr.length > 0) {
+ _createObject(arr, _modifyHandler);
+ }
+ };
+ this.removeObj = (arr) => {
+ for (let i = 0; i < arr.length; ++i) {
+ _removeHandler(arr[i]);
+ }
+ };
+ this.clearAll = () => {
+ for (let i = 1; i < canvases.length; ++i) {
+ const cc = $('#can-' + this.id + '-slide-' + i).closest('.canvas-container');
+ cc.remove();
+ canvases[i].dispose();
+ }
+ $('.room-block .wb-block .wb-video').remove();
+ canvases.splice(1);
+ canvases[0].clear();
+ zoomBar.update(role, canvases.length);
+ };
+ this.clearSlide = (_sl) => {
+ if (canvases.length > _sl) {
+ const canvas = canvases[_sl];
+ canvas.renderOnAddRemove = false;
+ let arr = canvas.getObjects();
+ while (arr.length > 0) {
+ canvas.remove(arr[arr.length - 1]);
+ arr = canvas.getObjects();
+ }
+ $('.room-block .wb-block .wb-video.slide-' + _sl).remove();
+ canvas.renderOnAddRemove = true;
+ canvas.requestRenderAll();
+ }
+ };
+ this.getCanvas = () => {
+ return canvases[slide];
+ };
+ this.eachCanvas = (func) => {
+ for (let i = 0; i < canvases.length; ++i) {
+ func(canvases[i]);
+ }
+ };
+ this.videoStatus = _videoStatus;
+ this.getRole = () => {
+ return role;
+ };
+ this.getFormula = () => {
+ return tools.getMath();
+ };
+ this.getZoom = () => {
+ return zoomBar.zoom;
+ };
+ this.destroy = () => {
+ tools.destroy();
+ };
+
+ wbEl = $('#' + tcid);
+ tools = new Tools(wbEl);
+ zoomBar = new WbZoom(wbEl, this);
+ zoomBar.init(wbo);
+ addCanvas();
+ this.setRole(_role);
+ }
+
+ get id() {
+ return this.id;
+ }
+
+ get width() {
+ return this.width;
+ }
+
+ get height() {
+ return this.height;
+ }
+};
diff --git a/openmeetings-web/src/main/java/org/apache/openmeetings/web/room/RoomPanel.java b/openmeetings-web/src/main/java/org/apache/openmeetings/web/room/RoomPanel.java
index af57e28..d01cc60 100644
--- a/openmeetings-web/src/main/java/org/apache/openmeetings/web/room/RoomPanel.java
+++ b/openmeetings-web/src/main/java/org/apache/openmeetings/web/room/RoomPanel.java
@@ -25,7 +25,6 @@ import static org.apache.openmeetings.db.entity.calendar.Appointment.allowedStar
import static org.apache.openmeetings.util.OmFileHelper.EXTENSION_PDF;
import static org.apache.openmeetings.web.app.WebSession.getDateFormat;
import static org.apache.openmeetings.web.app.WebSession.getUserId;
-import static org.apache.openmeetings.web.room.wb.InterviewWbPanel.INTERVIEWWB_JS_REFERENCE;
import static org.apache.openmeetings.web.room.wb.WbPanel.WB_JS_REFERENCE;
import java.io.IOException;
@@ -680,7 +679,7 @@ public class RoomPanel extends BasePanel {
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
- response.render(new PriorityHeaderItem(JavaScriptHeaderItem.forReference(interview ? INTERVIEWWB_JS_REFERENCE : WB_JS_REFERENCE)));
+ response.render(new PriorityHeaderItem(JavaScriptHeaderItem.forReference(WB_JS_REFERENCE)));
response.render(new PriorityHeaderItem(JavaScriptHeaderItem.forReference(new JavaScriptResourceReference(RoomPanel.class, "room.js"))) {
private static final long serialVersionUID = 1L;
diff --git a/openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/InterviewWbPanel.java b/openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/InterviewWbPanel.java
index 550c3c5..bdf55fc 100644
--- a/openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/InterviewWbPanel.java
+++ b/openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/InterviewWbPanel.java
@@ -26,15 +26,12 @@ import org.apache.openmeetings.db.entity.file.BaseFileItem;
import org.apache.openmeetings.db.entity.room.Room.Right;
import org.apache.openmeetings.web.room.RoomPanel;
import org.apache.wicket.core.request.handler.IPartialPageRequestHandler;
-import org.apache.wicket.request.resource.JavaScriptResourceReference;
-import org.apache.wicket.request.resource.ResourceReference;
import org.apache.wicket.spring.injection.annot.SpringBean;
import com.github.openjson.JSONObject;
public class InterviewWbPanel extends AbstractWbPanel {
private static final long serialVersionUID = 1L;
- public static final ResourceReference INTERVIEWWB_JS_REFERENCE = new JavaScriptResourceReference(WbPanel.class, "interviewwb.js");
@SpringBean
private StreamProcessor streamProcessor;
diff --git a/openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/fabric.js b/openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/fabric.js
deleted file mode 100644
index fcf17b0..0000000
--- a/openmeetings-web/src/main/java/org/apache/openmeetings/web/room/wb/fabric.js
+++ /dev/null
@@ -1,29648 +0,0 @@
-/* Licensed MIT https://github.com/kangax/fabric.js/blob/master/LICENSE */
-/* build: `node build.js modules=ALL exclude=gestures,accessors requirejs minifier=uglifyjs` */
-/*! Fabric.js Copyright 2008-2015, Printio (Juriy Zaytsev, Maxim Chernyak) */
-
-var fabric = fabric || { version: '3.6.0' };
-if (typeof exports !== 'undefined') {
- exports.fabric = fabric;
-}
-/* _AMD_START_ */
-else if (typeof define === 'function' && define.amd) {
- define([], function() { return fabric; });
-}
-/* _AMD_END_ */
-if (typeof document !== 'undefined' && typeof window !== 'undefined') {
- if (document instanceof (typeof HTMLDocument !== 'undefined' ? HTMLDocument : Document)) {
- fabric.document = document;
- }
- else {
- fabric.document = document.implementation.createHTMLDocument('');
- }
- fabric.window = window;
-}
-else {
- // assume we're running under node.js when document/window are not present
- var jsdom = require('jsdom');
- var virtualWindow = new jsdom.JSDOM(
- decodeURIComponent('%3C!DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3C%2Fhead%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E'),
- {
- features: {
- FetchExternalResources: ['img']
- },
- resources: 'usable'
- }).window;
- fabric.document = virtualWindow.document;
- fabric.jsdomImplForWrapper = require('jsdom/lib/jsdom/living/generated/utils').implForWrapper;
- fabric.nodeCanvas = require('jsdom/lib/jsdom/utils').Canvas;
- fabric.window = virtualWindow;
- DOMParser = fabric.window.DOMParser;
-}
-
-/**
- * True when in environment that supports touch events
- * @type boolean
- */
-fabric.isTouchSupported = 'ontouchstart' in fabric.window || 'ontouchstart' in fabric.document ||
- (fabric.window && fabric.window.navigator && fabric.window.navigator.maxTouchPoints > 0);
-
-/**
- * True when in environment that's probably Node.js
- * @type boolean
- */
-fabric.isLikelyNode = typeof Buffer !== 'undefined' &&
- typeof window === 'undefined';
-
-/* _FROM_SVG_START_ */
-/**
- * Attributes parsed from all SVG elements
- * @type array
- */
-fabric.SHARED_ATTRIBUTES = [
- 'display',
- 'transform',
- 'fill', 'fill-opacity', 'fill-rule',
- 'opacity',
- 'stroke', 'stroke-dasharray', 'stroke-linecap', 'stroke-dashoffset',
- 'stroke-linejoin', 'stroke-miterlimit',
- 'stroke-opacity', 'stroke-width',
- 'id', 'paint-order', 'vector-effect',
- 'instantiated_by_use', 'clip-path'
-];
-/* _FROM_SVG_END_ */
-
-/**
- * Pixel per Inch as a default value set to 96. Can be changed for more realistic conversion.
- */
-fabric.DPI = 96;
-fabric.reNum = '(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:[eE][-+]?\\d+)?)';
-fabric.rePathCommand = /([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/ig;
-fabric.reNonWord = /[ \n\.,;!\?\-]/;
-fabric.fontPaths = { };
-fabric.iMatrix = [1, 0, 0, 1, 0, 0];
-fabric.svgNS = 'http://www.w3.org/2000/svg';
-
-/**
- * Pixel limit for cache canvases. 1Mpx , 4Mpx should be fine.
- * @since 1.7.14
- * @type Number
- * @default
- */
-fabric.perfLimitSizeTotal = 2097152;
-
-/**
- * Pixel limit for cache canvases width or height. IE fixes the maximum at 5000
- * @since 1.7.14
- * @type Number
- * @default
- */
-fabric.maxCacheSideLimit = 4096;
-
-/**
- * Lowest pixel limit for cache canvases, set at 256PX
- * @since 1.7.14
- * @type Number
- * @default
- */
-fabric.minCacheSideLimit = 256;
-
-/**
- * Cache Object for widths of chars in text rendering.
- */
-fabric.charWidthsCache = { };
-
-/**
- * if webgl is enabled and available, textureSize will determine the size
- * of the canvas backend
- * @since 2.0.0
- * @type Number
- * @default
- */
-fabric.textureSize = 2048;
-
-/**
- * When 'true', style information is not retained when copy/pasting text, making
- * pasted text use destination style.
- * Defaults to 'false'.
- * @type Boolean
- * @default
- */
-fabric.disableStyleCopyPaste = false;
-
-/**
- * Enable webgl for filtering picture is available
- * A filtering backend will be initialized, this will both take memory and
- * time since a default 2048x2048 canvas will be created for the gl context
- * @since 2.0.0
- * @type Boolean
- * @default
- */
-fabric.enableGLFiltering = true;
-
-/**
- * Device Pixel Ratio
- * @see https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/HTML-canvas-guide/SettingUptheCanvas/SettingUptheCanvas.html
- */
-fabric.devicePixelRatio = fabric.window.devicePixelRatio ||
- fabric.window.webkitDevicePixelRatio ||
- fabric.window.mozDevicePixelRatio ||
- 1;
-/**
- * Browser-specific constant to adjust CanvasRenderingContext2D.shadowBlur value,
- * which is unitless and not rendered equally across browsers.
- *
- * Values that work quite well (as of October 2017) are:
- * - Chrome: 1.5
- * - Edge: 1.75
- * - Firefox: 0.9
- * - Safari: 0.95
- *
- * @since 2.0.0
- * @type Number
- * @default 1
- */
-fabric.browserShadowBlurConstant = 1;
-
-/**
- * This object contains the result of arc to beizer conversion for faster retrieving if the same arc needs to be converted again.
- * It was an internal variable, is accessible since version 2.3.4
- */
-fabric.arcToSegmentsCache = { };
-
-/**
- * This object keeps the results of the boundsOfCurve calculation mapped by the joined arguments necessary to calculate it.
- * It does speed up calculation, if you parse and add always the same paths, but in case of heavy usage of freedrawing
- * you do not get any speed benefit and you get a big object in memory.
- * The object was a private variable before, while now is appended to the lib so that you have access to it and you
- * can eventually clear it.
- * It was an internal variable, is accessible since version 2.3.4
- */
-fabric.boundsOfCurveCache = { };
-
-/**
- * If disabled boundsOfCurveCache is not used. For apps that make heavy usage of pencil drawing probably disabling it is better
- * @default true
- */
-fabric.cachesBoundsOfCurve = true;
-
-/**
- * Skip performance testing of setupGLContext and force the use of putImageData that seems to be the one that works best on
- * Chrome + old hardware. if your users are experiencing empty images after filtering you may try to force this to true
- * this has to be set before instantiating the filtering backend ( before filtering the first image )
- * @type Boolean
- * @default false
- */
-fabric.forceGLPutImageData = false;
-
-fabric.initFilterBackend = function() {
- if (fabric.enableGLFiltering && fabric.isWebglSupported && fabric.isWebglSupported(fabric.textureSize)) {
- console.log('max texture size: ' + fabric.maxTextureSize);
- return (new fabric.WebglFilterBackend({ tileSize: fabric.textureSize }));
- }
- else if (fabric.Canvas2dFilterBackend) {
- return (new fabric.Canvas2dFilterBackend());
- }
-};
-
-
-if (typeof document !== 'undefined' && typeof window !== 'undefined') {
- // ensure globality even if entire library were function wrapped (as in Meteor.js packaging system)
- window.fabric = fabric;
-}
-
-
-(function() {
-
- /**
- * @private
- * @param {String} eventName
- * @param {Function} handler
- */
- function _removeEventListener(eventName, handler) {
- if (!this.__eventListeners[eventName]) {
- return;
- }
- var eventListener = this.__eventListeners[eventName];
- if (handler) {
- eventListener[eventListener.indexOf(handler)] = false;
- }
- else {
- fabric.util.array.fill(eventListener, false);
- }
- }
-
- /**
- * Observes specified event
- * @deprecated `observe` deprecated since 0.8.34 (use `on` instead)
- * @memberOf fabric.Observable
- * @alias on
- * @param {String|Object} eventName Event name (eg. 'after:render') or object with key/value pairs (eg. {'after:render': handler, 'selection:cleared': handler})
- * @param {Function} handler Function that receives a notification when an event of the specified type occurs
- * @return {Self} thisArg
- * @chainable
- */
- function observe(eventName, handler) {
- if (!this.__eventListeners) {
- this.__eventListeners = { };
- }
- // one object with key/value pairs was passed
- if (arguments.length === 1) {
- for (var prop in eventName) {
- this.on(prop, eventName[prop]);
- }
- }
- else {
- if (!this.__eventListeners[eventName]) {
- this.__eventListeners[eventName] = [];
- }
- this.__eventListeners[eventName].push(handler);
- }
- return this;
- }
-
- /**
- * Stops event observing for a particular event handler. Calling this method
- * without arguments removes all handlers for all events
- * @deprecated `stopObserving` deprecated since 0.8.34 (use `off` instead)
- * @memberOf fabric.Observable
- * @alias off
- * @param {String|Object} eventName Event name (eg. 'after:render') or object with key/value pairs (eg. {'after:render': handler, 'selection:cleared': handler})
- * @param {Function} handler Function to be deleted from EventListeners
- * @return {Self} thisArg
- * @chainable
- */
- function stopObserving(eventName, handler) {
- if (!this.__eventListeners) {
- return this;
- }
-
- // remove all key/value pairs (event name -> event handler)
- if (arguments.length === 0) {
- for (eventName in this.__eventListeners) {
- _removeEventListener.call(this, eventName);
- }
- }
- // one object with key/value pairs was passed
- else if (arguments.length === 1 && typeof arguments[0] === 'object') {
- for (var prop in eventName) {
- _removeEventListener.call(this, prop, eventName[prop]);
- }
- }
- else {
- _removeEventListener.call(this, eventName, handler);
- }
- return this;
- }
-
- /**
- * Fires event with an optional options object
- * @deprecated `fire` deprecated since 1.0.7 (use `trigger` instead)
- * @memberOf fabric.Observable
- * @alias trigger
- * @param {String} eventName Event name to fire
- * @param {Object} [options] Options object
- * @return {Self} thisArg
- * @chainable
- */
- function fire(eventName, options) {
- if (!this.__eventListeners) {
- return this;
- }
-
- var listenersForEvent = this.__eventListeners[eventName];
- if (!listenersForEvent) {
- return this;
- }
-
- for (var i = 0, len = listenersForEvent.length; i < len; i++) {
- listenersForEvent[i] && listenersForEvent[i].call(this, options || { });
- }
- this.__eventListeners[eventName] = listenersForEvent.filter(function(value) {
- return value !== false;
- });
- return this;
- }
-
- /**
- * @namespace fabric.Observable
- * @tutorial {@link http://fabricjs.com/fabric-intro-part-2#events}
- * @see {@link http://fabricjs.com/events|Events demo}
- */
- fabric.Observable = {
- observe: observe,
- stopObserving: stopObserving,
- fire: fire,
-
- on: observe,
- off: stopObserving,
- trigger: fire
- };
-})();
-
-
-/**
- * @namespace fabric.Collection
- */
-fabric.Collection = {
-
- _objects: [],
-
- /**
- * Adds objects to collection, Canvas or Group, then renders canvas
- * (if `renderOnAddRemove` is not `false`).
- * in case of Group no changes to bounding box are made.
- * Objects should be instances of (or inherit from) fabric.Object
- * Use of this function is highly discouraged for groups.
- * you can add a bunch of objects with the add method but then you NEED
- * to run a addWithUpdate call for the Group class or position/bbox will be wrong.
- * @param {...fabric.Object} object Zero or more fabric instances
- * @return {Self} thisArg
- * @chainable
- */
- add: function () {
- this._objects.push.apply(this._objects, arguments);
- if (this._onObjectAdded) {
- for (var i = 0, length = arguments.length; i < length; i++) {
- this._onObjectAdded(arguments[i]);
- }
- }
- this.renderOnAddRemove && this.requestRenderAll();
- return this;
- },
-
- /**
- * Inserts an object into collection at specified index, then renders canvas (if `renderOnAddRemove` is not `false`)
- * An object should be an instance of (or inherit from) fabric.Object
- * Use of this function is highly discouraged for groups.
- * you can add a bunch of objects with the insertAt method but then you NEED
- * to run a addWithUpdate call for the Group class or position/bbox will be wrong.
- * @param {Object} object Object to insert
- * @param {Number} index Index to insert object at
- * @param {Boolean} nonSplicing When `true`, no splicing (shifting) of objects occurs
- * @return {Self} thisArg
- * @chainable
- */
- insertAt: function (object, index, nonSplicing) {
- var objects = this._objects;
- if (nonSplicing) {
- objects[index] = object;
- }
- else {
- objects.splice(index, 0, object);
- }
- this._onObjectAdded && this._onObjectAdded(object);
- this.renderOnAddRemove && this.requestRenderAll();
- return this;
- },
-
- /**
- * Removes objects from a collection, then renders canvas (if `renderOnAddRemove` is not `false`)
- * @param {...fabric.Object} object Zero or more fabric instances
- * @return {Self} thisArg
- * @chainable
- */
- remove: function() {
- var objects = this._objects,
- index, somethingRemoved = false;
-
- for (var i = 0, length = arguments.length; i < length; i++) {
- index = objects.indexOf(arguments[i]);
-
- // only call onObjectRemoved if an object was actually removed
- if (index !== -1) {
- somethingRemoved = true;
- objects.splice(index, 1);
- this._onObjectRemoved && this._onObjectRemoved(arguments[i]);
- }
- }
-
- this.renderOnAddRemove && somethingRemoved && this.requestRenderAll();
- return this;
- },
-
- /**
- * Executes given function for each object in this group
- * @param {Function} callback
- * Callback invoked with current object as first argument,
- * index - as second and an array of all objects - as third.
- * Callback is invoked in a context of Global Object (e.g. `window`)
- * when no `context` argument is given
- *
- * @param {Object} context Context (aka thisObject)
- * @return {Self} thisArg
- * @chainable
- */
- forEachObject: function(callback, context) {
- var objects = this.getObjects();
- for (var i = 0, len = objects.length; i < len; i++) {
- callback.call(context, objects[i], i, objects);
- }
- return this;
- },
-
- /**
- * Returns an array of children objects of this instance
- * Type parameter introduced in 1.3.10
- * since 2.3.5 this method return always a COPY of the array;
- * @param {String} [type] When specified, only objects of this type are returned
- * @return {Array}
- */
- getObjects: function(type) {
- if (typeof type === 'undefined') {
- return this._objects.concat();
- }
- return this._objects.filter(function(o) {
- return o.type === type;
- });
- },
-
- /**
- * Returns object at specified index
- * @param {Number} index
- * @return {Self} thisArg
- */
- item: function (index) {
- return this._objects[index];
- },
-
- /**
- * Returns true if collection contains no objects
- * @return {Boolean} true if collection is empty
- */
- isEmpty: function () {
- return this._objects.length === 0;
- },
-
- /**
- * Returns a size of a collection (i.e: length of an array containing its objects)
- * @return {Number} Collection size
- */
- size: function() {
- return this._objects.length;
- },
-
- /**
- * Returns true if collection contains an object
- * @param {Object} object Object to check against
- * @return {Boolean} `true` if collection contains an object
- */
- contains: function(object) {
- return this._objects.indexOf(object) > -1;
- },
-
- /**
- * Returns number representation of a collection complexity
- * @return {Number} complexity
- */
- complexity: function () {
- return this._objects.reduce(function (memo, current) {
- memo += current.complexity ? current.complexity() : 0;
- return memo;
- }, 0);
- }
-};
-
-
-/**
- * @namespace fabric.CommonMethods
- */
-fabric.CommonMethods = {
-
- /**
- * Sets object's properties from options
- * @param {Object} [options] Options object
- */
- _setOptions: function(options) {
- for (var prop in options) {
- this.set(prop, options[prop]);
- }
- },
-
- /**
- * @private
- * @param {Object} [filler] Options object
- * @param {String} [property] property to set the Gradient to
- */
- _initGradient: function(filler, property) {
- if (filler && filler.colorStops && !(filler instanceof fabric.Gradient)) {
- this.set(property, new fabric.Gradient(filler));
- }
- },
-
- /**
- * @private
- * @param {Object} [filler] Options object
- * @param {String} [property] property to set the Pattern to
- * @param {Function} [callback] callback to invoke after pattern load
- */
- _initPattern: function(filler, property, callback) {
- if (filler && filler.source && !(filler instanceof fabric.Pattern)) {
- this.set(property, new fabric.Pattern(filler, callback));
- }
- else {
- callback && callback();
- }
- },
-
- /**
- * @private
- * @param {Object} [options] Options object
- */
- _initClipping: function(options) {
- if (!options.clipTo || typeof options.clipTo !== 'string') {
- return;
- }
-
- var functionBody = fabric.util.getFunctionBody(options.clipTo);
- if (typeof functionBody !== 'undefined') {
- this.clipTo = new Function('ctx', functionBody);
- }
- },
-
- /**
- * @private
- */
- _setObject: function(obj) {
- for (var prop in obj) {
- this._set(prop, obj[prop]);
- }
- },
-
- /**
- * 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()`.
- * @param {String|Object} key Property name or object (if object, iterate over the object properties)
- * @param {Object|Function} value Property value (if function, the value is passed into it and its return value is used as a new one)
- * @return {fabric.Object} thisArg
- * @chainable
- */
- set: function(key, value) {
- if (typeof key === 'object') {
- this._setObject(key);
- }
- else {
- if (typeof value === 'function' && key !== 'clipTo') {
- this._set(key, value(this.get(key)));
- }
- else {
- this._set(key, value);
- }
- }
- return this;
- },
-
- _set: function(key, value) {
- this[key] = value;
- },
-
- /**
- * Toggles specified property from `true` to `false` or from `false` to `true`
- * @param {String} property Property to toggle
- * @return {fabric.Object} thisArg
- * @chainable
- */
- toggle: function(property) {
- var value = this.get(property);
- if (typeof value === 'boolean') {
- this.set(property, !value);
- }
- return this;
- },
-
- /**
- * Basic getter
- * @param {String} property Property name
- * @return {*} value of a property
- */
- get: function(property) {
- return this[property];
- }
-};
-
-
-(function(global) {
-
- var sqrt = Math.sqrt,
- atan2 = Math.atan2,
- pow = Math.pow,
- PiBy180 = Math.PI / 180,
- PiBy2 = Math.PI / 2;
-
- /**
- * @namespace fabric.util
- */
- fabric.util = {
-
- /**
- * Calculate the cos of an angle, avoiding returning floats for known results
- * @static
- * @memberOf fabric.util
- * @param {Number} angle the angle in radians or in degree
- * @return {Number}
- */
- cos: function(angle) {
- if (angle === 0) { return 1; }
- if (angle < 0) {
- // cos(a) = cos(-a)
- angle = -angle;
- }
- var angleSlice = angle / PiBy2;
- switch (angleSlice) {
- case 1: case 3: return 0;
- case 2: return -1;
- }
- return Math.cos(angle);
- },
-
- /**
- * Calculate the sin of an angle, avoiding returning floats for known results
- * @static
- * @memberOf fabric.util
- * @param {Number} angle the angle in radians or in degree
- * @return {Number}
- */
- sin: function(angle) {
- if (angle === 0) { return 0; }
- var angleSlice = angle / PiBy2, sign = 1;
- if (angle < 0) {
- // sin(-a) = -sin(a)
- sign = -1;
- }
- switch (angleSlice) {
- case 1: return sign;
- case 2: return 0;
- case 3: return -sign;
- }
- return Math.sin(angle);
- },
-
- /**
- * Removes value from an array.
- * Presence of value (and its position in an array) is determined via `Array.prototype.indexOf`
- * @static
- * @memberOf fabric.util
- * @param {Array} array
- * @param {*} value
- * @return {Array} original array
- */
- removeFromArray: function(array, value) {
- var idx = array.indexOf(value);
- if (idx !== -1) {
- array.splice(idx, 1);
- }
- return array;
- },
-
- /**
- * Returns random number between 2 specified ones.
- * @static
- * @memberOf fabric.util
- * @param {Number} min lower limit
- * @param {Number} max upper limit
- * @return {Number} random value (between min and max)
- */
- getRandomInt: function(min, max) {
- return Math.floor(Math.random() * (max - min + 1)) + min;
- },
-
- /**
- * Transforms degrees to radians.
- * @static
- * @memberOf fabric.util
- * @param {Number} degrees value in degrees
- * @return {Number} value in radians
- */
- degreesToRadians: function(degrees) {
- return degrees * PiBy180;
- },
-
- /**
- * Transforms radians to degrees.
- * @static
- * @memberOf fabric.util
- * @param {Number} radians value in radians
- * @return {Number} value in degrees
- */
- radiansToDegrees: function(radians) {
- return radians / PiBy180;
- },
-
- /**
- * Rotates `point` around `origin` with `radians`
- * @static
- * @memberOf fabric.util
- * @param {fabric.Point} point The point to rotate
- * @param {fabric.Point} origin The origin of the rotation
- * @param {Number} radians The radians of the angle for the rotation
- * @return {fabric.Point} The new rotated point
- */
- rotatePoint: function(point, origin, radians) {
- point.subtractEquals(origin);
- var v = fabric.util.rotateVector(point, radians);
- return new fabric.Point(v.x, v.y).addEquals(origin);
- },
-
- /**
- * Rotates `vector` with `radians`
- * @static
- * @memberOf fabric.util
- * @param {Object} vector The vector to rotate (x and y)
- * @param {Number} radians The radians of the angle for the rotation
- * @return {Object} The new rotated point
- */
- rotateVector: function(vector, radians) {
- var sin = fabric.util.sin(radians),
- cos = fabric.util.cos(radians),
- rx = vector.x * cos - vector.y * sin,
- ry = vector.x * sin + vector.y * cos;
- return {
- x: rx,
- y: ry
- };
- },
-
- /**
- * Apply transform t to point p
- * @static
- * @memberOf fabric.util
- * @param {fabric.Point} p The point to transform
- * @param {Array} t The transform
- * @param {Boolean} [ignoreOffset] Indicates that the offset should not be applied
- * @return {fabric.Point} The transformed point
- */
- transformPoint: function(p, t, ignoreOffset) {
- if (ignoreOffset) {
- return new fabric.Point(
- t[0] * p.x + t[2] * p.y,
- t[1] * p.x + t[3] * p.y
- );
- }
- return new fabric.Point(
- t[0] * p.x + t[2] * p.y + t[4],
- t[1] * p.x + t[3] * p.y + t[5]
- );
- },
-
- /**
- * Returns coordinates of points's bounding rectangle (left, top, width, height)
- * @param {Array} points 4 points array
- * @param {Array} [transform] an array of 6 numbers representing a 2x3 transform matrix
- * @return {Object} Object with left, top, width, height properties
- */
- makeBoundingBoxFromPoints: function(points, transform) {
- if (transform) {
- for (var i = 0; i < points.length; i++) {
- points[i] = fabric.util.transformPoint(points[i], transform);
- }
- }
- var xPoints = [points[0].x, points[1].x, points[2].x, points[3].x],
- minX = fabric.util.array.min(xPoints),
- maxX = fabric.util.array.max(xPoints),
- width = maxX - minX,
- yPoints = [points[0].y, points[1].y, points[2].y, points[3].y],
- minY = fabric.util.array.min(yPoints),
- maxY = fabric.util.array.max(yPoints),
- height = maxY - minY;
-
- return {
- left: minX,
- top: minY,
- width: width,
- height: height
- };
- },
-
- /**
- * Invert transformation t
- * @static
- * @memberOf fabric.util
- * @param {Array} t The transform
- * @return {Array} The inverted transform
- */
- invertTransform: function(t) {
- var a = 1 / (t[0] * t[3] - t[1] * t[2]),
- r = [a * t[3], -a * t[1], -a * t[2], a * t[0]],
- o = fabric.util.transformPoint({ x: t[4], y: t[5] }, r, true);
- r[4] = -o.x;
- r[5] = -o.y;
- return r;
- },
-
- /**
- * A wrapper around Number#toFixed, which contrary to native method returns number, not string.
- * @static
- * @memberOf fabric.util
- * @param {Number|String} number number to operate on
- * @param {Number} fractionDigits number of fraction digits to "leave"
- * @return {Number}
- */
- toFixed: function(number, fractionDigits) {
- return parseFloat(Number(number).toFixed(fractionDigits));
- },
-
- /**
- * Converts from attribute value to pixel value if applicable.
- * Returns converted pixels or original value not converted.
- * @param {Number|String} value number to operate on
- * @param {Number} fontSize
- * @return {Number|String}
- */
- parseUnit: function(value, fontSize) {
- var unit = /\D{0,2}$/.exec(value),
- number = parseFloat(value);
- if (!fontSize) {
- fontSize = fabric.Text.DEFAULT_SVG_FONT_SIZE;
- }
- switch (unit[0]) {
- case 'mm':
- return number * fabric.DPI / 25.4;
-
- case 'cm':
- return number * fabric.DPI / 2.54;
-
- case 'in':
- return number * fabric.DPI;
-
- case 'pt':
- return number * fabric.DPI / 72; // or * 4 / 3
-
- case 'pc':
- return number * fabric.DPI / 72 * 12; // or * 16
-
- case 'em':
- return number * fontSize;
-
- default:
- return number;
- }
- },
-
- /**
- * Function which always returns `false`.
- * @static
- * @memberOf fabric.util
- * @return {Boolean}
- */
- falseFunction: function() {
- return false;
- },
-
- /**
- * Returns klass "Class" object of given namespace
- * @memberOf fabric.util
- * @param {String} type Type of object (eg. 'circle')
- * @param {String} namespace Namespace to get klass "Class" object from
- * @return {Object} klass "Class"
- */
- getKlass: function(type, namespace) {
- // capitalize first letter only
- type = fabric.util.string.camelize(type.charAt(0).toUpperCase() + type.slice(1));
- return fabric.util.resolveNamespace(namespace)[type];
- },
-
- /**
- * Returns array of attributes for given svg that fabric parses
- * @memberOf fabric.util
- * @param {String} type Type of svg element (eg. 'circle')
- * @return {Array} string names of supported attributes
- */
- getSvgAttributes: function(type) {
- var attributes = [
- 'instantiated_by_use',
- 'style',
- 'id',
- 'class'
- ];
- switch (type) {
- case 'linearGradient':
- attributes = attributes.concat(['x1', 'y1', 'x2', 'y2', 'gradientUnits', 'gradientTransform']);
- break;
- case 'radialGradient':
- attributes = attributes.concat(['gradientUnits', 'gradientTransform', 'cx', 'cy', 'r', 'fx', 'fy', 'fr']);
- break;
- case 'stop':
- attributes = attributes.concat(['offset', 'stop-color', 'stop-opacity']);
- break;
- }
- return attributes;
- },
-
- /**
- * Returns object of given namespace
- * @memberOf fabric.util
- * @param {String} namespace Namespace string e.g. 'fabric.Image.filter' or 'fabric'
- * @return {Object} Object for given namespace (default fabric)
- */
- resolveNamespace: function(namespace) {
- if (!namespace) {
- return fabric;
- }
-
- var parts = namespace.split('.'),
- len = parts.length, i,
- obj = global || fabric.window;
-
- for (i = 0; i < len; ++i) {
- obj = obj[parts[i]];
- }
-
- return obj;
- },
-
- /**
- * Loads image element from given url and passes it to a callback
- * @memberOf fabric.util
- * @param {String} url URL representing an image
- * @param {Function} callback Callback; invoked with loaded image
- * @param {*} [context] Context to invoke callback in
- * @param {Object} [crossOrigin] crossOrigin value to set image element to
- */
- loadImage: function(url, callback, context, crossOrigin) {
- if (!url) {
- callback && callback.call(context, url);
- return;
- }
-
- var img = fabric.util.createImage();
-
- /** @ignore */
- var onLoadCallback = function () {
- callback && callback.call(context, img);
- img = img.onload = img.onerror = null;
- };
-
- img.onload = onLoadCallback;
- /** @ignore */
- img.onerror = function() {
- fabric.log('Error loading ' + img.src);
- callback && callback.call(context, null, true);
- img = img.onload = img.onerror = null;
- };
-
- // data-urls appear to be buggy with crossOrigin
- // https://github.com/kangax/fabric.js/commit/d0abb90f1cd5c5ef9d2a94d3fb21a22330da3e0a#commitcomment-4513767
- // see https://code.google.com/p/chromium/issues/detail?id=315152
- // https://bugzilla.mozilla.org/show_bug.cgi?id=935069
- if (url.indexOf('data') !== 0 && crossOrigin) {
- img.crossOrigin = crossOrigin;
- }
-
- // IE10 / IE11-Fix: SVG contents from data: URI
- // will only be available if the IMG is present
- // in the DOM (and visible)
- if (url.substring(0,14) === 'data:image/svg') {
- img.onload = null;
- fabric.util.loadImageInDom(img, onLoadCallback);
- }
-
- img.src = url;
- },
-
- /**
- * Attaches SVG image with data: URL to the dom
- * @memberOf fabric.util
- * @param {Object} img Image object with data:image/svg src
- * @param {Function} callback Callback; invoked with loaded image
- * @return {Object} DOM element (div containing the SVG image)
- */
- loadImageInDom: function(img, onLoadCallback) {
- var div = fabric.document.createElement('div');
- div.style.width = div.style.height = '1px';
- div.style.left = div.style.top = '-100%';
- div.style.position = 'absolute';
- div.appendChild(img);
- fabric.document.querySelector('body').appendChild(div);
- /**
- * Wrap in function to:
- * 1. Call existing callback
- * 2. Cleanup DOM
- */
- img.onload = function () {
- onLoadCallback();
- div.parentNode.removeChild(div);
- div = null;
- };
- },
-
- /**
- * Creates corresponding fabric instances from their object representations
- * @static
- * @memberOf fabric.util
- * @param {Array} objects Objects to enliven
- * @param {Function} callback Callback to invoke when all objects are created
- * @param {String} namespace Namespace to get klass "Class" object from
- * @param {Function} reviver Method for further parsing of object elements,
- * called after each fabric object created.
- */
- enlivenObjects: function(objects, callback, namespace, reviver) {
- objects = objects || [];
-
- var enlivenedObjects = [],
- numLoadedObjects = 0,
- numTotalObjects = objects.length;
-
- function onLoaded() {
- if (++numLoadedObjects === numTotalObjects) {
- callback && callback(enlivenedObjects.filter(function(obj) {
- // filter out undefined objects (objects that gave error)
- return obj;
- }));
- }
- }
-
- if (!numTotalObjects) {
- callback && callback(enlivenedObjects);
- return;
- }
-
- objects.forEach(function (o, index) {
- // if sparse array
- if (!o || !o.type) {
- onLoaded();
- return;
- }
- var klass = fabric.util.getKlass(o.type, namespace);
- klass.fromObject(o, function (obj, error) {
- error || (enlivenedObjects[index] = obj);
- reviver && reviver(o, obj, error);
- onLoaded();
- });
- });
- },
-
- /**
- * Create and wait for loading of patterns
- * @static
- * @memberOf fabric.util
- * @param {Array} patterns Objects to enliven
- * @param {Function} callback Callback to invoke when all objects are created
- * called after each fabric object created.
- */
- enlivenPatterns: function(patterns, callback) {
- patterns = patterns || [];
-
- function onLoaded() {
- if (++numLoadedPatterns === numPatterns) {
- callback && callback(enlivenedPatterns);
- }
- }
-
- var enlivenedPatterns = [],
- numLoadedPatterns = 0,
- numPatterns = patterns.length;
-
- if (!numPatterns) {
- callback && callback(enlivenedPatterns);
- return;
- }
-
- patterns.forEach(function (p, index) {
- if (p && p.source) {
- new fabric.Pattern(p, function(pattern) {
- enlivenedPatterns[index] = pattern;
- onLoaded();
- });
- }
- else {
- enlivenedPatterns[index] = p;
- onLoaded();
- }
- });
- },
-
- /**
- * Groups SVG elements (usually those retrieved from SVG document)
- * @static
- * @memberOf fabric.util
- * @param {Array} elements SVG elements to group
- * @param {Object} [options] Options object
- * @param {String} path Value to set sourcePath to
- * @return {fabric.Object|fabric.Group}
- */
- groupSVGElements: function(elements, options, path) {
- var object;
- if (elements && elements.length === 1) {
- return elements[0];
- }
- if (options) {
- if (options.width && options.height) {
- options.centerPoint = {
- x: options.width / 2,
- y: options.height / 2
- };
- }
- else {
- delete options.width;
- delete options.height;
- }
- }
- object = new fabric.Group(elements, options);
- if (typeof path !== 'undefined') {
- object.sourcePath = path;
- }
- return object;
- },
-
- /**
- * Populates an object with properties of another object
- * @static
- * @memberOf fabric.util
- * @param {Object} source Source object
- * @param {Object} destination Destination object
- * @return {Array} properties Properties names to include
- */
- populateWithProperties: function(source, destination, properties) {
- if (properties && Object.prototype.toString.call(properties) === '[object Array]') {
- for (var i = 0, len = properties.length; i < len; i++) {
- if (properties[i] in source) {
- destination[properties[i]] = source[properties[i]];
- }
- }
- }
- },
-
- /**
- * Draws a dashed line between two points
- *
- * This method is used to draw dashed line around selection area.
- * See <a href="http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas">dotted stroke in canvas</a>
- *
- * @param {CanvasRenderingContext2D} ctx context
- * @param {Number} x start x coordinate
- * @param {Number} y start y coordinate
- * @param {Number} x2 end x coordinate
- * @param {Number} y2 end y coordinate
- * @param {Array} da dash array pattern
- */
- drawDashedLine: function(ctx, x, y, x2, y2, da) {
- var dx = x2 - x,
- dy = y2 - y,
- len = sqrt(dx * dx + dy * dy),
- rot = atan2(dy, dx),
- dc = da.length,
- di = 0,
- draw = true;
-
- ctx.save();
- ctx.translate(x, y);
- ctx.moveTo(0, 0);
- ctx.rotate(rot);
-
- x = 0;
- while (len > x) {
- x += da[di++ % dc];
- if (x > len) {
- x = len;
- }
- ctx[draw ? 'lineTo' : 'moveTo'](x, 0);
- draw = !draw;
- }
-
- ctx.restore();
- },
-
- /**
- * Creates canvas element
- * @static
- * @memberOf fabric.util
- * @return {CanvasElement} initialized canvas element
- */
- createCanvasElement: function() {
- return fabric.document.createElement('canvas');
- },
-
- /**
- * Creates a canvas element that is a copy of another and is also painted
- * @param {CanvasElement} canvas to copy size and content of
- * @static
- * @memberOf fabric.util
- * @return {CanvasElement} initialized canvas element
- */
- copyCanvasElement: function(canvas) {
- var newCanvas = fabric.util.createCanvasElement();
- newCanvas.width = canvas.width;
- newCanvas.height = canvas.height;
- newCanvas.getContext('2d').drawImage(canvas, 0, 0);
- return newCanvas;
- },
-
- /**
- * since 2.6.0 moved from canvas instance to utility.
- * @param {CanvasElement} canvasEl to copy size and content of
- * @param {String} format 'jpeg' or 'png', in some browsers 'webp' is ok too
- * @param {Number} quality <= 1 and > 0
- * @static
- * @memberOf fabric.util
- * @return {String} data url
- */
- toDataURL: function(canvasEl, format, quality) {
- return canvasEl.toDataURL('image/' + format, quality);
- },
-
- /**
- * Creates image element (works on client and node)
- * @static
- * @memberOf fabric.util
- * @return {HTMLImageElement} HTML image element
- */
- createImage: function() {
- return fabric.document.createElement('img');
- },
-
- /**
- * @static
- * @memberOf fabric.util
- * @deprecated since 2.0.0
- * @param {fabric.Object} receiver Object implementing `clipTo` method
- * @param {CanvasRenderingContext2D} ctx Context to clip
- */
- clipContext: function(receiver, ctx) {
- ctx.save();
- ctx.beginPath();
- receiver.clipTo(ctx);
- ctx.clip();
- },
-
- /**
- * Multiply matrix A by matrix B to nest transformations
- * @static
- * @memberOf fabric.util
- * @param {Array} a First transformMatrix
- * @param {Array} b Second transformMatrix
- * @param {Boolean} is2x2 flag to multiply matrices as 2x2 matrices
- * @return {Array} The product of the two transform matrices
- */
- multiplyTransformMatrices: function(a, b, is2x2) {
- // Matrix multiply a * b
- return [
- a[0] * b[0] + a[2] * b[1],
- a[1] * b[0] + a[3] * b[1],
- a[0] * b[2] + a[2] * b[3],
- a[1] * b[2] + a[3] * b[3],
- is2x2 ? 0 : a[0] * b[4] + a[2] * b[5] + a[4],
- is2x2 ? 0 : a[1] * b[4] + a[3] * b[5] + a[5]
- ];
- },
-
- /**
- * Decomposes standard 2x3 matrix into transform components
- * @static
- * @memberOf fabric.util
- * @param {Array} a transformMatrix
- * @return {Object} Components of transform
- */
- qrDecompose: function(a) {
- var angle = atan2(a[1], a[0]),
- denom = pow(a[0], 2) + pow(a[1], 2),
- scaleX = sqrt(denom),
- scaleY = (a[0] * a[3] - a[2] * a [1]) / scaleX,
- skewX = atan2(a[0] * a[2] + a[1] * a [3], denom);
- return {
- angle: angle / PiBy180,
- scaleX: scaleX,
- scaleY: scaleY,
- skewX: skewX / PiBy180,
- skewY: 0,
- translateX: a[4],
- translateY: a[5]
- };
- },
-
- /**
- * Returns a transform matrix starting from an object of the same kind of
- * the one returned from qrDecompose, useful also if you want to calculate some
- * transformations from an object that is not enlived yet
- * @static
- * @memberOf fabric.util
- * @param {Object} options
- * @param {Number} [options.angle] angle in degrees
- * @return {Number[]} transform matrix
- */
- calcRotateMatrix: function(options) {
- if (!options.angle) {
- return fabric.iMatrix.concat();
- }
- var theta = fabric.util.degreesToRadians(options.angle),
- cos = fabric.util.cos(theta),
- sin = fabric.util.sin(theta);
- return [cos, sin, -sin, cos, 0, 0];
- },
-
- /**
- * Returns a transform matrix starting from an object of the same kind of
- * the one returned from qrDecompose, useful also if you want to calculate some
- * transformations from an object that is not enlived yet.
- * is called DimensionsTransformMatrix because those properties are the one that influence
- * the size of the resulting box of the object.
- * @static
- * @memberOf fabric.util
- * @param {Object} options
- * @param {Number} [options.scaleX]
- * @param {Number} [options.scaleY]
- * @param {Boolean} [options.flipX]
- * @param {Boolean} [options.flipY]
- * @param {Number} [options.skewX]
- * @param {Number} [options.skewX]
- * @return {Number[]} transform matrix
- */
- calcDimensionsMatrix: function(options) {
- var scaleX = typeof options.scaleX === 'undefined' ? 1 : options.scaleX,
- scaleY = typeof options.scaleY === 'undefined' ? 1 : options.scaleY,
- scaleMatrix = [
- options.flipX ? -scaleX : scaleX,
- 0,
- 0,
- options.flipY ? -scaleY : scaleY,
- 0,
- 0],
- multiply = fabric.util.multiplyTransformMatrices,
- degreesToRadians = fabric.util.degreesToRadians;
- if (options.skewX) {
- scaleMatrix = multiply(
- scaleMatrix,
- [1, 0, Math.tan(degreesToRadians(options.skewX)), 1],
- true);
- }
- if (options.skewY) {
- scaleMatrix = multiply(
- scaleMatrix,
- [1, Math.tan(degreesToRadians(options.skewY)), 0, 1],
- true);
- }
- return scaleMatrix;
- },
-
- /**
- * Returns a transform matrix starting from an object of the same kind of
- * the one returned from qrDecompose, useful also if you want to calculate some
- * transformations from an object that is not enlived yet
- * @static
- * @memberOf fabric.util
- * @param {Object} options
- * @param {Number} [options.angle]
- * @param {Number} [options.scaleX]
- * @param {Number} [options.scaleY]
- * @param {Boolean} [options.flipX]
- * @param {Boolean} [options.flipY]
- * @param {Number} [options.skewX]
- * @param {Number} [options.skewX]
- * @param {Number} [options.translateX]
- * @param {Number} [options.translateY]
- * @return {Number[]} transform matrix
- */
- composeMatrix: function(options) {
- var matrix = [1, 0, 0, 1, options.translateX || 0, options.translateY || 0],
- multiply = fabric.util.multiplyTransformMatrices;
- if (options.angle) {
- matrix = multiply(matrix, fabric.util.calcRotateMatrix(options));
- }
- if (options.scaleX || options.scaleY || options.skewX || options.skewY || options.flipX || options.flipY) {
- matrix = multiply(matrix, fabric.util.calcDimensionsMatrix(options));
- }
- return matrix;
- },
-
- /**
- * Returns a transform matrix that has the same effect of scaleX, scaleY and skewX.
- * Is deprecated for composeMatrix. Please do not use it.
- * @static
- * @deprecated since 3.4.0
- * @memberOf fabric.util
- * @param {Number} scaleX
- * @param {Number} scaleY
- * @param {Number} skewX
- * @return {Number[]} transform matrix
- */
- customTransformMatrix: function(scaleX, scaleY, skewX) {
- return fabric.util.composeMatrix({ scaleX: scaleX, scaleY: scaleY, skewX: skewX });
- },
-
- /**
- * reset an object transform state to neutral. Top and left are not accounted for
- * @static
- * @memberOf fabric.util
- * @param {fabric.Object} target object to transform
- */
- resetObjectTransform: function (target) {
- target.scaleX = 1;
- target.scaleY = 1;
- target.skewX = 0;
- target.skewY = 0;
- target.flipX = false;
- target.flipY = false;
- target.rotate(0);
- },
-
- /**
- * Extract Object transform values
- * @static
- * @memberOf fabric.util
- * @param {fabric.Object} target object to read from
- * @return {Object} Components of transform
- */
- saveObjectTransform: function (target) {
- return {
- scaleX: target.scaleX,
- scaleY: target.scaleY,
- skewX: target.skewX,
- skewY: target.skewY,
- angle: target.angle,
- left: target.left,
- flipX: target.flipX,
- flipY: target.flipY,
- top: target.top
- };
- },
-
- /**
- * Returns string representation of function body
- * @param {Function} fn Function to get body of
- * @return {String} Function body
- */
- getFunctionBody: function(fn) {
- return (String(fn).match(/function[^{]*\{([\s\S]*)\}/) || {})[1];
- },
-
- /**
- * Returns true if context has transparent pixel
- * at specified location (taking tolerance into account)
- * @param {CanvasRenderingContext2D} ctx context
- * @param {Number} x x coordinate
- * @param {Number} y y coordinate
- * @param {Number} tolerance Tolerance
- */
- isTransparent: function(ctx, x, y, tolerance) {
-
- // If tolerance is > 0 adjust start coords to take into account.
- // If moves off Canvas fix to 0
- if (tolerance > 0) {
- if (x > tolerance) {
- x -= tolerance;
- }
- else {
- x = 0;
- }
- if (y > tolerance) {
- y -= tolerance;
- }
- else {
- y = 0;
- }
- }
-
- var _isTransparent = true, i, temp,
- imageData = ctx.getImageData(x, y, (tolerance * 2) || 1, (tolerance * 2) || 1),
- l = imageData.data.length;
-
- // Split image data - for tolerance > 1, pixelDataSize = 4;
- for (i = 3; i < l; i += 4) {
- temp = imageData.data[i];
- _isTransparent = temp <= 0;
- if (_isTransparent === false) {
- break; // Stop if colour found
- }
- }
-
- imageData = null;
-
- return _isTransparent;
- },
-
- /**
- * Parse preserveAspectRatio attribute from element
- * @param {string} attribute to be parsed
- * @return {Object} an object containing align and meetOrSlice attribute
- */
- parsePreserveAspectRatioAttribute: function(attribute) {
- var meetOrSlice = 'meet', alignX = 'Mid', alignY = 'Mid',
- aspectRatioAttrs = attribute.split(' '), align;
-
- if (aspectRatioAttrs && aspectRatioAttrs.length) {
- meetOrSlice = aspectRatioAttrs.pop();
- if (meetOrSlice !== 'meet' && meetOrSlice !== 'slice') {
- align = meetOrSlice;
- meetOrSlice = 'meet';
- }
- else if (aspectRatioAttrs.length) {
- align = aspectRatioAttrs.pop();
- }
- }
- //divide align in alignX and alignY
- alignX = align !== 'none' ? align.slice(1, 4) : 'none';
- alignY = align !== 'none' ? align.slice(5, 8) : 'none';
- return {
- meetOrSlice: meetOrSlice,
- alignX: alignX,
- alignY: alignY
- };
- },
-
- /**
- * Clear char widths cache for the given font family or all the cache if no
- * fontFamily is specified.
- * Use it if you know you are loading fonts in a lazy way and you are not waiting
- * for custom fonts to load properly when adding text objects to the canvas.
- * If a text object is added when its own font is not loaded yet, you will get wrong
- * measurement and so wrong bounding boxes.
- * After the font cache is cleared, either change the textObject text content or call
- * initDimensions() to trigger a recalculation
- * @memberOf fabric.util
- * @param {String} [fontFamily] font family to clear
- */
- clearFabricFontCache: function(fontFamily) {
- fontFamily = (fontFamily || '').toLowerCase();
- if (!fontFamily) {
- fabric.charWidthsCache = { };
- }
- else if (fabric.charWidthsCache[fontFamily]) {
- delete fabric.charWidthsCache[fontFamily];
- }
- },
-
- /**
- * Given current aspect ratio, determines the max width and height that can
- * respect the total allowed area for the cache.
- * @memberOf fabric.util
- * @param {Number} ar aspect ratio
- * @param {Number} maximumArea Maximum area you want to achieve
- * @return {Object.x} Limited dimensions by X
- * @return {Object.y} Limited dimensions by Y
- */
- limitDimsByArea: function(ar, maximumArea) {
- var roughWidth = Math.sqrt(maximumArea * ar),
- perfLimitSizeY = Math.floor(maximumArea / roughWidth);
- return { x: Math.floor(roughWidth), y: perfLimitSizeY };
- },
-
- capValue: function(min, value, max) {
- return Math.max(min, Math.min(value, max));
- },
-
- findScaleToFit: function(source, destination) {
- return Math.min(destination.width / source.width, destination.height / source.height);
- },
-
- findScaleToCover: function(source, destination) {
- return Math.max(destination.width / source.width, destination.height / source.height);
- },
-
- /**
- * given an array of 6 number returns something like `"matrix(...numbers)"`
- * @memberOf fabric.util
- * @param {Array} trasnform an array with 6 numbers
- * @return {String} transform matrix for svg
- * @return {Object.y} Limited dimensions by Y
- */
- matrixToSVG: function(transform) {
- return 'matrix(' + transform.map(function(value) {
- return fabric.util.toFixed(value, fabric.Object.NUM_FRACTION_DIGITS);
- }).join(' ') + ')';
- }
- };
-})(typeof exports !== 'undefined' ? exports : this);
-
-
-(function() {
-
- var _join = Array.prototype.join;
-
- /* Adapted from http://dxr.mozilla.org/mozilla-central/source/content/svg/content/src/nsSVGPathDataParser.cpp
- * by Andrea Bogazzi code is under MPL. if you don't have a copy of the license you can take it here
- * http://mozilla.org/MPL/2.0/
- */
- function arcToSegments(toX, toY, rx, ry, large, sweep, rotateX) {
- var argsString = _join.call(arguments);
- if (fabric.arcToSegmentsCache[argsString]) {
- return fabric.arcToSegmentsCache[argsString];
- }
-
- var PI = Math.PI, th = rotateX * PI / 180,
- sinTh = fabric.util.sin(th),
- cosTh = fabric.util.cos(th),
- fromX = 0, fromY = 0;
-
- rx = Math.abs(rx);
- ry = Math.abs(ry);
-
- var px = -cosTh * toX * 0.5 - sinTh * toY * 0.5,
- py = -cosTh * toY * 0.5 + sinTh * toX * 0.5,
- rx2 = rx * rx, ry2 = ry * ry, py2 = py * py, px2 = px * px,
- pl = rx2 * ry2 - rx2 * py2 - ry2 * px2,
- root = 0;
-
- if (pl < 0) {
- var s = Math.sqrt(1 - pl / (rx2 * ry2));
- rx *= s;
- ry *= s;
- }
- else {
- root = (large === sweep ? -1.0 : 1.0) *
- Math.sqrt( pl / (rx2 * py2 + ry2 * px2));
- }
-
- var cx = root * rx * py / ry,
- cy = -root * ry * px / rx,
- cx1 = cosTh * cx - sinTh * cy + toX * 0.5,
- cy1 = sinTh * cx + cosTh * cy + toY * 0.5,
- mTheta = calcVectorAngle(1, 0, (px - cx) / rx, (py - cy) / ry),
- dtheta = calcVectorAngle((px - cx) / rx, (py - cy) / ry, (-px - cx) / rx, (-py - cy) / ry);
-
- if (sweep === 0 && dtheta > 0) {
- dtheta -= 2 * PI;
- }
- else if (sweep === 1 && dtheta < 0) {
- dtheta += 2 * PI;
- }
-
- // Convert into cubic bezier segments <= 90deg
- var segments = Math.ceil(Math.abs(dtheta / PI * 2)),
- result = [], mDelta = dtheta / segments,
- mT = 8 / 3 * Math.sin(mDelta / 4) * Math.sin(mDelta / 4) / Math.sin(mDelta / 2),
- th3 = mTheta + mDelta;
-
- for (var i = 0; i < segments; i++) {
- result[i] = segmentToBezier(mTheta, th3, cosTh, sinTh, rx, ry, cx1, cy1, mT, fromX, fromY);
- fromX = result[i][4];
- fromY = result[i][5];
- mTheta = th3;
- th3 += mDelta;
- }
- fabric.arcToSegmentsCache[argsString] = result;
- return result;
- }
-
- function segmentToBezier(th2, th3, cosTh, sinTh, rx, ry, cx1, cy1, mT, fromX, fromY) {
- var costh2 = fabric.util.cos(th2),
- sinth2 = fabric.util.sin(th2),
- costh3 = fabric.util.cos(th3),
- sinth3 = fabric.util.sin(th3),
- toX = cosTh * rx * costh3 - sinTh * ry * sinth3 + cx1,
- toY = sinTh * rx * costh3 + cosTh * ry * sinth3 + cy1,
- cp1X = fromX + mT * ( -cosTh * rx * sinth2 - sinTh * ry * costh2),
- cp1Y = fromY + mT * ( -sinTh * rx * sinth2 + cosTh * ry * costh2),
- cp2X = toX + mT * ( cosTh * rx * sinth3 + sinTh * ry * costh3),
- cp2Y = toY + mT * ( sinTh * rx * sinth3 - cosTh * ry * costh3);
-
- return [
- cp1X, cp1Y,
- cp2X, cp2Y,
- toX, toY
- ];
- }
-
- /*
- * Private
- */
- function calcVectorAngle(ux, uy, vx, vy) {
- var ta = Math.atan2(uy, ux),
- tb = Math.atan2(vy, vx);
- if (tb >= ta) {
- return tb - ta;
- }
- else {
- return 2 * Math.PI - (ta - tb);
- }
- }
-
- /**
- * Draws arc
- * @param {CanvasRenderingContext2D} ctx
- * @param {Number} fx
- * @param {Number} fy
- * @param {Array} coords
- */
- fabric.util.drawArc = function(ctx, fx, fy, coords) {
- var rx = coords[0],
- ry = coords[1],
- rot = coords[2],
- large = coords[3],
- sweep = coords[4],
- tx = coords[5],
- ty = coords[6],
- segs = [[], [], [], []],
- segsNorm = arcToSegments(tx - fx, ty - fy, rx, ry, large, sweep, rot);
-
- for (var i = 0, len = segsNorm.length; i < len; i++) {
- segs[i][0] = segsNorm[i][0] + fx;
- segs[i][1] = segsNorm[i][1] + fy;
- segs[i][2] = segsNorm[i][2] + fx;
- segs[i][3] = segsNorm[i][3] + fy;
- segs[i][4] = segsNorm[i][4] + fx;
- segs[i][5] = segsNorm[i][5] + fy;
- ctx.bezierCurveTo.apply(ctx, segs[i]);
- }
- };
-
- /**
- * Calculate bounding box of a elliptic-arc
- * @param {Number} fx start point of arc
- * @param {Number} fy
- * @param {Number} rx horizontal radius
- * @param {Number} ry vertical radius
- * @param {Number} rot angle of horizontal axe
- * @param {Number} large 1 or 0, whatever the arc is the big or the small on the 2 points
- * @param {Number} sweep 1 or 0, 1 clockwise or counterclockwise direction
- * @param {Number} tx end point of arc
- * @param {Number} ty
- */
- fabric.util.getBoundsOfArc = function(fx, fy, rx, ry, rot, large, sweep, tx, ty) {
-
- var fromX = 0, fromY = 0, bound, bounds = [],
- segs = arcToSegments(tx - fx, ty - fy, rx, ry, large, sweep, rot);
-
- for (var i = 0, len = segs.length; i < len; i++) {
- bound = getBoundsOfCurve(fromX, fromY, segs[i][0], segs[i][1], segs[i][2], segs[i][3], segs[i][4], segs[i][5]);
- bounds.push({ x: bound[0].x + fx, y: bound[0].y + fy });
- bounds.push({ x: bound[1].x + fx, y: bound[1].y + fy });
- fromX = segs[i][4];
- fromY = segs[i][5];
- }
- return bounds;
- };
-
- /**
- * Calculate bounding box of a beziercurve
- * @param {Number} x0 starting point
- * @param {Number} y0
- * @param {Number} x1 first control point
- * @param {Number} y1
- * @param {Number} x2 secondo control point
- * @param {Number} y2
- * @param {Number} x3 end of beizer
- * @param {Number} y3
- */
- // taken from http://jsbin.com/ivomiq/56/edit no credits available for that.
- function getBoundsOfCurve(x0, y0, x1, y1, x2, y2, x3, y3) {
- var argsString;
- if (fabric.cachesBoundsOfCurve) {
- argsString = _join.call(arguments);
- if (fabric.boundsOfCurveCache[argsString]) {
- return fabric.boundsOfCurveCache[argsString];
- }
- }
-
- var sqrt = Math.sqrt,
- min = Math.min, max = Math.max,
- abs = Math.abs, tvalues = [],
- bounds = [[], []],
- a, b, c, t, t1, t2, b2ac, sqrtb2ac;
-
- b = 6 * x0 - 12 * x1 + 6 * x2;
- a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3;
- c = 3 * x1 - 3 * x0;
-
- for (var i = 0; i < 2; ++i) {
- if (i > 0) {
- b = 6 * y0 - 12 * y1 + 6 * y2;
- a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3;
- c = 3 * y1 - 3 * y0;
- }
-
- if (abs(a) < 1e-12) {
- if (abs(b) < 1e-12) {
- continue;
- }
- t = -c / b;
- if (0 < t && t < 1) {
- tvalues.push(t);
- }
- continue;
- }
- b2ac = b * b - 4 * c * a;
- if (b2ac < 0) {
- continue;
- }
- sqrtb2ac = sqrt(b2ac);
- t1 = (-b + sqrtb2ac) / (2 * a);
- if (0 < t1 && t1 < 1) {
- tvalues.push(t1);
- }
- t2 = (-b - sqrtb2ac) / (2 * a);
- if (0 < t2 && t2 < 1) {
- tvalues.push(t2);
- }
- }
-
- var x, y, j = tvalues.length, jlen = j, mt;
- while (j--) {
- t = tvalues[j];
- mt = 1 - t;
- x = (mt * mt * mt * x0) + (3 * mt * mt * t * x1) + (3 * mt * t * t * x2) + (t * t * t * x3);
- bounds[0][j] = x;
-
- y = (mt * mt * mt * y0) + (3 * mt * mt * t * y1) + (3 * mt * t * t * y2) + (t * t * t * y3);
- bounds[1][j] = y;
- }
-
- bounds[0][jlen] = x0;
- bounds[1][jlen] = y0;
- bounds[0][jlen + 1] = x3;
- bounds[1][jlen + 1] = y3;
- var result = [
- {
- x: min.apply(null, bounds[0]),
- y: min.apply(null, bounds[1])
- },
- {
- x: max.apply(null, bounds[0]),
- y: max.apply(null, bounds[1])
- }
- ];
- if (fabric.cachesBoundsOfCurve) {
- fabric.boundsOfCurveCache[argsString] = result;
- }
- return result;
- }
-
- fabric.util.getBoundsOfCurve = getBoundsOfCurve;
-
-})();
-
-
-(function() {
-
- var slice = Array.prototype.slice;
-
- /**
- * Invokes method on all items in a given array
- * @memberOf fabric.util.array
- * @param {Array} array Array to iterate over
- * @param {String} method Name of a method to invoke
- * @return {Array}
- */
- function invoke(array, method) {
- var args = slice.call(arguments, 2), result = [];
- for (var i = 0, len = array.length; i < len; i++) {
- result[i] = args.length ? array[i][method].apply(array[i], args) : array[i][method].call(array[i]);
- }
- return result;
- }
-
- /**
- * Finds maximum value in array (not necessarily "first" one)
- * @memberOf fabric.util.array
- * @param {Array} array Array to iterate over
- * @param {String} byProperty
- * @return {*}
- */
- function max(array, byProperty) {
- return find(array, byProperty, function(value1, value2) {
- return value1 >= value2;
- });
- }
-
- /**
- * Finds minimum value in array (not necessarily "first" one)
- * @memberOf fabric.util.array
- * @param {Array} array Array to iterate over
- * @param {String} byProperty
- * @return {*}
- */
- function min(array, byProperty) {
- return find(array, byProperty, function(value1, value2) {
- return value1 < value2;
- });
- }
-
- /**
- * @private
- */
- function fill(array, value) {
- var k = array.length;
- while (k--) {
- array[k] = value;
- }
- return array;
- }
-
- /**
- * @private
- */
- function find(array, byProperty, condition) {
- if (!array || array.length === 0) {
- return;
- }
-
- var i = array.length - 1,
- result = byProperty ? array[i][byProperty] : array[i];
- if (byProperty) {
- while (i--) {
- if (condition(array[i][byProperty], result)) {
- result = array[i][byProperty];
- }
- }
- }
- else {
- while (i--) {
- if (condition(array[i], result)) {
- result = array[i];
- }
- }
- }
- return result;
- }
-
- /**
- * @namespace fabric.util.array
- */
- fabric.util.array = {
- fill: fill,
- invoke: invoke,
- min: min,
- max: max
- };
-
-})();
-
-
-(function() {
- /**
- * Copies all enumerable properties of one js object to another
- * this does not and cannot compete with generic utils.
- * Does not clone or extend fabric.Object subclasses.
- * This is mostly for internal use and has extra handling for fabricJS objects
- * it skips the canvas property in deep cloning.
- * @memberOf fabric.util.object
- * @param {Object} destination Where to copy to
- * @param {Object} source Where to copy from
- * @return {Object}
- */
-
- function extend(destination, source, deep) {
- // JScript DontEnum bug is not taken care of
- // the deep clone is for internal use, is not meant to avoid
- // javascript traps or cloning html element or self referenced objects.
- if (deep) {
- if (!fabric.isLikelyNode && source instanceof Element) {
- // avoid cloning deep images, canvases,
- destination = source;
- }
- else if (source instanceof Array) {
- destination = [];
- for (var i = 0, len = source.length; i < len; i++) {
- destination[i] = extend({ }, source[i], deep);
- }
- }
- else if (source && typeof source === 'object') {
- for (var property in source) {
- if (property === 'canvas') {
- destination[property] = extend({ }, source[property]);
- }
- else if (source.hasOwnProperty(property)) {
- destination[property] = extend({ }, source[property], deep);
- }
- }
- }
- else {
- // this sounds odd for an extend but is ok for recursive use
- destination = source;
- }
- }
- else {
- for (var property in source) {
- destination[property] = source[property];
- }
- }
- return destination;
- }
-
- /**
- * Creates an empty object and copies all enumerable properties of another object to it
- * @memberOf fabric.util.object
- * TODO: this function return an empty object if you try to clone null
- * @param {Object} object Object to clone
- * @return {Object}
- */
- function clone(object, deep) {
- return extend({ }, object, deep);
- }
-
- /** @namespace fabric.util.object */
- fabric.util.object = {
- extend: extend,
- clone: clone
- };
- fabric.util.object.extend(fabric.util, fabric.Observable);
-})();
-
-
-(function() {
-
- /**
- * Camelizes a string
- * @memberOf fabric.util.string
- * @param {String} string String to camelize
- * @return {String} Camelized version of a string
- */
- function camelize(string) {
- return string.replace(/-+(.)?/g, function(match, character) {
- return character ? character.toUpperCase() : '';
- });
- }
-
- /**
- * Capitalizes a string
- * @memberOf fabric.util.string
- * @param {String} string String to capitalize
- * @param {Boolean} [firstLetterOnly] If true only first letter is capitalized
- * and other letters stay untouched, if false first letter is capitalized
- * and other letters are converted to lowercase.
- * @return {String} Capitalized version of a string
- */
- function capitalize(string, firstLetterOnly) {
- return string.charAt(0).toUpperCase() +
- (firstLetterOnly ? string.slice(1) : string.slice(1).toLowerCase());
- }
-
- /**
- * Escapes XML in a string
- * @memberOf fabric.util.string
- * @param {String} string String to escape
- * @return {String} Escaped version of a string
- */
- function escapeXml(string) {
- return string.replace(/&/g, '&')
- .replace(/"/g, '"')
- .replace(/'/g, ''')
- .replace(/</g, '<')
- .replace(/>/g, '>');
- }
-
- /**
- * Divide a string in the user perceived single units
- * @memberOf fabric.util.string
- * @param {String} textstring String to escape
- * @return {Array} array containing the graphemes
- */
- function graphemeSplit(textstring) {
- var i = 0, chr, graphemes = [];
- for (i = 0, chr; i < textstring.length; i++) {
- if ((chr = getWholeChar(textstring, i)) === false) {
- continue;
- }
- graphemes.push(chr);
- }
- return graphemes;
- }
-
- // taken from mdn in the charAt doc page.
- function getWholeChar(str, i) {
- var code = str.charCodeAt(i);
-
- if (isNaN(code)) {
- return ''; // Position not found
- }
- if (code < 0xD800 || code > 0xDFFF) {
- return str.charAt(i);
- }
-
- // High surrogate (could change last hex to 0xDB7F to treat high private
- // surrogates as single characters)
- if (0xD800 <= code && code <= 0xDBFF) {
- if (str.length <= (i + 1)) {
- throw 'High surrogate without following low surrogate';
- }
- var next = str.charCodeAt(i + 1);
- if (0xDC00 > next || next > 0xDFFF) {
- throw 'High surrogate without following low surrogate';
- }
- return str.charAt(i) + str.charAt(i + 1);
- }
- // Low surrogate (0xDC00 <= code && code <= 0xDFFF)
- if (i === 0) {
- throw 'Low surrogate without preceding high surrogate';
- }
- var prev = str.charCodeAt(i - 1);
-
- // (could change last hex to 0xDB7F to treat high private
- // surrogates as single characters)
- if (0xD800 > prev || prev > 0xDBFF) {
- throw 'Low surrogate without preceding high surrogate';
- }
- // We can pass over low surrogates now as the second component
- // in a pair which we have already processed
- return false;
- }
-
-
- /**
- * String utilities
- * @namespace fabric.util.string
- */
- fabric.util.string = {
- camelize: camelize,
- capitalize: capitalize,
- escapeXml: escapeXml,
- graphemeSplit: graphemeSplit
- };
-})();
-
-
-(function() {
-
- var slice = Array.prototype.slice, emptyFunction = function() { },
-
- IS_DONTENUM_BUGGY = (function() {
- for (var p in { toString: 1 }) {
- if (p === 'toString') {
- return false;
- }
- }
- return true;
- })(),
-
- /** @ignore */
- addMethods = function(klass, source, parent) {
- for (var property in source) {
-
- if (property in klass.prototype &&
- typeof klass.prototype[property] === 'function' &&
- (source[property] + '').indexOf('callSuper') > -1) {
-
- klass.prototype[property] = (function(property) {
- return function() {
-
- var superclass = this.constructor.superclass;
- this.constructor.superclass = parent;
- var returnValue = source[property].apply(this, arguments);
- this.constructor.superclass = superclass;
-
- if (property !== 'initialize') {
- return returnValue;
- }
- };
- })(property);
- }
- else {
- klass.prototype[property] = source[property];
- }
-
- if (IS_DONTENUM_BUGGY) {
- if (source.toString !== Object.prototype.toString) {
- klass.prototype.toString = source.toString;
- }
- if (source.valueOf !== Object.prototype.valueOf) {
- klass.prototype.valueOf = source.valueOf;
- }
- }
- }
- };
-
- function Subclass() { }
-
- function callSuper(methodName) {
- var parentMethod = null,
- _this = this;
-
- // climb prototype chain to find method not equal to callee's method
- while (_this.constructor.superclass) {
- var superClassMethod = _this.constructor.superclass.prototype[methodName];
- if (_this[methodName] !== superClassMethod) {
- parentMethod = superClassMethod;
- break;
- }
- // eslint-disable-next-line
- _this = _this.constructor.superclass.prototype;
- }
-
- if (!parentMethod) {
- return console.log('tried to callSuper ' + methodName + ', method not found in prototype chain', this);
- }
-
- return (arguments.length > 1)
- ? parentMethod.apply(this, slice.call(arguments, 1))
- : parentMethod.call(this);
- }
-
- /**
- * Helper for creation of "classes".
- * @memberOf fabric.util
- * @param {Function} [parent] optional "Class" to inherit from
- * @param {Object} [properties] Properties shared by all instances of this class
- * (be careful modifying objects defined here as this would affect all instances)
- */
- function createClass() {
- var parent = null,
- properties = slice.call(arguments, 0);
-
- if (typeof properties[0] === 'function') {
- parent = properties.shift();
- }
- function klass() {
- this.initialize.apply(this, arguments);
- }
-
- klass.superclass = parent;
- klass.subclasses = [];
-
- if (parent) {
- Subclass.prototype = parent.prototype;
- klass.prototype = new Subclass();
- parent.subclasses.push(klass);
- }
- for (var i = 0, length = properties.length; i < length; i++) {
- addMethods(klass, properties[i], parent);
- }
- if (!klass.prototype.initialize) {
- klass.prototype.initialize = emptyFunction;
- }
- klass.prototype.constructor = klass;
- klass.prototype.callSuper = callSuper;
- return klass;
- }
-
- fabric.util.createClass = createClass;
-})();
-
-
-(function () {
- // since ie10 or ie9 can use addEventListener but they do not support options, i need to check
- var couldUseAttachEvent = !!fabric.document.createElement('div').attachEvent;
- /**
- * Adds an event listener to an element
- * @function
- * @memberOf fabric.util
- * @param {HTMLElement} element
- * @param {String} eventName
- * @param {Function} handler
- */
- fabric.util.addListener = function(element, eventName, handler, options) {
- element && element.addEventListener(eventName, handler, couldUseAttachEvent ? false : options);
- };
-
- /**
- * Removes an event listener from an element
- * @function
- * @memberOf fabric.util
- * @param {HTMLElement} element
- * @param {String} eventName
- * @param {Function} handler
- */
- fabric.util.removeListener = function(element, eventName, handler, options) {
- element && element.removeEventListener(eventName, handler, couldUseAttachEvent ? false : options);
- };
-
- function getTouchInfo(event) {
- var touchProp = event.changedTouches;
- if (touchProp && touchProp[0]) {
- return touchProp[0];
- }
- return event;
- }
-
- fabric.util.getPointer = function(event) {
- var element = event.target,
- scroll = fabric.util.getScrollLeftTop(element),
- _evt = getTouchInfo(event);
- return {
- x: _evt.clientX + scroll.left,
- y: _evt.clientY + scroll.top
- };
- };
-})();
-
-
-(function () {
-
- /**
- * Cross-browser wrapper for setting element's style
- * @memberOf fabric.util
- * @param {HTMLElement} element
- * @param {Object} styles
- * @return {HTMLElement} Element that was passed as a first argument
- */
- function setStyle(element, styles) {
- var elementStyle = element.style;
- if (!elementStyle) {
- return element;
- }
- if (typeof styles === 'string') {
- element.style.cssText += ';' + styles;
- return styles.indexOf('opacity') > -1
- ? setOpacity(element, styles.match(/opacity:\s*(\d?\.?\d*)/)[1])
- : element;
- }
- for (var property in styles) {
- if (property === 'opacity') {
- setOpacity(element, styles[property]);
- }
- else {
- var normalizedProperty = (property === 'float' || property === 'cssFloat')
- ? (typeof elementStyle.styleFloat === 'undefined' ? 'cssFloat' : 'styleFloat')
- : property;
- elementStyle[normalizedProperty] = styles[property];
- }
- }
- return element;
- }
-
- var parseEl = fabric.document.createElement('div'),
- supportsOpacity = typeof parseEl.style.opacity === 'string',
- supportsFilters = typeof parseEl.style.filter === 'string',
- reOpacity = /alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,
-
- /** @ignore */
- setOpacity = function (element) { return element; };
-
- if (supportsOpacity) {
- /** @ignore */
- setOpacity = function(element, value) {
- element.style.opacity = value;
- return element;
- };
- }
- else if (supportsFilters) {
- /** @ignore */
- setOpacity = function(element, value) {
- var es = element.style;
- if (element.currentStyle && !element.currentStyle.hasLayout) {
- es.zoom = 1;
- }
- if (reOpacity.test(es.filter)) {
- value = value >= 0.9999 ? '' : ('alpha(opacity=' + (value * 100) + ')');
- es.filter = es.filter.replace(reOpacity, value);
- }
- else {
- es.filter += ' alpha(opacity=' + (value * 100) + ')';
- }
- return element;
- };
- }
-
- fabric.util.setStyle = setStyle;
-
-})();
-
-
-(function() {
-
- var _slice = Array.prototype.slice;
-
- /**
- * Takes id and returns an element with that id (if one exists in a document)
- * @memberOf fabric.util
- * @param {String|HTMLElement} id
- * @return {HTMLElement|null}
- */
- function getById(id) {
- return typeof id === 'string' ? fabric.document.getElementById(id) : id;
- }
-
- var sliceCanConvertNodelists,
- /**
- * Converts an array-like object (e.g. arguments or NodeList) to an array
- * @memberOf fabric.util
- * @param {Object} arrayLike
- * @return {Array}
- */
- toArray = function(arrayLike) {
- return _slice.call(arrayLike, 0);
- };
-
- try {
- sliceCanConvertNodelists = toArray(fabric.document.childNodes) instanceof Array;
- }
- catch (err) { }
-
- if (!sliceCanConvertNodelists) {
- toArray = function(arrayLike) {
- var arr = new Array(arrayLike.length), i = arrayLike.length;
- while (i--) {
- arr[i] = arrayLike[i];
- }
- return arr;
- };
- }
-
- /**
- * Creates specified element with specified attributes
- * @memberOf fabric.util
- * @param {String} tagName Type of an element to create
- * @param {Object} [attributes] Attributes to set on an element
- * @return {HTMLElement} Newly created element
- */
- function makeElement(tagName, attributes) {
- var el = fabric.document.createElement(tagName);
- for (var prop in attributes) {
- if (prop === 'class') {
- el.className = attributes[prop];
- }
- else if (prop === 'for') {
- el.htmlFor = attributes[prop];
- }
- else {
- el.setAttribute(prop, attributes[prop]);
- }
- }
- return el;
- }
-
- /**
- * Adds class to an element
- * @memberOf fabric.util
- * @param {HTMLElement} element Element to add class to
- * @param {String} className Class to add to an element
- */
- function addClass(element, className) {
- if (element && (' ' + element.className + ' ').indexOf(' ' + className + ' ') === -1) {
- element.className += (element.className ? ' ' : '') + className;
- }
- }
-
- /**
- * Wraps element with another element
- * @memberOf fabric.util
- * @param {HTMLElement} element Element to wrap
- * @param {HTMLElement|String} wrapper Element to wrap with
- * @param {Object} [attributes] Attributes to set on a wrapper
- * @return {HTMLElement} wrapper
- */
- function wrapElement(element, wrapper, attributes) {
- if (typeof wrapper === 'string') {
- wrapper = makeElement(wrapper, attributes);
- }
- if (element.parentNode) {
- element.parentNode.replaceChild(wrapper, element);
- }
- wrapper.appendChild(element);
- return wrapper;
- }
-
- /**
- * Returns element scroll offsets
- * @memberOf fabric.util
- * @param {HTMLElement} element Element to operate on
- * @return {Object} Object with left/top values
- */
- function getScrollLeftTop(element) {
-
- var left = 0,
- top = 0,
- docElement = fabric.document.documentElement,
- body = fabric.document.body || {
- scrollLeft: 0, scrollTop: 0
- };
-
- // While loop checks (and then sets element to) .parentNode OR .host
- // to account for ShadowDOM. We still want to traverse up out of ShadowDOM,
- // but the .parentNode of a root ShadowDOM node will always be null, instead
- // it should be accessed through .host. See http://stackoverflow.com/a/24765528/4383938
- while (element && (element.parentNode || element.host)) {
-
- // Set element to element parent, or 'host' in case of ShadowDOM
- element = element.parentNode || element.host;
-
- if (element === fabric.document) {
- left = body.scrollLeft || docElement.scrollLeft || 0;
- top = body.scrollTop || docElement.scrollTop || 0;
- }
- else {
- left += element.scrollLeft || 0;
- top += element.scrollTop || 0;
- }
-
- if (element.nodeType === 1 && element.style.position === 'fixed') {
- break;
- }
- }
-
- return { left: left, top: top };
- }
-
- /**
- * Returns offset for a given element
- * @function
- * @memberOf fabric.util
- * @param {HTMLElement} element Element to get offset for
- * @return {Object} Object with "left" and "top" properties
- */
- function getElementOffset(element) {
- var docElem,
- doc = element && element.ownerDocument,
- box = { left: 0, top: 0 },
- offset = { left: 0, top: 0 },
- scrollLeftTop,
- offsetAttributes = {
- borderLeftWidth: 'left',
- borderTopWidth: 'top',
- paddingLeft: 'left',
- paddingTop: 'top'
- };
-
- if (!doc) {
- return offset;
- }
-
- for (var attr in offsetAttributes) {
- offset[offsetAttributes[attr]] += parseInt(getElementStyle(element, attr), 10) || 0;
- }
-
- docElem = doc.documentElement;
- if ( typeof element.getBoundingClientRect !== 'undefined' ) {
- box = element.getBoundingClientRect();
- }
-
- scrollLeftTop = getScrollLeftTop(element);
-
- return {
- left: box.left + scrollLeftTop.left - (docElem.clientLeft || 0) + offset.left,
- top: box.top + scrollLeftTop.top - (docElem.clientTop || 0) + offset.top
- };
- }
-
- /**
- * Returns style attribute value of a given element
- * @memberOf fabric.util
- * @param {HTMLElement} element Element to get style attribute for
- * @param {String} attr Style attribute to get for element
- * @return {String} Style attribute value of the given element.
- */
- var getElementStyle;
- if (fabric.document.defaultView && fabric.document.defaultView.getComputedStyle) {
- getElementStyle = function(element, attr) {
- var style = fabric.document.defaultView.getComputedStyle(element, null);
- return style ? style[attr] : undefined;
- };
- }
- else {
- getElementStyle = function(element, attr) {
- var value = element.style[attr];
- if (!value && element.currentStyle) {
- value = element.currentStyle[attr];
- }
- return value;
- };
- }
-
- (function () {
- var style = fabric.document.documentElement.style,
- selectProp = 'userSelect' in style
- ? 'userSelect'
- : 'MozUserSelect' in style
- ? 'MozUserSelect'
- : 'WebkitUserSelect' in style
- ? 'WebkitUserSelect'
- : 'KhtmlUserSelect' in style
- ? 'KhtmlUserSelect'
- : '';
-
- /**
- * Makes element unselectable
- * @memberOf fabric.util
- * @param {HTMLElement} element Element to make unselectable
- * @return {HTMLElement} Element that was passed in
- */
- function makeElementUnselectable(element) {
- if (typeof element.onselectstart !== 'undefined') {
- element.onselectstart = fabric.util.falseFunction;
- }
- if (selectProp) {
- element.style[selectProp] = 'none';
- }
- else if (typeof element.unselectable === 'string') {
- element.unselectable = 'on';
- }
- return element;
- }
-
- /**
- * Makes element selectable
- * @memberOf fabric.util
- * @param {HTMLElement} element Element to make selectable
- * @return {HTMLElement} Element that was passed in
- */
- function makeElementSelectable(element) {
- if (typeof element.onselectstart !== 'undefined') {
- element.onselectstart = null;
- }
- if (selectProp) {
- element.style[selectProp] = '';
- }
- else if (typeof element.unselectable === 'string') {
- element.unselectable = '';
- }
- return element;
- }
-
- fabric.util.makeElementUnselectable = makeElementUnselectable;
- fabric.util.makeElementSelectable = makeElementSelectable;
- })();
-
- (function() {
-
- /**
- * Inserts a script element with a given url into a document; invokes callback, when that script is finished loading
- * @memberOf fabric.util
- * @param {String} url URL of a script to load
- * @param {Function} callback Callback to execute when script is finished loading
- */
- function getScript(url, callback) {
- var headEl = fabric.document.getElementsByTagName('head')[0],
- scriptEl = fabric.document.createElement('script'),
- loading = true;
-
- /** @ignore */
- scriptEl.onload = /** @ignore */ scriptEl.onreadystatechange = function(e) {
- if (loading) {
- if (typeof this.readyState === 'string' &&
- this.readyState !== 'loaded' &&
- this.readyState !== 'complete') {
- return;
- }
- loading = false;
- callback(e || fabric.window.event);
- scriptEl = scriptEl.onload = scriptEl.onreadystatechange = null;
- }
- };
- scriptEl.src = url;
- headEl.appendChild(scriptEl);
- // causes issue in Opera
- // headEl.removeChild(scriptEl);
- }
-
- fabric.util.getScript = getScript;
- })();
-
- function getNodeCanvas(element) {
- var impl = fabric.jsdomImplForWrapper(element);
- return impl._canvas || impl._image;
- };
-
- function cleanUpJsdomNode(element) {
- if (!fabric.isLikelyNode) {
- return;
- }
- var impl = fabric.jsdomImplForWrapper(element);
- if (impl) {
- impl._image = null;
- impl._canvas = null;
- // unsure if necessary
- impl._currentSrc = null;
- impl._attributes = null;
- impl._classList = null;
- }
- }
-
- fabric.util.getById = getById;
- fabric.util.toArray = toArray;
- fabric.util.makeElement = makeElement;
- fabric.util.addClass = addClass;
- fabric.util.wrapElement = wrapElement;
- fabric.util.getScrollLeftTop = getScrollLeftTop;
- fabric.util.getElementOffset = getElementOffset;
- fabric.util.getElementStyle = getElementStyle;
- fabric.util.getNodeCanvas = getNodeCanvas;
- fabric.util.cleanUpJsdomNode = cleanUpJsdomNode;
-
-})();
-
-
-(function() {
-
- function addParamToUrl(url, param) {
- return url + (/\?/.test(url) ? '&' : '?') + param;
- }
-
- function emptyFn() { }
-
- /**
- * Cross-browser abstraction for sending XMLHttpRequest
- * @memberOf fabric.util
- * @param {String} url URL to send XMLHttpRequest to
- * @param {Object} [options] Options object
- * @param {String} [options.method="GET"]
- * @param {String} [options.parameters] parameters to append to url in GET or in body
- * @param {String} [options.body] body to send with POST or PUT request
- * @param {Function} options.onComplete Callback to invoke when request is completed
- * @return {XMLHttpRequest} request
- */
- function request(url, options) {
- options || (options = { });
-
- var method = options.method ? options.method.toUpperCase() : 'GET',
- onComplete = options.onComplete || function() { },
- xhr = new fabric.window.XMLHttpRequest(),
- body = options.body || options.parameters;
-
- /** @ignore */
- xhr.onreadystatechange = function() {
- if (xhr.readyState === 4) {
- onComplete(xhr);
- xhr.onreadystatechange = emptyFn;
- }
- };
-
- if (method === 'GET') {
- body = null;
- if (typeof options.parameters === 'string') {
- url = addParamToUrl(url, options.parameters);
- }
- }
-
- xhr.open(method, url, true);
-
- if (method === 'POST' || method === 'PUT') {
- xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
- }
-
- xhr.send(body);
- return xhr;
- }
-
- fabric.util.request = request;
-})();
-
-
-/**
- * Wrapper around `console.log` (when available)
- * @param {*} [values] Values to log
- */
-fabric.log = console.log;
-
-/**
- * Wrapper around `console.warn` (when available)
- * @param {*} [values] Values to log as a warning
- */
-fabric.warn = console.warn;
-
-
-(function() {
-
- function noop() {
- return false;
- }
-
- function defaultEasing(t, b, c, d) {
- return -c * Math.cos(t / d * (Math.PI / 2)) + c + b;
- }
-
- /**
- * Changes value from one to another within certain period of time, invoking callbacks as value is being changed.
- * @memberOf fabric.util
- * @param {Object} [options] Animation options
- * @param {Function} [options.onChange] Callback; invoked on every value change
- * @param {Function} [options.onComplete] Callback; invoked when value change is completed
- * @param {Number} [options.startValue=0] Starting value
- * @param {Number} [options.endValue=100] Ending value
- * @param {Number} [options.byValue=100] Value to modify the property by
- * @param {Function} [options.easing] Easing function
- * @param {Number} [options.duration=500] Duration of change (in ms)
- * @param {Function} [options.abort] Additional function with logic. If returns true, onComplete is called.
- */
- function animate(options) {
-
- requestAnimFrame(function(timestamp) {
- options || (options = { });
-
- var start = timestamp || +new Date(),
- duration = options.duration || 500,
- finish = start + duration, time,
- onChange = options.onChange || noop,
- abort = options.abort || noop,
- onComplete = options.onComplete || noop,
- easing = options.easing || defaultEasing,
- startValue = 'startValue' in options ? options.startValue : 0,
- endValue = 'endValue' in options ? options.endValue : 100,
- byValue = options.byValue || endValue - startValue;
-
- options.onStart && options.onStart();
-
- (function tick(ticktime) {
- // TODO: move abort call after calculation
- // and pass (current,valuePerc, timePerc) as arguments
- time = ticktime || +new Date();
- var currentTime = time > finish ? duration : (time - start),
- timePerc = currentTime / duration,
- current = easing(currentTime, startValue, byValue, duration),
- valuePerc = Math.abs((current - startValue) / byValue);
- if (abort()) {
- onComplete(endValue, 1, 1);
- return;
- }
- if (time > finish) {
- onChange(endValue, 1, 1);
- onComplete(endValue, 1, 1);
- return;
- }
- else {
- onChange(current, valuePerc, timePerc);
- requestAnimFrame(tick);
- }
- })(start);
- });
- }
-
- var _requestAnimFrame = fabric.window.requestAnimationFrame ||
- fabric.window.webkitRequestAnimationFrame ||
- fabric.window.mozRequestAnimationFrame ||
- fabric.window.oRequestAnimationFrame ||
- fabric.window.msRequestAnimationFrame ||
- function(callback) {
- return fabric.window.setTimeout(callback, 1000 / 60);
- };
-
- var _cancelAnimFrame = fabric.window.cancelAnimationFrame || fabric.window.clearTimeout;
-
- /**
- * requestAnimationFrame polyfill based on http://paulirish.com/2011/requestanimationframe-for-smart-animating/
- * In order to get a precise start time, `requestAnimFrame` should be called as an entry into the method
- * @memberOf fabric.util
- * @param {Function} callback Callback to invoke
- * @param {DOMElement} element optional Element to associate with animation
- */
- function requestAnimFrame() {
- return _requestAnimFrame.apply(fabric.window, arguments);
- }
-
- function cancelAnimFrame() {
- return _cancelAnimFrame.apply(fabric.window, arguments);
- }
-
- fabric.util.animate = animate;
- fabric.util.requestAnimFrame = requestAnimFrame;
- fabric.util.cancelAnimFrame = cancelAnimFrame;
-})();
-
-
-(function() {
- // Calculate an in-between color. Returns a "rgba()" string.
- // Credit: Edwin Martin <ed...@bitstorm.org>
- // http://www.bitstorm.org/jquery/color-animation/jquery.animate-colors.js
- function calculateColor(begin, end, pos) {
- var color = 'rgba('
- + parseInt((begin[0] + pos * (end[0] - begin[0])), 10) + ','
- + parseInt((begin[1] + pos * (end[1] - begin[1])), 10) + ','
- + parseInt((begin[2] + pos * (end[2] - begin[2])), 10);
-
- color += ',' + (begin && end ? parseFloat(begin[3] + pos * (end[3] - begin[3])) : 1);
- color += ')';
- return color;
- }
-
- /**
- * Changes the color from one to another within certain period of time, invoking callbacks as value is being changed.
- * @memberOf fabric.util
- * @param {String} fromColor The starting color in hex or rgb(a) format.
- * @param {String} toColor The starting color in hex or rgb(a) format.
- * @param {Number} [duration] Duration of change (in ms).
- * @param {Object} [options] Animation options
- * @param {Function} [options.onChange] Callback; invoked on every value change
- * @param {Function} [options.onComplete] Callback; invoked when value change is completed
- * @param {Function} [options.colorEasing] Easing function. Note that this function only take two arguments (currentTime, duration). Thus the regular animation easing functions cannot be used.
- * @param {Function} [options.abort] Additional function with logic. If returns true, onComplete is called.
- */
- function animateColor(fromColor, toColor, duration, options) {
- var startColor = new fabric.Color(fromColor).getSource(),
- endColor = new fabric.Color(toColor).getSource();
-
- options = options || {};
-
- fabric.util.animate(fabric.util.object.extend(options, {
- duration: duration || 500,
- startValue: startColor,
- endValue: endColor,
- byValue: endColor,
- easing: function (currentTime, startValue, byValue, duration) {
- var posValue = options.colorEasing
- ? options.colorEasing(currentTime, duration)
- : 1 - Math.cos(currentTime / duration * (Math.PI / 2));
- return calculateColor(startValue, byValue, posValue);
- }
- }));
- }
-
- fabric.util.animateColor = animateColor;
-
-})();
-
-
-(function() {
-
- function normalize(a, c, p, s) {
- if (a < Math.abs(c)) {
- a = c;
- s = p / 4;
- }
- else {
- //handle the 0/0 case:
- if (c === 0 && a === 0) {
- s = p / (2 * Math.PI) * Math.asin(1);
- }
- else {
- s = p / (2 * Math.PI) * Math.asin(c / a);
- }
- }
- return { a: a, c: c, p: p, s: s };
- }
-
- function elastic(opts, t, d) {
- return opts.a *
- Math.pow(2, 10 * (t -= 1)) *
- Math.sin( (t * d - opts.s) * (2 * Math.PI) / opts.p );
- }
-
- /**
- * Cubic easing out
- * @memberOf fabric.util.ease
- */
- function easeOutCubic(t, b, c, d) {
- return c * ((t = t / d - 1) * t * t + 1) + b;
- }
-
- /**
- * Cubic easing in and out
- * @memberOf fabric.util.ease
- */
- function easeInOutCubic(t, b, c, d) {
- t /= d / 2;
- if (t < 1) {
- return c / 2 * t * t * t + b;
- }
- return c / 2 * ((t -= 2) * t * t + 2) + b;
- }
-
- /**
- * Quartic easing in
- * @memberOf fabric.util.ease
- */
- function easeInQuart(t, b, c, d) {
- return c * (t /= d) * t * t * t + b;
- }
-
- /**
- * Quartic easing out
- * @memberOf fabric.util.ease
- */
- function easeOutQuart(t, b, c, d) {
- return -c * ((t = t / d - 1) * t * t * t - 1) + b;
- }
-
- /**
- * Quartic easing in and out
- * @memberOf fabric.util.ease
- */
- function easeInOutQuart(t, b, c, d) {
- t /= d / 2;
- if (t < 1) {
- return c / 2 * t * t * t * t + b;
- }
- return -c / 2 * ((t -= 2) * t * t * t - 2) + b;
- }
-
- /**
- * Quintic easing in
- * @memberOf fabric.util.ease
- */
- function easeInQuint(t, b, c, d) {
- return c * (t /= d) * t * t * t * t + b;
- }
-
- /**
- * Quintic easing out
- * @memberOf fabric.util.ease
- */
- function easeOutQuint(t, b, c, d) {
- return c * ((t = t / d - 1) * t * t * t * t + 1) + b;
- }
-
- /**
- * Quintic easing in and out
- * @memberOf fabric.util.ease
- */
- function easeInOutQuint(t, b, c, d) {
- t /= d / 2;
- if (t < 1) {
- return c / 2 * t * t * t * t * t + b;
- }
- return c / 2 * ((t -= 2) * t * t * t * t + 2) + b;
- }
-
- /**
- * Sinusoidal easing in
- * @memberOf fabric.util.ease
- */
- function easeInSine(t, b, c, d) {
- return -c * Math.cos(t / d * (Math.PI / 2)) + c + b;
- }
-
- /**
- * Sinusoidal easing out
- * @memberOf fabric.util.ease
- */
- function easeOutSine(t, b, c, d) {
- return c * Math.sin(t / d * (Math.PI / 2)) + b;
- }
-
- /**
- * Sinusoidal easing in and out
- * @memberOf fabric.util.ease
- */
- function easeInOutSine(t, b, c, d) {
- return -c / 2 * (Math.cos(Math.PI * t / d) - 1) + b;
- }
-
- /**
- * Exponential easing in
- * @memberOf fabric.util.ease
- */
- function easeInExpo(t, b, c, d) {
- return (t === 0) ? b : c * Math.pow(2, 10 * (t / d - 1)) + b;
- }
-
- /**
- * Exponential easing out
- * @memberOf fabric.util.ease
- */
- function easeOutExpo(t, b, c, d) {
- return (t === d) ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b;
- }
-
- /**
- * Exponential easing in and out
- * @memberOf fabric.util.ease
- */
- function easeInOutExpo(t, b, c, d) {
- if (t === 0) {
- return b;
- }
- if (t === d) {
- return b + c;
- }
- t /= d / 2;
- if (t < 1) {
- return c / 2 * Math.pow(2, 10 * (t - 1)) + b;
- }
- return c / 2 * (-Math.pow(2, -10 * --t) + 2) + b;
- }
-
- /**
- * Circular easing in
- * @memberOf fabric.util.ease
- */
- function easeInCirc(t, b, c, d) {
- return -c * (Math.sqrt(1 - (t /= d) * t) - 1) + b;
- }
-
- /**
- * Circular easing out
- * @memberOf fabric.util.ease
- */
- function easeOutCirc(t, b, c, d) {
- return c * Math.sqrt(1 - (t = t / d - 1) * t) + b;
- }
-
- /**
- * Circular easing in and out
- * @memberOf fabric.util.ease
- */
- function easeInOutCirc(t, b, c, d) {
- t /= d / 2;
- if (t < 1) {
- return -c / 2 * (Math.sqrt(1 - t * t) - 1) + b;
- }
- return c / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1) + b;
- }
-
- /**
- * Elastic easing in
- * @memberOf fabric.util.ease
- */
- function easeInElastic(t, b, c, d) {
- var s = 1.70158, p = 0, a = c;
- if (t === 0) {
- return b;
- }
- t /= d;
- if (t === 1) {
- return b + c;
- }
- if (!p) {
- p = d * 0.3;
- }
- var opts = normalize(a, c, p, s);
- return -elastic(opts, t, d) + b;
- }
-
- /**
- * Elastic easing out
- * @memberOf fabric.util.ease
- */
- function easeOutElastic(t, b, c, d) {
- var s = 1.70158, p = 0, a = c;
- if (t === 0) {
- return b;
- }
- t /= d;
- if (t === 1) {
- return b + c;
- }
- if (!p) {
- p = d * 0.3;
- }
- var opts = normalize(a, c, p, s);
- return opts.a * Math.pow(2, -10 * t) * Math.sin((t * d - opts.s) * (2 * Math.PI) / opts.p ) + opts.c + b;
- }
-
- /**
- * Elastic easing in and out
- * @memberOf fabric.util.ease
- */
- function easeInOutElastic(t, b, c, d) {
- var s = 1.70158, p = 0, a = c;
- if (t === 0) {
- return b;
- }
- t /= d / 2;
- if (t === 2) {
- return b + c;
- }
- if (!p) {
- p = d * (0.3 * 1.5);
- }
- var opts = normalize(a, c, p, s);
- if (t < 1) {
- return -0.5 * elastic(opts, t, d) + b;
- }
- return opts.a * Math.pow(2, -10 * (t -= 1)) *
- Math.sin((t * d - opts.s) * (2 * Math.PI) / opts.p ) * 0.5 + opts.c + b;
- }
-
- /**
- * Backwards easing in
- * @memberOf fabric.util.ease
- */
- function easeInBack(t, b, c, d, s) {
- if (s === undefined) {
- s = 1.70158;
- }
- return c * (t /= d) * t * ((s + 1) * t - s) + b;
- }
-
- /**
- * Backwards easing out
- * @memberOf fabric.util.ease
- */
- function easeOutBack(t, b, c, d, s) {
- if (s === undefined) {
- s = 1.70158;
- }
- return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
- }
-
- /**
- * Backwards easing in and out
- * @memberOf fabric.util.ease
- */
- function easeInOutBack(t, b, c, d, s) {
- if (s === undefined) {
- s = 1.70158;
- }
- t /= d / 2;
- if (t < 1) {
- return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b;
- }
- return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
- }
-
- /**
- * Bouncing easing in
- * @memberOf fabric.util.ease
- */
- function easeInBounce(t, b, c, d) {
- return c - easeOutBounce (d - t, 0, c, d) + b;
- }
-
- /**
- * Bouncing easing out
- * @memberOf fabric.util.ease
- */
- function easeOutBounce(t, b, c, d) {
- if ((t /= d) < (1 / 2.75)) {
- return c * (7.5625 * t * t) + b;
- }
- else if (t < (2 / 2.75)) {
- return c * (7.5625 * (t -= (1.5 / 2.75)) * t + 0.75) + b;
- }
- else if (t < (2.5 / 2.75)) {
- return c * (7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375) + b;
- }
- else {
- return c * (7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375) + b;
- }
- }
-
- /**
- * Bouncing easing in and out
- * @memberOf fabric.util.ease
- */
- function easeInOutBounce(t, b, c, d) {
- if (t < d / 2) {
- return easeInBounce (t * 2, 0, c, d) * 0.5 + b;
- }
- return easeOutBounce(t * 2 - d, 0, c, d) * 0.5 + c * 0.5 + b;
- }
-
- /**
- * Easing functions
- * See <a href="http://gizma.com/easing/">Easing Equations by Robert Penner</a>
- * @namespace fabric.util.ease
- */
- fabric.util.ease = {
-
- /**
- * Quadratic easing in
- * @memberOf fabric.util.ease
- */
- easeInQuad: function(t, b, c, d) {
- return c * (t /= d) * t + b;
- },
-
- /**
- * Quadratic easing out
- * @memberOf fabric.util.ease
- */
- easeOutQuad: function(t, b, c, d) {
- return -c * (t /= d) * (t - 2) + b;
- },
-
- /**
- * Quadratic easing in and out
- * @memberOf fabric.util.ease
- */
- easeInOutQuad: function(t, b, c, d) {
- t /= (d / 2);
- if (t < 1) {
- return c / 2 * t * t + b;
- }
- return -c / 2 * ((--t) * (t - 2) - 1) + b;
- },
-
- /**
- * Cubic easing in
- * @memberOf fabric.util.ease
- */
- easeInCubic: function(t, b, c, d) {
- return c * (t /= d) * t * t + b;
- },
-
- easeOutCubic: easeOutCubic,
- easeInOutCubic: easeInOutCubic,
- easeInQuart: easeInQuart,
- easeOutQuart: easeOutQuart,
- easeInOutQuart: easeInOutQuart,
- easeInQuint: easeInQuint,
- easeOutQuint: easeOutQuint,
- easeInOutQuint: easeInOutQuint,
- easeInSine: easeInSine,
- easeOutSine: easeOutSine,
- easeInOutSine: easeInOutSine,
- easeInExpo: easeInExpo,
- easeOutExpo: easeOutExpo,
- easeInOutExpo: easeInOutExpo,
- easeInCirc: easeInCirc,
- easeOutCirc: easeOutCirc,
- easeInOutCirc: easeInOutCirc,
- easeInElastic: easeInElastic,
- easeOutElastic: easeOutElastic,
- easeInOutElastic: easeInOutElastic,
- easeInBack: easeInBack,
- easeOutBack: easeOutBack,
- easeInOutBack: easeInOutBack,
- easeInBounce: easeInBounce,
- easeOutBounce: easeOutBounce,
- easeInOutBounce: easeInOutBounce
- };
-
-})();
-
-
-(function(global) {
-
- 'use strict';
-
- /**
- * @name fabric
- * @namespace
- */
-
- var fabric = global.fabric || (global.fabric = { }),
- extend = fabric.util.object.extend,
- clone = fabric.util.object.clone,
- toFixed = fabric.util.toFixed,
- parseUnit = fabric.util.parseUnit,
- multiplyTransformMatrices = fabric.util.multiplyTransformMatrices,
-
- svgValidTagNames = ['path', 'circle', 'polygon', 'polyline', 'ellipse', 'rect', 'line',
- 'image', 'text'],
- svgViewBoxElements = ['symbol', 'image', 'marker', 'pattern', 'view', 'svg'],
- svgInvalidAncestors = ['pattern', 'defs', 'symbol', 'metadata', 'clipPath', 'mask', 'desc'],
- svgValidParents = ['symbol', 'g', 'a', 'svg', 'clipPath', 'defs'],
-
- attributesMap = {
- cx: 'left',
- x: 'left',
- r: 'radius',
- cy: 'top',
- y: 'top',
- display: 'visible',
- visibility: 'visible',
- transform: 'transformMatrix',
- 'fill-opacity': 'fillOpacity',
- 'fill-rule': 'fillRule',
- 'font-family': 'fontFamily',
- 'font-size': 'fontSize',
- 'font-style': 'fontStyle',
- 'font-weight': 'fontWeight',
- 'letter-spacing': 'charSpacing',
- 'paint-order': 'paintFirst',
- 'stroke-dasharray': 'strokeDashArray',
- 'stroke-dashoffset': 'strokeDashOffset',
- 'stroke-linecap': 'strokeLineCap',
- 'stroke-linejoin': 'strokeLineJoin',
- 'stroke-miterlimit': 'strokeMiterLimit',
- 'stroke-opacity': 'strokeOpacity',
- 'stroke-width': 'strokeWidth',
- 'text-decoration': 'textDecoration',
- 'text-anchor': 'textAnchor',
- opacity: 'opacity',
- 'clip-path': 'clipPath',
- 'clip-rule': 'clipRule',
- 'vector-effect': 'strokeUniform'
- },
-
- colorAttributes = {
- stroke: 'strokeOpacity',
- fill: 'fillOpacity'
- },
-
- fSize = 'font-size', cPath = 'clip-path';
-
- fabric.svgValidTagNamesRegEx = getSvgRegex(svgValidTagNames);
- fabric.svgViewBoxElementsRegEx = getSvgRegex(svgViewBoxElements);
- fabric.svgInvalidAncestorsRegEx = getSvgRegex(svgInvalidAncestors);
- fabric.svgValidParentsRegEx = getSvgRegex(svgValidParents);
-
- fabric.cssRules = { };
- fabric.gradientDefs = { };
- fabric.clipPaths = { };
-
- function normalizeAttr(attr) {
- // transform attribute names
- if (attr in attributesMap) {
- return attributesMap[attr];
- }
- return attr;
- }
-
- function normalizeValue(attr, value, parentAttributes, fontSize) {
- var isArray = Object.prototype.toString.call(value) === '[object Array]',
- parsed;
-
- if ((attr === 'fill' || attr === 'stroke') && value === 'none') {
- value = '';
- }
- else if (attr === 'vector-effect') {
- value = value === 'non-scaling-stroke';
- }
- else if (attr === 'strokeDashArray') {
- if (value === 'none') {
- value = null;
- }
- else {
- value = value.replace(/,/g, ' ').split(/\s+/).map(parseFloat);
- }
- }
- else if (attr === 'transformMatrix') {
- if (parentAttributes && parentAttributes.transformMatrix) {
- value = multiplyTransformMatrices(
- parentAttributes.transformMatrix, fabric.parseTransformAttribute(value));
- }
- else {
- value = fabric.parseTransformAttribute(value);
- }
- }
- else if (attr === 'visible') {
- value = value !== 'none' && value !== 'hidden';
- // display=none on parent element always takes precedence over child element
- if (parentAttributes && parentAttributes.visible === false) {
- value = false;
- }
- }
- else if (attr === 'opacity') {
- value = parseFloat(value);
- if (parentAttributes && typeof parentAttributes.opacity !== 'undefined') {
- value *= parentAttributes.opacity;
- }
- }
- else if (attr === 'textAnchor' /* text-anchor */) {
- value = value === 'start' ? 'left' : value === 'end' ? 'right' : 'center';
- }
- else if (attr === 'charSpacing') {
- // parseUnit returns px and we convert it to em
- parsed = parseUnit(value, fontSize) / fontSize * 1000;
- }
- else if (attr === 'paintFirst') {
- var fillIndex = value.indexOf('fill');
- var strokeIndex = value.indexOf('stroke');
- var value = 'fill';
- if (fillIndex > -1 && strokeIndex > -1 && strokeIndex < fillIndex) {
- value = 'stroke';
- }
- else if (fillIndex === -1 && strokeIndex > -1) {
- value = 'stroke';
- }
- }
- else if (attr === 'href' || attr === 'xlink:href') {
- return value;
- }
- else {
- parsed = isArray ? value.map(parseUnit) : parseUnit(value, fontSize);
- }
-
- return (!isArray && isNaN(parsed) ? value : parsed);
- }
-
- /**
- * @private
- */
- function getSvgRegex(arr) {
- return new RegExp('^(' + arr.join('|') + ')\\b', 'i');
- }
-
- /**
- * @private
- * @param {Object} attributes Array of attributes to parse
- */
- function _setStrokeFillOpacity(attributes) {
- for (var attr in colorAttributes) {
-
- if (typeof attributes[colorAttributes[attr]] === 'undefined' || attributes[attr] === '') {
- continue;
- }
-
- if (typeof attributes[attr] === 'undefined') {
- if (!fabric.Object.prototype[attr]) {
- continue;
- }
- attributes[attr] = fabric.Object.prototype[attr];
- }
-
- if (attributes[attr].indexOf('url(') === 0) {
- continue;
- }
-
- var color = new fabric.Color(attributes[attr]);
- attributes[attr] = color.setAlpha(toFixed(color.getAlpha() * attributes[colorAttributes[attr]], 2)).toRgba();
- }
- return attributes;
- }
-
- /**
- * @private
- */
- function _getMultipleNodes(doc, nodeNames) {
- var nodeName, nodeArray = [], nodeList, i, len;
- for (i = 0, len = nodeNames.length; i < len; i++) {
- nodeName = nodeNames[i];
- nodeList = doc.getElementsByTagName(nodeName);
- nodeArray = nodeArray.concat(Array.prototype.slice.call(nodeList));
- }
- return nodeArray;
- }
-
- /**
- * Parses "transform" attribute, returning an array of values
- * @static
- * @function
- * @memberOf fabric
- * @param {String} attributeValue String containing attribute value
- * @return {Array} Array of 6 elements representing transformation matrix
- */
- fabric.parseTransformAttribute = (function() {
- function rotateMatrix(matrix, args) {
- var cos = fabric.util.cos(args[0]), sin = fabric.util.sin(args[0]),
- x = 0, y = 0;
- if (args.length === 3) {
- x = args[1];
- y = args[2];
- }
-
- matrix[0] = cos;
- matrix[1] = sin;
- matrix[2] = -sin;
- matrix[3] = cos;
- matrix[4] = x - (cos * x - sin * y);
- matrix[5] = y - (sin * x + cos * y);
- }
-
- function scaleMatrix(matrix, args) {
- var multiplierX = args[0],
- multiplierY = (args.length === 2) ? args[1] : args[0];
-
- matrix[0] = multiplierX;
- matrix[3] = multiplierY;
- }
-
- function skewMatrix(matrix, args, pos) {
- matrix[pos] = Math.tan(fabric.util.degreesToRadians(args[0]));
- }
-
- function translateMatrix(matrix, args) {
- matrix[4] = args[0];
- if (args.length === 2) {
- matrix[5] = args[1];
- }
- }
-
- // identity matrix
- var iMatrix = fabric.iMatrix,
-
- // == begin transform regexp
- number = fabric.reNum,
-
- commaWsp = '(?:\\s+,?\\s*|,\\s*)',
-
- skewX = '(?:(skewX)\\s*\\(\\s*(' + number + ')\\s*\\))',
-
- skewY = '(?:(skewY)\\s*\\(\\s*(' + number + ')\\s*\\))',
-
- rotate = '(?:(rotate)\\s*\\(\\s*(' + number + ')(?:' +
- commaWsp + '(' + number + ')' +
- commaWsp + '(' + number + '))?\\s*\\))',
-
- scale = '(?:(scale)\\s*\\(\\s*(' + number + ')(?:' +
- commaWsp + '(' + number + '))?\\s*\\))',
-
- translate = '(?:(translate)\\s*\\(\\s*(' + number + ')(?:' +
- commaWsp + '(' + number + '))?\\s*\\))',
-
- matrix = '(?:(matrix)\\s*\\(\\s*' +
- '(' + number + ')' + commaWsp +
- '(' + number + ')' + commaWsp +
- '(' + number + ')' + commaWsp +
- '(' + number + ')' + commaWsp +
- '(' + number + ')' + commaWsp +
- '(' + number + ')' +
- '\\s*\\))',
-
- transform = '(?:' +
- matrix + '|' +
- translate + '|' +
- scale + '|' +
- rotate + '|' +
- skewX + '|' +
- skewY +
- ')',
-
- transforms = '(?:' + transform + '(?:' + commaWsp + '*' + transform + ')*' + ')',
-
- transformList = '^\\s*(?:' + transforms + '?)\\s*$',
-
- // http://www.w3.org/TR/SVG/coords.html#TransformAttribute
- reTransformList = new RegExp(transformList),
- // == end transform regexp
-
- reTransform = new RegExp(transform, 'g');
-
- return function(attributeValue) {
-
- // start with identity matrix
- var matrix = iMatrix.concat(),
- matrices = [];
-
- // return if no argument was given or
- // an argument does not match transform attribute regexp
- if (!attributeValue || (attributeValue && !reTransformList.test(attributeValue))) {
- return matrix;
- }
-
- attributeValue.replace(reTransform, function(match) {
-
- var m = new RegExp(transform).exec(match).filter(function (match) {
- // match !== '' && match != null
- return (!!match);
- }),
- operation = m[1],
- args = m.slice(2).map(parseFloat);
-
- switch (operation) {
- case 'translate':
- translateMatrix(matrix, args);
- break;
- case 'rotate':
- args[0] = fabric.util.degreesToRadians(args[0]);
- rotateMatrix(matrix, args);
- break;
- case 'scale':
- scaleMatrix(matrix, args);
- break;
- case 'skewX':
- skewMatrix(matrix, args, 2);
- break;
- case 'skewY':
- skewMatrix(matrix, args, 1);
- break;
- case 'matrix':
- matrix = args;
- break;
- }
-
- // snapshot current matrix into matrices array
- matrices.push(matrix.concat());
- // reset
- matrix = iMatrix.concat();
- });
-
- var combinedMatrix = matrices[0];
- while (matrices.length > 1) {
- matrices.shift();
- combinedMatrix = fabric.util.multiplyTransformMatrices(combinedMatrix, matrices[0]);
- }
- return combinedMatrix;
- };
- })();
-
- /**
- * @private
- */
- function parseStyleString(style, oStyle) {
- var attr, value;
- style.replace(/;\s*$/, '').split(';').forEach(function (chunk) {
- var pair = chunk.split(':');
-
- attr = pair[0].trim().toLowerCase();
- value = pair[1].trim();
-
- oStyle[attr] = value;
- });
- }
-
- /**
- * @private
- */
- function parseStyleObject(style, oStyle) {
- var attr, value;
- for (var prop in style) {
- if (typeof style[prop] === 'undefined') {
- continue;
- }
-
- attr = prop.toLowerCase();
- value = style[prop];
-
- oStyle[attr] = value;
- }
- }
-
- /**
- * @private
- */
- function getGlobalStylesForElement(element, svgUid) {
- var styles = { };
- for (var rule in fabric.cssRules[svgUid]) {
- if (elementMatchesRule(element, rule.split(' '))) {
- for (var property in fabric.cssRules[svgUid][rule]) {
- styles[property] = fabric.cssRules[svgUid][rule][property];
- }
- }
- }
- return styles;
- }
-
- /**
- * @private
- */
- function elementMatchesRule(element, selectors) {
- var firstMatching, parentMatching = true;
- //start from rightmost selector.
- firstMatching = selectorMatches(element, selectors.pop());
- if (firstMatching && selectors.length) {
- parentMatching = doesSomeParentMatch(element, selectors);
- }
- return firstMatching && parentMatching && (selectors.length === 0);
- }
-
- function doesSomeParentMatch(element, selectors) {
- var selector, parentMatching = true;
- while (element.parentNode && element.parentNode.nodeType === 1 && selectors.length) {
- if (parentMatching) {
- selector = selectors.pop();
- }
- element = element.parentNode;
- parentMatching = selectorMatches(element, selector);
- }
- return selectors.length === 0;
- }
-
- /**
- * @private
- */
- function selectorMatches(element, selector) {
- var nodeName = element.nodeName,
- classNames = element.getAttribute('class'),
- id = element.getAttribute('id'), matcher, i;
- // i check if a selector matches slicing away part from it.
- // if i get empty string i should match
- matcher = new RegExp('^' + nodeName, 'i');
- selector = selector.replace(matcher, '');
- if (id && selector.length) {
- matcher = new RegExp('#' + id + '(?![a-zA-Z\\-]+)', 'i');
- selector = selector.replace(matcher, '');
- }
- if (classNames && selector.length) {
- classNames = classNames.split(' ');
- for (i = classNames.length; i--;) {
- matcher = new RegExp('\\.' + classNames[i] + '(?![a-zA-Z\\-]+)', 'i');
- selector = selector.replace(matcher, '');
- }
- }
- return selector.length === 0;
- }
-
- /**
- * @private
- * to support IE8 missing getElementById on SVGdocument and on node xmlDOM
- */
- function elementById(doc, id) {
- var el;
- doc.getElementById && (el = doc.getElementById(id));
- if (el) {
- return el;
- }
- var node, i, len, nodelist = doc.getElementsByTagName('*');
- for (i = 0, len = nodelist.length; i < len; i++) {
- node = nodelist[i];
- if (id === node.getAttribute('id')) {
- return node;
- }
- }
- }
-
- /**
- * @private
- */
- function parseUseDirectives(doc) {
- var nodelist = _getMultipleNodes(doc, ['use', 'svg:use']), i = 0;
- while (nodelist.length && i < nodelist.length) {
- var el = nodelist[i],
- xlink = (el.getAttribute('xlink:href') || el.getAttribute('href')).substr(1),
- x = el.getAttribute('x') || 0,
- y = el.getAttribute('y') || 0,
- el2 = elementById(doc, xlink).cloneNode(true),
- currentTrans = (el2.getAttribute('transform') || '') + ' translate(' + x + ', ' + y + ')',
- parentNode, oldLength = nodelist.length, attr, j, attrs, len, namespace = fabric.svgNS;
-
- applyViewboxTransform(el2);
- if (/^svg$/i.test(el2.nodeName)) {
- var el3 = el2.ownerDocument.createElementNS(namespace, 'g');
- for (j = 0, attrs = el2.attributes, len = attrs.length; j < len; j++) {
- attr = attrs.item(j);
- el3.setAttributeNS(namespace, attr.nodeName, attr.nodeValue);
- }
- // el2.firstChild != null
- while (el2.firstChild) {
- el3.appendChild(el2.firstChild);
- }
- el2 = el3;
- }
-
- for (j = 0, attrs = el.attributes, len = attrs.length; j < len; j++) {
- attr = attrs.item(j);
- if (attr.nodeName === 'x' || attr.nodeName === 'y' ||
- attr.nodeName === 'xlink:href' || attr.nodeName === 'href') {
- continue;
- }
-
- if (attr.nodeName === 'transform') {
- currentTrans = attr.nodeValue + ' ' + currentTrans;
- }
- else {
- el2.setAttribute(attr.nodeName, attr.nodeValue);
- }
- }
-
- el2.setAttribute('transform', currentTrans);
- el2.setAttribute('instantiated_by_use', '1');
- el2.removeAttribute('id');
- parentNode = el.parentNode;
- parentNode.replaceChild(el2, el);
- // some browsers do not shorten nodelist after replaceChild (IE8)
- if (nodelist.length === oldLength) {
- i++;
- }
- }
- }
-
- // http://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute
- // matches, e.g.: +14.56e-12, etc.
- var reViewBoxAttrValue = new RegExp(
- '^' +
- '\\s*(' + fabric.reNum + '+)\\s*,?' +
- '\\s*(' + fabric.reNum + '+)\\s*,?' +
- '\\s*(' + fabric.reNum + '+)\\s*,?' +
- '\\s*(' + fabric.reNum + '+)\\s*' +
- '$'
- );
-
- /**
- * Add a <g> element that envelop all child elements and makes the viewbox transformMatrix descend on all elements
- */
- function applyViewboxTransform(element) {
-
- var viewBoxAttr = element.getAttribute('viewBox'),
- scaleX = 1,
- scaleY = 1,
- minX = 0,
- minY = 0,
- viewBoxWidth, viewBoxHeight, matrix, el,
- widthAttr = element.getAttribute('width'),
- heightAttr = element.getAttribute('height'),
- x = element.getAttribute('x') || 0,
- y = element.getAttribute('y') || 0,
- preserveAspectRatio = element.getAttribute('preserveAspectRatio') || '',
- missingViewBox = (!viewBoxAttr || !fabric.svgViewBoxElementsRegEx.test(element.nodeName)
- || !(viewBoxAttr = viewBoxAttr.match(reViewBoxAttrValue))),
- missingDimAttr = (!widthAttr || !heightAttr || widthAttr === '100%' || heightAttr === '100%'),
- toBeParsed = missingViewBox && missingDimAttr,
- parsedDim = { }, translateMatrix = '', widthDiff = 0, heightDiff = 0;
-
- parsedDim.width = 0;
- parsedDim.height = 0;
- parsedDim.toBeParsed = toBeParsed;
-
- if (toBeParsed) {
- return parsedDim;
- }
-
- if (missingViewBox) {
- parsedDim.width = parseUnit(widthAttr);
- parsedDim.height = parseUnit(heightAttr);
- return parsedDim;
- }
- minX = -parseFloat(viewBoxAttr[1]);
- minY = -parseFloat(viewBoxAttr[2]);
- viewBoxWidth = parseFloat(viewBoxAttr[3]);
- viewBoxHeight = parseFloat(viewBoxAttr[4]);
- parsedDim.minX = minX;
- parsedDim.minY = minY;
- parsedDim.viewBoxWidth = viewBoxWidth;
- parsedDim.viewBoxHeight = viewBoxHeight;
- if (!missingDimAttr) {
- parsedDim.width = parseUnit(widthAttr);
- parsedDim.height = parseUnit(heightAttr);
- scaleX = parsedDim.width / viewBoxWidth;
- scaleY = parsedDim.height / viewBoxHeight;
- }
- else {
- parsedDim.width = viewBoxWidth;
- parsedDim.height = viewBoxHeight;
- }
-
- // default is to preserve aspect ratio
- preserveAspectRatio = fabric.util.parsePreserveAspectRatioAttribute(preserveAspectRatio);
- if (preserveAspectRatio.alignX !== 'none') {
- //translate all container for the effect of Mid, Min, Max
- if (preserveAspectRatio.meetOrSlice === 'meet') {
- scaleY = scaleX = (scaleX > scaleY ? scaleY : scaleX);
- // calculate additional translation to move the viewbox
- }
- if (preserveAspectRatio.meetOrSlice === 'slice') {
- scaleY = scaleX = (scaleX > scaleY ? scaleX : scaleY);
- // calculate additional translation to move the viewbox
- }
- widthDiff = parsedDim.width - viewBoxWidth * scaleX;
- heightDiff = parsedDim.height - viewBoxHeight * scaleX;
- if (preserveAspectRatio.alignX === 'Mid') {
- widthDiff /= 2;
- }
- if (preserveAspectRatio.alignY === 'Mid') {
- heightDiff /= 2;
- }
- if (preserveAspectRatio.alignX === 'Min') {
- widthDiff = 0;
- }
- if (preserveAspectRatio.alignY === 'Min') {
- heightDiff = 0;
- }
- }
-
- if (scaleX === 1 && scaleY === 1 && minX === 0 && minY === 0 && x === 0 && y === 0) {
- return parsedDim;
- }
-
- if (x || y) {
- translateMatrix = ' translate(' + parseUnit(x) + ' ' + parseUnit(y) + ') ';
- }
-
- matrix = translateMatrix + ' matrix(' + scaleX +
- ' 0' +
- ' 0 ' +
- scaleY + ' ' +
- (minX * scaleX + widthDiff) + ' ' +
- (minY * scaleY + heightDiff) + ') ';
- parsedDim.viewboxTransform = fabric.parseTransformAttribute(matrix);
- if (element.nodeName === 'svg') {
- el = element.ownerDocument.createElementNS(fabric.svgNS, 'g');
- // element.firstChild != null
- while (element.firstChild) {
- el.appendChild(element.firstChild);
- }
- element.appendChild(el);
- }
- else {
- el = element;
- matrix = el.getAttribute('transform') + matrix;
- }
- el.setAttribute('transform', matrix);
- return parsedDim;
- }
-
- function hasAncestorWithNodeName(element, nodeName) {
- while (element && (element = element.parentNode)) {
- if (element.nodeName && nodeName.test(element.nodeName.replace('svg:', ''))
- && !element.getAttribute('instantiated_by_use')) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Parses an SVG document, converts it to an array of corresponding fabric.* instances and passes them to a callback
- * @static
- * @function
- * @memberOf fabric
- * @param {SVGDocument} doc SVG document to parse
- * @param {Function} callback Callback to call when parsing is finished;
- * It's being passed an array of elements (parsed from a document).
- * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
- * @param {Object} [parsingOptions] options for parsing document
- * @param {String} [parsingOptions.crossOrigin] crossOrigin settings
- */
- fabric.parseSVGDocument = function(doc, callback, reviver, parsingOptions) {
- if (!doc) {
- return;
- }
-
- parseUseDirectives(doc);
-
- var svgUid = fabric.Object.__uid++, i, len,
- options = applyViewboxTransform(doc),
- descendants = fabric.util.toArray(doc.getElementsByTagName('*'));
- options.crossOrigin = parsingOptions && parsingOptions.crossOrigin;
- options.svgUid = svgUid;
-
- if (descendants.length === 0 && fabric.isLikelyNode) {
- // we're likely in node, where "o3-xml" library fails to gEBTN("*")
- // https://github.com/ajaxorg/node-o3-xml/issues/21
- descendants = doc.selectNodes('//*[name(.)!="svg"]');
- var arr = [];
- for (i = 0, len = descendants.length; i < len; i++) {
- arr[i] = descendants[i];
- }
- descendants = arr;
- }
-
- var elements = descendants.filter(function(el) {
- applyViewboxTransform(el);
- return fabric.svgValidTagNamesRegEx.test(el.nodeName.replace('svg:', '')) &&
- !hasAncestorWithNodeName(el, fabric.svgInvalidAncestorsRegEx); // http://www.w3.org/TR/SVG/struct.html#DefsElement
- });
-
- if (!elements || (elements && !elements.length)) {
- callback && callback([], {});
- return;
- }
- var clipPaths = { };
- descendants.filter(function(el) {
- return el.nodeName.replace('svg:', '') === 'clipPath';
- }).forEach(function(el) {
- var id = el.getAttribute('id');
- clipPaths[id] = fabric.util.toArray(el.getElementsByTagName('*')).filter(function(el) {
- return fabric.svgValidTagNamesRegEx.test(el.nodeName.replace('svg:', ''));
- });
- });
- fabric.gradientDefs[svgUid] = fabric.getGradientDefs(doc);
- fabric.cssRules[svgUid] = fabric.getCSSRules(doc);
- fabric.clipPaths[svgUid] = clipPaths;
- // Precedence of rules: style > class > attribute
- fabric.parseElements(elements, function(instances, elements) {
- if (callback) {
- callback(instances, options, elements, descendants);
- delete fabric.gradientDefs[svgUid];
- delete fabric.cssRules[svgUid];
- delete fabric.clipPaths[svgUid];
- }
- }, clone(options), reviver, parsingOptions);
- };
-
- function recursivelyParseGradientsXlink(doc, gradient) {
- var gradientsAttrs = ['gradientTransform', 'x1', 'x2', 'y1', 'y2', 'gradientUnits', 'cx', 'cy', 'r', 'fx', 'fy'],
- xlinkAttr = 'xlink:href',
- xLink = gradient.getAttribute(xlinkAttr).substr(1),
- referencedGradient = elementById(doc, xLink);
- if (referencedGradient && referencedGradient.getAttribute(xlinkAttr)) {
- recursivelyParseGradientsXlink(doc, referencedGradient);
- }
- gradientsAttrs.forEach(function(attr) {
- if (referencedGradient && !gradient.hasAttribute(attr) && referencedGradient.hasAttribute(attr)) {
- gradient.setAttribute(attr, referencedGradient.getAttribute(attr));
- }
- });
- if (!gradient.children.length) {
- var referenceClone = referencedGradient.cloneNode(true);
- while (referenceClone.firstChild) {
- gradient.appendChild(referenceClone.firstChild);
- }
- }
- gradient.removeAttribute(xlinkAttr);
- }
-
- var reFontDeclaration = new RegExp(
- '(normal|italic)?\\s*(normal|small-caps)?\\s*' +
- '(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\s*(' +
- fabric.reNum +
- '(?:px|cm|mm|em|pt|pc|in)*)(?:\\/(normal|' + fabric.reNum + '))?\\s+(.*)');
-
- extend(fabric, {
- /**
- * Parses a short font declaration, building adding its properties to a style object
- * @static
- * @function
- * @memberOf fabric
- * @param {String} value font declaration
- * @param {Object} oStyle definition
- */
- parseFontDeclaration: function(value, oStyle) {
- var match = value.match(reFontDeclaration);
-
- if (!match) {
- return;
- }
- var fontStyle = match[1],
- // font variant is not used
- // fontVariant = match[2],
- fontWeight = match[3],
- fontSize = match[4],
- lineHeight = match[5],
- fontFamily = match[6];
-
- if (fontStyle) {
- oStyle.fontStyle = fontStyle;
- }
- if (fontWeight) {
- oStyle.fontWeight = isNaN(parseFloat(fontWeight)) ? fontWeight : parseFloat(fontWeight);
- }
- if (fontSize) {
- oStyle.fontSize = parseUnit(fontSize);
- }
- if (fontFamily) {
- oStyle.fontFamily = fontFamily;
- }
- if (lineHeight) {
- oStyle.lineHeight = lineHeight === 'normal' ? 1 : lineHeight;
- }
- },
-
- /**
- * Parses an SVG document, returning all of the gradient declarations found in it
- * @static
- * @function
- * @memberOf fabric
- * @param {SVGDocument} doc SVG document to parse
- * @return {Object} Gradient definitions; key corresponds to element id, value -- to gradient definition element
- */
- getGradientDefs: function(doc) {
- var tagArray = [
- 'linearGradient',
- 'radialGradient',
- 'svg:linearGradient',
- 'svg:radialGradient'],
- elList = _getMultipleNodes(doc, tagArray),
- el, j = 0, gradientDefs = { };
- j = elList.length;
- while (j--) {
- el = elList[j];
- if (el.getAttribute('xlink:href')) {
- recursivelyParseGradientsXlink(doc, el);
- }
- gradientDefs[el.getAttribute('id')] = el;
- }
- return gradientDefs;
- },
-
- /**
- * Returns an object of attributes' name/value, given element and an array of attribute names;
- * Parses parent "g" nodes recursively upwards.
- * @static
- * @memberOf fabric
- * @param {DOMElement} element Element to parse
- * @param {Array} attributes Array of attributes to parse
- * @return {Object} object containing parsed attributes' names/values
- */
- parseAttributes: function(element, attributes, svgUid) {
-
- if (!element) {
- return;
- }
-
- var value,
- parentAttributes = { },
- fontSize, parentFontSize;
-
- if (typeof svgUid === 'undefined') {
- svgUid = element.getAttribute('svgUid');
- }
- // if there's a parent container (`g` or `a` or `symbol` node), parse its attributes recursively upwards
- if (element.parentNode && fabric.svgValidParentsRegEx.test(element.parentNode.nodeName)) {
- parentAttributes = fabric.parseAttributes(element.parentNode, attributes, svgUid);
- }
-
- var ownAttributes = attributes.reduce(function(memo, attr) {
- value = element.getAttribute(attr);
- if (value) { // eslint-disable-line
- memo[attr] = value;
- }
- return memo;
- }, { });
- // add values parsed from style, which take precedence over attributes
- // (see: http://www.w3.org/TR/SVG/styling.html#UsingPresentationAttributes)
- var cssAttrs = extend(
- getGlobalStylesForElement(element, svgUid),
- fabric.parseStyleAttribute(element)
- );
- ownAttributes = extend(
- ownAttributes,
- cssAttrs
- );
- if (cssAttrs[cPath]) {
- element.setAttribute(cPath, cssAttrs[cPath]);
- }
- fontSize = parentFontSize = parentAttributes.fontSize || fabric.Text.DEFAULT_SVG_FONT_SIZE;
- if (ownAttributes[fSize]) {
- // looks like the minimum should be 9px when dealing with ems. this is what looks like in browsers.
- ownAttributes[fSize] = fontSize = parseUnit(ownAttributes[fSize], parentFontSize);
- }
-
- var normalizedAttr, normalizedValue, normalizedStyle = {};
- for (var attr in ownAttributes) {
- normalizedAttr = normalizeAttr(attr);
- normalizedValue = normalizeValue(normalizedAttr, ownAttributes[attr], parentAttributes, fontSize);
- normalizedStyle[normalizedAttr] = normalizedValue;
- }
- if (normalizedStyle && normalizedStyle.font) {
- fabric.parseFontDeclaration(normalizedStyle.font, normalizedStyle);
- }
- var mergedAttrs = extend(parentAttributes, normalizedStyle);
- return fabric.svgValidParentsRegEx.test(element.nodeName) ? mergedAttrs : _setStrokeFillOpacity(mergedAttrs);
- },
-
- /**
- * Transforms an array of svg elements to corresponding fabric.* instances
- * @static
- * @memberOf fabric
- * @param {Array} elements Array of elements to parse
- * @param {Function} callback Being passed an array of fabric instances (transformed from SVG elements)
- * @param {Object} [options] Options object
- * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
- */
- parseElements: function(elements, callback, options, reviver, parsingOptions) {
- new fabric.ElementsParser(elements, callback, options, reviver, parsingOptions).parse();
- },
-
- /**
- * Parses "style" attribute, retuning an object with values
- * @static
- * @memberOf fabric
- * @param {SVGElement} element Element to parse
- * @return {Object} Objects with values parsed from style attribute of an element
- */
- parseStyleAttribute: function(element) {
- var oStyle = { },
- style = element.getAttribute('style');
-
- if (!style) {
- return oStyle;
- }
-
- if (typeof style === 'string') {
- parseStyleString(style, oStyle);
- }
- else {
- parseStyleObject(style, oStyle);
- }
-
- return oStyle;
- },
-
- /**
- * Parses "points" attribute, returning an array of values
- * @static
- * @memberOf fabric
- * @param {String} points points attribute string
- * @return {Array} array of points
- */
- parsePointsAttribute: function(points) {
-
- // points attribute is required and must not be empty
- if (!points) {
- return null;
- }
-
- // replace commas with whitespace and remove bookending whitespace
- points = points.replace(/,/g, ' ').trim();
-
- points = points.split(/\s+/);
- var parsedPoints = [], i, len;
-
- for (i = 0, len = points.length; i < len; i += 2) {
- parsedPoints.push({
- x: parseFloat(points[i]),
- y: parseFloat(points[i + 1])
- });
- }
-
- // odd number of points is an error
- // if (parsedPoints.length % 2 !== 0) {
- // return null;
- // }
-
- return parsedPoints;
- },
-
- /**
- * Returns CSS rules for a given SVG document
- * @static
- * @function
- * @memberOf fabric
- * @param {SVGDocument} doc SVG document to parse
- * @return {Object} CSS rules of this document
- */
- getCSSRules: function(doc) {
- var styles = doc.getElementsByTagName('style'), i, len,
- allRules = { }, rules;
-
- // very crude parsing of style contents
- for (i = 0, len = styles.length; i < len; i++) {
- // IE9 doesn't support textContent, but provides text instead.
- var styleContents = styles[i].textContent || styles[i].text;
-
- // remove comments
- styleContents = styleContents.replace(/\/\*[\s\S]*?\*\//g, '');
- if (styleContents.trim() === '') {
- continue;
- }
- rules = styleContents.match(/[^{]*\{[\s\S]*?\}/g);
- rules = rules.map(function(rule) { return rule.trim(); });
- // eslint-disable-next-line no-loop-func
- rules.forEach(function(rule) {
-
- var match = rule.match(/([\s\S]*?)\s*\{([^}]*)\}/),
- ruleObj = { }, declaration = match[2].trim(),
- propertyValuePairs = declaration.replace(/;$/, '').split(/\s*;\s*/);
-
- for (i = 0, len = propertyValuePairs.length; i < len; i++) {
- var pair = propertyValuePairs[i].split(/\s*:\s*/),
- property = pair[0],
- value = pair[1];
- ruleObj[property] = value;
- }
- rule = match[1];
- rule.split(',').forEach(function(_rule) {
- _rule = _rule.replace(/^svg/i, '').trim();
- if (_rule === '') {
- return;
- }
- if (allRules[_rule]) {
- fabric.util.object.extend(allRules[_rule], ruleObj);
- }
- else {
- allRules[_rule] = fabric.util.object.clone(ruleObj);
- }
- });
- });
- }
- return allRules;
- },
-
- /**
- * Takes url corresponding to an SVG document, and parses it into a set of fabric objects.
- * Note that SVG is fetched via XMLHttpRequest, so it needs to conform to SOP (Same Origin Policy)
- * @memberOf fabric
- * @param {String} url
- * @param {Function} callback
- * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
- * @param {Object} [options] Object containing options for parsing
- * @param {String} [options.crossOrigin] crossOrigin crossOrigin setting to use for external resources
- */
- loadSVGFromURL: function(url, callback, reviver, options) {
-
- url = url.replace(/^\n\s*/, '').trim();
- new fabric.util.request(url, {
- method: 'get',
- onComplete: onComplete
- });
-
- function onComplete(r) {
-
- var xml = r.responseXML;
- if (xml && !xml.documentElement && fabric.window.ActiveXObject && r.responseText) {
- xml = new ActiveXObject('Microsoft.XMLDOM');
- xml.async = 'false';
- //IE chokes on DOCTYPE
- xml.loadXML(r.responseText.replace(/<!DOCTYPE[\s\S]*?(\[[\s\S]*\])*?>/i, ''));
- }
- if (!xml || !xml.documentElement) {
- callback && callback(null);
- return false;
- }
-
- fabric.parseSVGDocument(xml.documentElement, function (results, _options, elements, allElements) {
- callback && callback(results, _options, elements, allElements);
- }, reviver, options);
- }
- },
-
- /**
- * Takes string corresponding to an SVG document, and parses it into a set of fabric objects
- * @memberOf fabric
- * @param {String} string
- * @param {Function} callback
- * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
- * @param {Object} [options] Object containing options for parsing
- * @param {String} [options.crossOrigin] crossOrigin crossOrigin setting to use for external resources
- */
- loadSVGFromString: function(string, callback, reviver, options) {
- string = string.trim();
- var doc;
- if (typeof fabric.window.DOMParser !== 'undefined') {
- var parser = new fabric.window.DOMParser();
- if (parser && parser.parseFromString) {
- doc = parser.parseFromString(string, 'text/xml');
- }
- }
- else if (fabric.window.ActiveXObject) {
- doc = new ActiveXObject('Microsoft.XMLDOM');
- doc.async = 'false';
- // IE chokes on DOCTYPE
- doc.loadXML(string.replace(/<!DOCTYPE[\s\S]*?(\[[\s\S]*\])*?>/i, ''));
- }
-
- fabric.parseSVGDocument(doc.documentElement, function (results, _options, elements, allElements) {
- callback(results, _options, elements, allElements);
- }, reviver, options);
- }
- });
-
-})(typeof exports !== 'undefined' ? exports : this);
-
-
-fabric.ElementsParser = function(elements, callback, options, reviver, parsingOptions, doc) {
- this.elements = elements;
- this.callback = callback;
- this.options = options;
- this.reviver = reviver;
- this.svgUid = (options && options.svgUid) || 0;
- this.parsingOptions = parsingOptions;
- this.regexUrl = /^url\(['"]?#([^'"]+)['"]?\)/g;
- this.doc = doc;
-};
-
-(function(proto) {
- proto.parse = function() {
- this.instances = new Array(this.elements.length);
- this.numElements = this.elements.length;
- this.createObjects();
- };
-
- proto.createObjects = function() {
- var _this = this;
- this.elements.forEach(function(element, i) {
- element.setAttribute('svgUid', _this.svgUid);
- _this.createObject(element, i);
- });
- };
-
- proto.findTag = function(el) {
- return fabric[fabric.util.string.capitalize(el.tagName.replace('svg:', ''))];
- };
-
- proto.createObject = function(el, index) {
- var klass = this.findTag(el);
- if (klass && klass.fromElement) {
- try {
- klass.fromElement(el, this.createCallback(index, el), this.options);
- }
- catch (err) {
- fabric.log(err);
- }
- }
- else {
- this.checkIfDone();
- }
- };
-
- proto.createCallback = function(index, el) {
- var _this = this;
- return function(obj) {
- var _options;
- _this.resolveGradient(obj, el, 'fill');
- _this.resolveGradient(obj, el, 'stroke');
- if (obj instanceof fabric.Image && obj._originalElement) {
- _options = obj.parsePreserveAspectRatioAttribute(el);
- }
- obj._removeTransformMatrix(_options);
- _this.resolveClipPath(obj, el);
- _this.reviver && _this.reviver(el, obj);
- _this.instances[index] = obj;
- _this.checkIfDone();
- };
- };
-
- proto.extractPropertyDefinition = function(obj, property, storage) {
- var value = obj[property], regex = this.regexUrl;
- if (!regex.test(value)) {
- return;
- }
- regex.lastIndex = 0;
- var id = regex.exec(value)[1];
- regex.lastIndex = 0;
- return fabric[storage][this.svgUid][id];
- };
-
- proto.resolveGradient = function(obj, el, property) {
- var gradientDef = this.extractPropertyDefinition(obj, property, 'gradientDefs');
- if (gradientDef) {
- var opacityAttr = el.getAttribute(property + '-opacity');
- var gradient = fabric.Gradient.fromElement(gradientDef, obj, opacityAttr, this.options);
- obj.set(property, gradient);
- }
- };
-
- proto.createClipPathCallback = function(obj, container) {
- return function(_newObj) {
- _newObj._removeTransformMatrix();
- _newObj.fillRule = _newObj.clipRule;
- container.push(_newObj);
- };
- };
-
- proto.resolveClipPath = function(obj, usingElement) {
- var clipPath = this.extractPropertyDefinition(obj, 'clipPath', 'clipPaths'),
- element, klass, objTransformInv, container, gTransform, options;
- if (clipPath) {
- container = [];
- objTransformInv = fabric.util.invertTransform(obj.calcTransformMatrix());
- // move the clipPath tag as sibling to the real element that is using it
- var clipPathTag = clipPath[0].parentNode;
- var clipPathOwner = usingElement;
- while (clipPathOwner.parentNode && clipPathOwner.getAttribute('clip-path') !== obj.clipPath) {
- clipPathOwner = clipPathOwner.parentNode;
- }
- clipPathOwner.parentNode.appendChild(clipPathTag);
- for (var i = 0; i < clipPath.length; i++) {
- element = clipPath[i];
- klass = this.findTag(element);
- klass.fromElement(
- element,
- this.createClipPathCallback(obj, container),
- this.options
- );
- }
- if (container.length === 1) {
- clipPath = container[0];
- }
- else {
- clipPath = new fabric.Group(container);
- }
- gTransform = fabric.util.multiplyTransformMatrices(
- objTransformInv,
- clipPath.calcTransformMatrix()
- );
- if (clipPath.clipPath) {
- this.resolveClipPath(clipPath, clipPathOwner);
- }
- var options = fabric.util.qrDecompose(gTransform);
- clipPath.flipX = false;
- clipPath.flipY = false;
- clipPath.set('scaleX', options.scaleX);
- clipPath.set('scaleY', options.scaleY);
- clipPath.angle = options.angle;
- clipPath.skewX = options.skewX;
- clipPath.skewY = 0;
- clipPath.setPositionByOrigin({ x: options.translateX, y: options.translateY }, 'center', 'center');
- obj.clipPath = clipPath;
- }
- };
-
- proto.checkIfDone = function() {
- if (--this.numElements === 0) {
- this.instances = this.instances.filter(function(el) {
- // eslint-disable-next-line no-eq-null, eqeqeq
- return el != null;
- });
- this.callback(this.instances, this.elements);
- }
- };
-})(fabric.ElementsParser.prototype);
-
-
-(function(global) {
-
- 'use strict';
-
- /* Adaptation of work of Kevin Lindsey (kevin@kevlindev.com) */
-
- var fabric = global.fabric || (global.fabric = { });
-
- if (fabric.Point) {
- fabric.warn('fabric.Point is already defined');
- return;
- }
-
- fabric.Point = Point;
-
- /**
- * Point class
- * @class fabric.Point
- * @memberOf fabric
- * @constructor
- * @param {Number} x
- * @param {Number} y
- * @return {fabric.Point} thisArg
- */
- function Point(x, y) {
- this.x = x;
- this.y = y;
- }
-
- Point.prototype = /** @lends fabric.Point.prototype */ {
-
- type: 'point',
-
- constructor: Point,
-
- /**
- * Adds another point to this one and returns another one
- * @param {fabric.Point} that
- * @return {fabric.Point} new Point instance with added values
- */
- add: function (that) {
- return new Point(this.x + that.x, this.y + that.y);
- },
-
- /**
- * Adds another point to this one
- * @param {fabric.Point} that
- * @return {fabric.Point} thisArg
- * @chainable
- */
- addEquals: function (that) {
- this.x += that.x;
- this.y += that.y;
- return this;
- },
-
- /**
- * Adds value to this point and returns a new one
- * @param {Number} scalar
- * @return {fabric.Point} new Point with added value
- */
- scalarAdd: function (scalar) {
- return new Point(this.x + scalar, this.y + scalar);
- },
-
- /**
- * Adds value to this point
- * @param {Number} scalar
- * @return {fabric.Point} thisArg
- * @chainable
- */
- scalarAddEquals: function (scalar) {
- this.x += scalar;
- this.y += scalar;
- return this;
- },
-
- /**
- * Subtracts another point from this point and returns a new one
- * @param {fabric.Point} that
- * @return {fabric.Point} new Point object with subtracted values
- */
- subtract: function (that) {
- return new Point(this.x - that.x, this.y - that.y);
- },
-
- /**
- * Subtracts another point from this point
- * @param {fabric.Point} that
- * @return {fabric.Point} thisArg
- * @chainable
- */
- subtractEquals: function (that) {
- this.x -= that.x;
- this.y -= that.y;
- return this;
- },
-
- /**
- * Subtracts value from this point and returns a new one
- * @param {Number} scalar
- * @return {fabric.Point}
- */
- scalarSubtract: function (scalar) {
- return new Point(this.x - scalar, this.y - scalar);
- },
-
- /**
- * Subtracts value from this point
- * @param {Number} scalar
- * @return {fabric.Point} thisArg
- * @chainable
- */
- scalarSubtractEquals: function (scalar) {
- this.x -= scalar;
- this.y -= scalar;
- return this;
- },
-
- /**
- * Multiplies this point by a value and returns a new one
- * TODO: rename in scalarMultiply in 2.0
- * @param {Number} scalar
- * @return {fabric.Point}
- */
- multiply: function (scalar) {
- return new Point(this.x * scalar, this.y * scalar);
- },
-
- /**
- * Multiplies this point by a value
- * TODO: rename in scalarMultiplyEquals in 2.0
- * @param {Number} scalar
- * @return {fabric.Point} thisArg
- * @chainable
- */
- multiplyEquals: function (scalar) {
- this.x *= scalar;
- this.y *= scalar;
- return this;
- },
-
- /**
- * Divides this point by a value and returns a new one
- * TODO: rename in scalarDivide in 2.0
- * @param {Number} scalar
- * @return {fabric.Point}
- */
- divide: function (scalar) {
- return new Point(this.x / scalar, this.y / scalar);
- },
-
- /**
- * Divides this point by a value
- * TODO: rename in scalarDivideEquals in 2.0
- * @param {Number} scalar
- * @return {fabric.Point} thisArg
- * @chainable
- */
- divideEquals: function (scalar) {
- this.x /= scalar;
- this.y /= scalar;
- return this;
- },
-
- /**
- * Returns true if this point is equal to another one
- * @param {fabric.Point} that
- * @return {Boolean}
- */
- eq: function (that) {
- return (this.x === that.x && this.y === that.y);
- },
-
- /**
- * Returns true if this point is less than another one
- * @param {fabric.Point} that
- * @return {Boolean}
- */
- lt: function (that) {
- return (this.x < that.x && this.y < that.y);
- },
-
- /**
- * Returns true if this point is less than or equal to another one
- * @param {fabric.Point} that
- * @return {Boolean}
- */
- lte: function (that) {
- return (this.x <= that.x && this.y <= that.y);
- },
-
- /**
-
- * Returns true if this point is greater another one
- * @param {fabric.Point} that
- * @return {Boolean}
- */
- gt: function (that) {
- return (this.x > that.x && this.y > that.y);
- },
-
- /**
- * Returns true if this point is greater than or equal to another one
- * @param {fabric.Point} that
- * @return {Boolean}
- */
- gte: function (that) {
- return (this.x >= that.x && this.y >= that.y);
- },
-
- /**
- * Returns new point which is the result of linear interpolation with this one and another one
- * @param {fabric.Point} that
- * @param {Number} t , position of interpolation, between 0 and 1 default 0.5
- * @return {fabric.Point}
- */
- lerp: function (that, t) {
- if (typeof t === 'undefined') {
- t = 0.5;
- }
- t = Math.max(Math.min(1, t), 0);
- return new Point(this.x + (that.x - this.x) * t, this.y + (that.y - this.y) * t);
- },
-
- /**
- * Returns distance from this point and another one
- * @param {fabric.Point} that
- * @return {Number}
- */
- distanceFrom: function (that) {
- var dx = this.x - that.x,
- dy = this.y - that.y;
- return Math.sqrt(dx * dx + dy * dy);
- },
-
- /**
- * Returns the point between this point and another one
- * @param {fabric.Point} that
- * @return {fabric.Point}
- */
- midPointFrom: function (that) {
- return this.lerp(that);
- },
-
- /**
- * Returns a new point which is the min of this and another one
- * @param {fabric.Point} that
- * @return {fabric.Point}
- */
- min: function (that) {
- return new Point(Math.min(this.x, that.x), Math.min(this.y, that.y));
- },
-
- /**
- * Returns a new point which is the max of this and another one
- * @param {fabric.Point} that
- * @return {fabric.Point}
- */
- max: function (that) {
- return new Point(Math.max(this.x, that.x), Math.max(this.y, that.y));
- },
-
- /**
- * Returns string representation of this point
- * @return {String}
- */
- toString: function () {
- return this.x + ',' + this.y;
- },
-
- /**
- * Sets x/y of this point
- * @param {Number} x
- * @param {Number} y
- * @chainable
- */
- setXY: function (x, y) {
- this.x = x;
- this.y = y;
- return this;
- },
-
- /**
- * Sets x of this point
- * @param {Number} x
- * @chainable
- */
- setX: function (x) {
- this.x = x;
- return this;
- },
-
- /**
- * Sets y of this point
- * @param {Number} y
- * @chainable
- */
- setY: function (y) {
- this.y = y;
- return this;
- },
-
- /**
- * Sets x/y of this point from another point
- * @param {fabric.Point} that
- * @chainable
- */
- setFromPoint: function (that) {
- this.x = that.x;
- this.y = that.y;
- return this;
- },
-
- /**
- * Swaps x/y of this point and another point
- * @param {fabric.Point} that
- */
- swap: function (that) {
- var x = this.x,
- y = this.y;
- this.x = that.x;
- this.y = that.y;
- that.x = x;
- that.y = y;
- },
-
- /**
- * return a cloned instance of the point
- * @return {fabric.Point}
- */
- clone: function () {
- return new Point(this.x, this.y);
- }
- };
-
-})(typeof exports !== 'undefined' ? exports : this);
-
-
-(function(global) {
-
- 'use strict';
-
- /* Adaptation of work of Kevin Lindsey (kevin@kevlindev.com) */
- var fabric = global.fabric || (global.fabric = { });
-
- if (fabric.Intersection) {
- fabric.warn('fabric.Intersection is already defined');
- return;
- }
-
- /**
- * Intersection class
- * @class fabric.Intersection
- * @memberOf fabric
- * @constructor
- */
- function Intersection(status) {
- this.status = status;
- this.points = [];
- }
-
- fabric.Intersection = Intersection;
-
- fabric.Intersection.prototype = /** @lends fabric.Intersection.prototype */ {
-
- constructor: Intersection,
-
- /**
- * Appends a point to intersection
- * @param {fabric.Point} point
- * @return {fabric.Intersection} thisArg
- * @chainable
- */
- appendPoint: function (point) {
- this.points.push(point);
- return this;
- },
-
- /**
- * Appends points to intersection
- * @param {Array} points
- * @return {fabric.Intersection} thisArg
- * @chainable
- */
- appendPoints: function (points) {
- this.points = this.points.concat(points);
- return this;
- }
- };
-
- /**
- * Checks if one line intersects another
- * TODO: rename in intersectSegmentSegment
- * @static
- * @param {fabric.Point} a1
- * @param {fabric.Point} a2
- * @param {fabric.Point} b1
- * @param {fabric.Point} b2
- * @return {fabric.Intersection}
- */
- fabric.Intersection.intersectLineLine = function (a1, a2, b1, b2) {
- var result,
- uaT = (b2.x - b1.x) * (a1.y - b1.y) - (b2.y - b1.y) * (a1.x - b1.x),
- ubT = (a2.x - a1.x) * (a1.y - b1.y) - (a2.y - a1.y) * (a1.x - b1.x),
- uB = (b2.y - b1.y) * (a2.x - a1.x) - (b2.x - b1.x) * (a2.y - a1.y);
- if (uB !== 0) {
- var ua = uaT / uB,
- ub = ubT / uB;
- if (0 <= ua && ua <= 1 && 0 <= ub && ub <= 1) {
- result = new Intersection('Intersection');
- result.appendPoint(new fabric.Point(a1.x + ua * (a2.x - a1.x), a1.y + ua * (a2.y - a1.y)));
- }
- else {
- result = new Intersection();
- }
- }
- else {
- if (uaT === 0 || ubT === 0) {
- result = new Intersection('Coincident');
- }
- else {
- result = new Intersection('Parallel');
- }
- }
- return result;
- };
-
- /**
- * Checks if line intersects polygon
- * TODO: rename in intersectSegmentPolygon
- * fix detection of coincident
- * @static
- * @param {fabric.Point} a1
- * @param {fabric.Point} a2
- * @param {Array} points
- * @return {fabric.Intersection}
- */
- fabric.Intersection.intersectLinePolygon = function(a1, a2, points) {
- var result = new Intersection(),
- length = points.length,
- b1, b2, inter, i;
-
- for (i = 0; i < length; i++) {
- b1 = points[i];
- b2 = points[(i + 1) % length];
- inter = Intersection.intersectLineLine(a1, a2, b1, b2);
-
- result.appendPoints(inter.points);
- }
- if (result.points.length > 0) {
- result.status = 'Intersection';
- }
- return result;
- };
-
- /**
- * Checks if polygon intersects another polygon
- * @static
- * @param {Array} points1
- * @param {Array} points2
- * @return {fabric.Intersection}
- */
- fabric.Intersection.intersectPolygonPolygon = function (points1, points2) {
- var result = new Intersection(),
- length = points1.length, i;
-
- for (i = 0; i < length; i++) {
- var a1 = points1[i],
- a2 = points1[(i + 1) % length],
- inter = Intersection.intersectLinePolygon(a1, a2, points2);
-
- result.appendPoints(inter.points);
- }
- if (result.points.length > 0) {
- result.status = 'Intersection';
- }
- return result;
- };
-
- /**
- * Checks if polygon intersects rectangle
- * @static
- * @param {Array} points
- * @param {fabric.Point} r1
- * @param {fabric.Point} r2
- * @return {fabric.Intersection}
- */
- fabric.Intersection.intersectPolygonRectangle = function (points, r1, r2) {
- var min = r1.min(r2),
- max = r1.max(r2),
- topRight = new fabric.Point(max.x, min.y),
- bottomLeft = new fabric.Point(min.x, max.y),
- inter1 = Intersection.intersectLinePolygon(min, topRight, points),
- inter2 = Intersection.intersectLinePolygon(topRight, max, points),
- inter3 = Intersection.intersectLinePolygon(max, bottomLeft, points),
- inter4 = Intersection.intersectLinePolygon(bottomLeft, min, points),
- result = new Intersection();
-
- result.appendPoints(inter1.points);
- result.appendPoints(inter2.points);
- result.appendPoints(inter3.points);
- result.appendPoints(inter4.points);
-
- if (result.points.length > 0) {
- result.status = 'Intersection';
- }
- return result;
- };
-
-})(typeof exports !== 'undefined' ? exports : this);
-
-
-(function(global) {
-
- 'use strict';
-
- var fabric = global.fabric || (global.fabric = { });
-
- if (fabric.Color) {
- fabric.warn('fabric.Color is already defined.');
- return;
- }
-
- /**
- * Color class
- * The purpose of {@link fabric.Color} is to abstract and encapsulate common color operations;
- * {@link fabric.Color} is a constructor and creates instances of {@link fabric.Color} objects.
- *
- * @class fabric.Color
- * @param {String} color optional in hex or rgb(a) or hsl format or from known color list
- * @return {fabric.Color} thisArg
- * @tutorial {@link http://fabricjs.com/fabric-intro-part-2/#colors}
- */
- function Color(color) {
- if (!color) {
- this.setSource([0, 0, 0, 1]);
- }
- else {
- this._tryParsingColor(color);
- }
- }
-
- fabric.Color = Color;
-
- fabric.Color.prototype = /** @lends fabric.Color.prototype */ {
-
- /**
- * @private
- * @param {String|Array} color Color value to parse
- */
- _tryParsingColor: function(color) {
- var source;
-
- if (color in Color.colorNameMap) {
- color = Color.colorNameMap[color];
- }
-
- if (color === 'transparent') {
- source = [255, 255, 255, 0];
- }
-
- if (!source) {
- source = Color.sourceFromHex(color);
- }
- if (!source) {
- source = Color.sourceFromRgb(color);
- }
- if (!source) {
- source = Color.sourceFromHsl(color);
- }
- if (!source) {
- //if color is not recognize let's make black as canvas does
- source = [0, 0, 0, 1];
- }
- if (source) {
- this.setSource(source);
- }
- },
-
- /**
- * 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>
- * @private
- * @param {Number} r Red color value
- * @param {Number} g Green color value
- * @param {Number} b Blue color value
- * @return {Array} Hsl color
- */
- _rgbToHsl: function(r, g, b) {
- r /= 255; g /= 255; b /= 255;
-
- var h, s, l,
- max = fabric.util.array.max([r, g, b]),
- min = fabric.util.array.min([r, g, b]);
-
- l = (max + min) / 2;
-
- if (max === min) {
- h = s = 0; // achromatic
- }
- else {
- var d = max - min;
- s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
- switch (max) {
- case r:
- h = (g - b) / d + (g < b ? 6 : 0);
- break;
- case g:
- h = (b - r) / d + 2;
- break;
- case b:
- h = (r - g) / d + 4;
- break;
- }
- h /= 6;
- }
-
- return [
- Math.round(h * 360),
- Math.round(s * 100),
- Math.round(l * 100)
- ];
- },
-
- /**
- * Returns source of this color (where source is an array representation; ex: [200, 200, 100, 1])
- * @return {Array}
- */
- getSource: function() {
- return this._source;
- },
-
- /**
- * Sets source of this color (where source is an array representation; ex: [200, 200, 100, 1])
- * @param {Array} source
- */
- setSource: function(source) {
- this._source = source;
- },
-
- /**
- * Returns color representation in RGB format
- * @return {String} ex: rgb(0-255,0-255,0-255)
- */
- toRgb: function() {
- var source = this.getSource();
- return 'rgb(' + source[0] + ',' + source[1] + ',' + source[2] + ')';
- },
-
- /**
- * Returns color representation in RGBA format
- * @return {String} ex: rgba(0-255,0-255,0-255,0-1)
- */
- toRgba: function() {
- var source = this.getSource();
- return 'rgba(' + source[0] + ',' + source[1] + ',' + source[2] + ',' + source[3] + ')';
- },
-
- /**
- * Returns color representation in HSL format
- * @return {String} ex: hsl(0-360,0%-100%,0%-100%)
- */
- toHsl: function() {
- var source = this.getSource(),
- hsl = this._rgbToHsl(source[0], source[1], source[2]);
-
- return 'hsl(' + hsl[0] + ',' + hsl[1] + '%,' + hsl[2] + '%)';
- },
-
- /**
- * Returns color representation in HSLA format
- * @return {String} ex: hsla(0-360,0%-100%,0%-100%,0-1)
- */
- toHsla: function() {
- var source = this.getSource(),
- hsl = this._rgbToHsl(source[0], source[1], source[2]);
-
- return 'hsla(' + hsl[0] + ',' + hsl[1] + '%,' + hsl[2] + '%,' + source[3] + ')';
- },
-
- /**
- * Returns color representation in HEX format
- * @return {String} ex: FF5555
- */
- toHex: function() {
- var source = this.getSource(), r, g, b;
-
- r = source[0].toString(16);
- r = (r.length === 1) ? ('0' + r) : r;
-
- g = source[1].toString(16);
- g = (g.length === 1) ? ('0' + g) : g;
-
- b = source[2].toString(16);
- b = (b.length === 1) ? ('0' + b) : b;
-
- return r.toUpperCase() + g.toUpperCase() + b.toUpperCase();
- },
-
- /**
- * Returns color representation in HEXA format
- * @return {String} ex: FF5555CC
- */
- toHexa: function() {
- var source = this.getSource(), a;
-
- a = Math.round(source[3] * 255);
- a = a.toString(16);
- a = (a.length === 1) ? ('0' + a) : a;
-
- return this.toHex() + a.toUpperCase();
- },
-
- /**
- * Gets value of alpha channel for this color
- * @return {Number} 0-1
- */
- getAlpha: function() {
- return this.getSource()[3];
- },
-
- /**
- * Sets value of alpha channel for this color
- * @param {Number} alpha Alpha value 0-1
- * @return {fabric.Color} thisArg
- */
- setAlpha: function(alpha) {
- var source = this.getSource();
- source[3] = alpha;
- this.setSource(source);
- return this;
- },
-
- /**
- * Transforms color to its grayscale representation
- * @return {fabric.Color} thisArg
- */
- toGrayscale: function() {
- var source = this.getSource(),
- average = parseInt((source[0] * 0.3 + source[1] * 0.59 + source[2] * 0.11).toFixed(0), 10),
- currentAlpha = source[3];
- this.setSource([average, average, average, currentAlpha]);
- return this;
- },
-
- /**
- * Transforms color to its black and white representation
- * @param {Number} threshold
- * @return {fabric.Color} thisArg
- */
- toBlackWhite: function(threshold) {
- var source = this.getSource(),
- average = (source[0] * 0.3 + source[1] * 0.59 + source[2] * 0.11).toFixed(0),
- currentAlpha = source[3];
-
- threshold = threshold || 127;
-
- average = (Number(average) < Number(threshold)) ? 0 : 255;
- this.setSource([average, average, average, currentAlpha]);
- return this;
- },
-
- /**
- * Overlays color with another color
- * @param {String|fabric.Color} otherColor
- * @return {fabric.Color} thisArg
- */
- overlayWith: function(otherColor) {
- if (!(otherColor instanceof Color)) {
- otherColor = new Color(otherColor);
- }
-
- var result = [],
- alpha = this.getAlpha(),
- otherAlpha = 0.5,
- source = this.getSource(),
- otherSource = otherColor.getSource(), i;
-
- for (i = 0; i < 3; i++) {
- result.push(Math.round((source[i] * (1 - otherAlpha)) + (otherSource[i] * otherAlpha)));
- }
-
- result[3] = alpha;
- this.setSource(result);
- return this;
- }
- };
-
- /**
- * Regex matching color in RGB or RGBA formats (ex: rgb(0, 0, 0), rgba(255, 100, 10, 0.5), rgba( 255 , 100 , 10 , 0.5 ), rgb(1,1,1), rgba(100%, 60%, 10%, 0.5))
- * @static
- * @field
- * @memberOf fabric.Color
- */
- // eslint-disable-next-line max-len
- 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*)?\)$/i;
-
- /**
- * Regex matching color in HSL or HSLA formats (ex: hsl(200, 80%, 10%), hsla(300, 50%, 80%, 0.5), hsla( 300 , 50% , 80% , 0.5 ))
- * @static
- * @field
- * @memberOf fabric.Color
- */
- fabric.Color.reHSLa = /^hsla?\(\s*(\d{1,3})\s*,\s*(\d{1,3}\%)\s*,\s*(\d{1,3}\%)\s*(?:\s*,\s*(\d+(?:\.\d+)?)\s*)?\)$/i;
-
- /**
- * Regex matching color in HEX format (ex: #FF5544CC, #FF5555, 010155, aff)
- * @static
- * @field
- * @memberOf fabric.Color
- */
- fabric.Color.reHex = /^#?([0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{4}|[0-9a-f]{3})$/i;
-
- /**
- * Map of the 148 color names with HEX code
- * @static
- * @field
- * @memberOf fabric.Color
- * @see: https://www.w3.org/TR/css3-color/#svg-color
- */
- fabric.Color.colorNameMap = {
- aliceblue: '#F0F8FF',
- antiquewhite: '#FAEBD7',
- aqua: '#00FFFF',
- aquamarine: '#7FFFD4',
- azure: '#F0FFFF',
- beige: '#F5F5DC',
- bisque: '#FFE4C4',
- black: '#000000',
- blanchedalmond: '#FFEBCD',
- blue: '#0000FF',
- blueviolet: '#8A2BE2',
- brown: '#A52A2A',
- burlywood: '#DEB887',
- cadetblue: '#5F9EA0',
- chartreuse: '#7FFF00',
- chocolate: '#D2691E',
- coral: '#FF7F50',
- cornflowerblue: '#6495ED',
- cornsilk: '#FFF8DC',
- crimson: '#DC143C',
- cyan: '#00FFFF',
- darkblue: '#00008B',
- darkcyan: '#008B8B',
- darkgoldenrod: '#B8860B',
- darkgray: '#A9A9A9',
- darkgrey: '#A9A9A9',
- darkgreen: '#006400',
- darkkhaki: '#BDB76B',
- darkmagenta: '#8B008B',
- darkolivegreen: '#556B2F',
- darkorange: '#FF8C00',
- darkorchid: '#9932CC',
- darkred: '#8B0000',
- darksalmon: '#E9967A',
- darkseagreen: '#8FBC8F',
- darkslateblue: '#483D8B',
- darkslategray: '#2F4F4F',
- darkslategrey: '#2F4F4F',
- darkturquoise: '#00CED1',
- darkviolet: '#9400D3',
- deeppink: '#FF1493',
- deepskyblue: '#00BFFF',
- dimgray: '#696969',
- dimgrey: '#696969',
- dodgerblue: '#1E90FF',
- firebrick: '#B22222',
- floralwhite: '#FFFAF0',
- forestgreen: '#228B22',
- fuchsia: '#FF00FF',
- gainsboro: '#DCDCDC',
- ghostwhite: '#F8F8FF',
- gold: '#FFD700',
- goldenrod: '#DAA520',
- gray: '#808080',
- grey: '#808080',
- green: '#008000',
- greenyellow: '#ADFF2F',
- honeydew: '#F0FFF0',
- hotpink: '#FF69B4',
- indianred: '#CD5C5C',
- indigo: '#4B0082',
- ivory: '#FFFFF0',
- khaki: '#F0E68C',
- lavender: '#E6E6FA',
- lavenderblush: '#FFF0F5',
- lawngreen: '#7CFC00',
- lemonchiffon: '#FFFACD',
- lightblue: '#ADD8E6',
- lightcoral: '#F08080',
- lightcyan: '#E0FFFF',
- lightgoldenrodyellow: '#FAFAD2',
- lightgray: '#D3D3D3',
- lightgrey: '#D3D3D3',
- lightgreen: '#90EE90',
- lightpink: '#FFB6C1',
- lightsalmon: '#FFA07A',
- lightseagreen: '#20B2AA',
- lightskyblue: '#87CEFA',
- lightslategray: '#778899',
- lightslategrey: '#778899',
- lightsteelblue: '#B0C4DE',
- lightyellow: '#FFFFE0',
- lime: '#00FF00',
- limegreen: '#32CD32',
- linen: '#FAF0E6',
- magenta: '#FF00FF',
- maroon: '#800000',
- mediumaquamarine: '#66CDAA',
- mediumblue: '#0000CD',
- mediumorchid: '#BA55D3',
- mediumpurple: '#9370DB',
- mediumseagreen: '#3CB371',
- mediumslateblue: '#7B68EE',
- mediumspringgreen: '#00FA9A',
- mediumturquoise: '#48D1CC',
- mediumvioletred: '#C71585',
- midnightblue: '#191970',
- mintcream: '#F5FFFA',
- mistyrose: '#FFE4E1',
- moccasin: '#FFE4B5',
- navajowhite: '#FFDEAD',
- navy: '#000080',
- oldlace: '#FDF5E6',
- olive: '#808000',
- olivedrab: '#6B8E23',
- orange: '#FFA500',
- orangered: '#FF4500',
- orchid: '#DA70D6',
- palegoldenrod: '#EEE8AA',
- palegreen: '#98FB98',
- paleturquoise: '#AFEEEE',
- palevioletred: '#DB7093',
- papayawhip: '#FFEFD5',
- peachpuff: '#FFDAB9',
- peru: '#CD853F',
- pink: '#FFC0CB',
- plum: '#DDA0DD',
- powderblue: '#B0E0E6',
- purple: '#800080',
- rebeccapurple: '#663399',
- red: '#FF0000',
- rosybrown: '#BC8F8F',
- royalblue: '#4169E1',
- saddlebrown: '#8B4513',
- salmon: '#FA8072',
- sandybrown: '#F4A460',
- seagreen: '#2E8B57',
- seashell: '#FFF5EE',
- sienna: '#A0522D',
- silver: '#C0C0C0',
- skyblue: '#87CEEB',
- slateblue: '#6A5ACD',
- slategray: '#708090',
- slategrey: '#708090',
- snow: '#FFFAFA',
- springgreen: '#00FF7F',
- steelblue: '#4682B4',
- tan: '#D2B48C',
- teal: '#008080',
- thistle: '#D8BFD8',
- tomato: '#FF6347',
- turquoise: '#40E0D0',
- violet: '#EE82EE',
- wheat: '#F5DEB3',
- white: '#FFFFFF',
- whitesmoke: '#F5F5F5',
- yellow: '#FFFF00',
- yellowgreen: '#9ACD32'
- };
-
- /**
- * @private
- * @param {Number} p
- * @param {Number} q
- * @param {Number} t
- * @return {Number}
- */
- function hue2rgb(p, q, t) {
- if (t < 0) {
- t += 1;
- }
- if (t > 1) {
- t -= 1;
- }
- if (t < 1 / 6) {
- return p + (q - p) * 6 * t;
- }
- if (t < 1 / 2) {
- return q;
- }
- if (t < 2 / 3) {
- return p + (q - p) * (2 / 3 - t) * 6;
- }
- return p;
- }
-
- /**
- * Returns new color object, when given a color in RGB format
- * @memberOf fabric.Color
- * @param {String} color Color value ex: rgb(0-255,0-255,0-255)
- * @return {fabric.Color}
- */
- fabric.Color.fromRgb = function(color) {
- return Color.fromSource(Color.sourceFromRgb(color));
- };
-
- /**
- * Returns array representation (ex: [100, 100, 200, 1]) of a color that's in RGB or RGBA format
- * @memberOf fabric.Color
- * @param {String} color Color value ex: rgb(0-255,0-255,0-255), rgb(0%-100%,0%-100%,0%-100%)
- * @return {Array} source
- */
- fabric.Color.sourceFromRgb = function(color) {
- var match = color.match(Color.reRGBa);
- if (match) {
- var r = parseInt(match[1], 10) / (/%$/.test(match[1]) ? 100 : 1) * (/%$/.test(match[1]) ? 255 : 1),
- g = parseInt(match[2], 10) / (/%$/.test(match[2]) ? 100 : 1) * (/%$/.test(match[2]) ? 255 : 1),
- b = parseInt(match[3], 10) / (/%$/.test(match[3]) ? 100 : 1) * (/%$/.test(match[3]) ? 255 : 1);
-
- return [
- parseInt(r, 10),
- parseInt(g, 10),
- parseInt(b, 10),
- match[4] ? parseFloat(match[4]) : 1
- ];
- }
- };
-
- /**
- * Returns new color object, when given a color in RGBA format
- * @static
- * @function
- * @memberOf fabric.Color
- * @param {String} color
- * @return {fabric.Color}
- */
- fabric.Color.fromRgba = Color.fromRgb;
-
- /**
- * Returns new color object, when given a color in HSL format
- * @param {String} color Color value ex: hsl(0-260,0%-100%,0%-100%)
- * @memberOf fabric.Color
- * @return {fabric.Color}
- */
- fabric.Color.fromHsl = function(color) {
- return Color.fromSource(Color.sourceFromHsl(color));
- };
-
- /**
- * Returns array representation (ex: [100, 100, 200, 1]) of a color that's in HSL or HSLA format.
- * 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>
- * @memberOf fabric.Color
- * @param {String} color Color value ex: hsl(0-360,0%-100%,0%-100%) or hsla(0-360,0%-100%,0%-100%, 0-1)
- * @return {Array} source
- * @see http://http://www.w3.org/TR/css3-color/#hsl-color
- */
- fabric.Color.sourceFromHsl = function(color) {
- var match = color.match(Color.reHSLa);
- if (!match) {
- return;
- }
-
- var h = (((parseFloat(match[1]) % 360) + 360) % 360) / 360,
- s = parseFloat(match[2]) / (/%$/.test(match[2]) ? 100 : 1),
- l = parseFloat(match[3]) / (/%$/.test(match[3]) ? 100 : 1),
- r, g, b;
-
- if (s === 0) {
- r = g = b = l;
- }
- else {
- var q = l <= 0.5 ? l * (s + 1) : l + s - l * s,
- p = l * 2 - q;
-
- r = hue2rgb(p, q, h + 1 / 3);
- g = hue2rgb(p, q, h);
- b = hue2rgb(p, q, h - 1 / 3);
- }
-
- return [
- Math.round(r * 255),
- Math.round(g * 255),
- Math.round(b * 255),
- match[4] ? parseFloat(match[4]) : 1
- ];
- };
-
- /**
- * Returns new color object, when given a color in HSLA format
- * @static
- * @function
- * @memberOf fabric.Color
- * @param {String} color
- * @return {fabric.Color}
- */
- fabric.Color.fromHsla = Color.fromHsl;
-
- /**
- * Returns new color object, when given a color in HEX format
- * @static
- * @memberOf fabric.Color
- * @param {String} color Color value ex: FF5555
- * @return {fabric.Color}
- */
- fabric.Color.fromHex = function(color) {
- return Color.fromSource(Color.sourceFromHex(color));
- };
-
- /**
- * Returns array representation (ex: [100, 100, 200, 1]) of a color that's in HEX format
- * @static
- * @memberOf fabric.Color
- * @param {String} color ex: FF5555 or FF5544CC (RGBa)
- * @return {Array} source
- */
- fabric.Color.sourceFromHex = function(color) {
- if (color.match(Color.reHex)) {
- var value = color.slice(color.indexOf('#') + 1),
- isShortNotation = (value.length === 3 || value.length === 4),
- isRGBa = (value.length === 8 || value.length === 4),
- r = isShortNotation ? (value.charAt(0) + value.charAt(0)) : value.substring(0, 2),
- g = isShortNotation ? (value.charAt(1) + value.charAt(1)) : value.substring(2, 4),
- b = isShortNotation ? (value.charAt(2) + value.charAt(2)) : value.substring(4, 6),
- a = isRGBa ? (isShortNotation ? (value.charAt(3) + value.charAt(3)) : value.substring(6, 8)) : 'FF';
-
- return [
- parseInt(r, 16),
- parseInt(g, 16),
- parseInt(b, 16),
- parseFloat((parseInt(a, 16) / 255).toFixed(2))
- ];
- }
- };
-
- /**
- * Returns new color object, when given color in array representation (ex: [200, 100, 100, 0.5])
- * @static
- * @memberOf fabric.Color
- * @param {Array} source
- * @return {fabric.Color}
- */
- fabric.Color.fromSource = function(source) {
- var oColor = new Color();
- oColor.setSource(source);
- return oColor;
- };
-
-})(typeof exports !== 'undefined' ? exports : this);
-
-
-(function() {
-
- /* _FROM_SVG_START_ */
- function getColorStop(el, multiplier) {
- var style = el.getAttribute('style'),
- offset = el.getAttribute('offset') || 0,
- color, colorAlpha, opacity, i;
-
- // convert percents to absolute values
- offset = parseFloat(offset) / (/%$/.test(offset) ? 100 : 1);
- offset = offset < 0 ? 0 : offset > 1 ? 1 : offset;
- if (style) {
- var keyValuePairs = style.split(/\s*;\s*/);
-
- if (keyValuePairs[keyValuePairs.length - 1] === '') {
- keyValuePairs.pop();
- }
-
- for (i = keyValuePairs.length; i--; ) {
-
- var split = keyValuePairs[i].split(/\s*:\s*/),
- key = split[0].trim(),
- value = split[1].trim();
-
- if (key === 'stop-color') {
- color = value;
- }
- else if (key === 'stop-opacity') {
- opacity = value;
- }
- }
- }
-
- if (!color) {
- color = el.getAttribute('stop-color') || 'rgb(0,0,0)';
- }
- if (!opacity) {
- opacity = el.getAttribute('stop-opacity');
- }
-
- color = new fabric.Color(color);
- colorAlpha = color.getAlpha();
- opacity = isNaN(parseFloat(opacity)) ? 1 : parseFloat(opacity);
- opacity *= colorAlpha * multiplier;
-
- return {
- offset: offset,
- color: color.toRgb(),
- opacity: opacity
- };
- }
-
- function getLinearCoords(el) {
- return {
- x1: el.getAttribute('x1') || 0,
- y1: el.getAttribute('y1') || 0,
- x2: el.getAttribute('x2') || '100%',
- y2: el.getAttribute('y2') || 0
- };
- }
-
- function getRadialCoords(el) {
- return {
- x1: el.getAttribute('fx') || el.getAttribute('cx') || '50%',
- y1: el.getAttribute('fy') || el.getAttribute('cy') || '50%',
- r1: 0,
- x2: el.getAttribute('cx') || '50%',
- y2: el.getAttribute('cy') || '50%',
- r2: el.getAttribute('r') || '50%'
- };
- }
- /* _FROM_SVG_END_ */
-
- var clone = fabric.util.object.clone;
-
- /**
- * Gradient class
- * @class fabric.Gradient
- * @tutorial {@link http://fabricjs.com/fabric-intro-part-2#gradients}
- * @see {@link fabric.Gradient#initialize} for constructor definition
- */
- fabric.Gradient = fabric.util.createClass(/** @lends fabric.Gradient.prototype */ {
-
- /**
- * Horizontal offset for aligning gradients coming from SVG when outside pathgroups
- * @type Number
- * @default 0
- */
- offsetX: 0,
-
- /**
- * Vertical offset for aligning gradients coming from SVG when outside pathgroups
- * @type Number
- * @default 0
- */
- offsetY: 0,
-
- /**
- * A transform matrix to apply to the gradient before painting.
- * Imported from svg gradients, is not applied with the current transform in the center.
- * Before this transform is applied, the origin point is at the top left corner of the object
- * plus the addition of offsetY and offsetX.
- * @type Number[]
- * @default null
- */
- gradientTransform: null,
-
- /**
- * coordinates units for coords.
- * If `pixels`, the number of coords are in the same unit of width / height.
- * If set as `percentage` the coords are still a number, but 1 means 100% of width
- * for the X and 100% of the height for the y. It can be bigger than 1 and negative.
- * allowed values pixels or percentage.
- * @type String
- * @default 'pixels'
- */
- gradientUnits: 'pixels',
-
- /**
- * Gradient type linear or radial
- * @type String
- * @default 'pixels'
- */
- type: 'linear',
-
- /**
- * Constructor
- * @param {Object} options Options object with type, coords, gradientUnits and colorStops
- * @param {Object} [options.type] gradient type linear or radial
- * @param {Object} [options.gradientUnits] gradient units
- * @param {Object} [options.offsetX] SVG import compatibility
- * @param {Object} [options.offsetY] SVG import compatibility
- * @param {Object[]} options.colorStops contains the colorstops.
- * @param {Object} options.coords contains the coords of the gradient
- * @param {Number} [options.coords.x1] X coordiante of the first point for linear or of the focal point for radial
- * @param {Number} [options.coords.y1] Y coordiante of the first point for linear or of the focal point for radial
- * @param {Number} [options.coords.x2] X coordiante of the second point for linear or of the center point for radial
- * @param {Number} [options.coords.y2] Y coordiante of the second point for linear or of the center point for radial
- * @param {Number} [options.coords.r1] only for radial gradient, radius of the inner circle
- * @param {Number} [options.coords.r2] only for radial gradient, radius of the external circle
- * @return {fabric.Gradient} thisArg
- */
- initialize: function(options) {
- options || (options = { });
- options.coords || (options.coords = { });
-
- var coords, _this = this;
-
- // sets everything, then coords and colorstops get sets again
- Object.keys(options).forEach(function(option) {
- _this[option] = options[option];
- });
-
- if (this.id) {
- this.id += '_' + fabric.Object.__uid++;
- }
- else {
- this.id = fabric.Object.__uid++;
- }
-
- coords = {
- x1: options.coords.x1 || 0,
- y1: options.coords.y1 || 0,
- x2: options.coords.x2 || 0,
- y2: options.coords.y2 || 0
- };
-
- if (this.type === 'radial') {
- coords.r1 = options.coords.r1 || 0;
- coords.r2 = options.coords.r2 || 0;
- }
-
- this.coords = coords;
- this.colorStops = options.colorStops.slice();
- },
-
- /**
- * Adds another colorStop
- * @param {Object} colorStop Object with offset and color
- * @return {fabric.Gradient} thisArg
- */
- addColorStop: function(colorStops) {
- for (var position in colorStops) {
- var color = new fabric.Color(colorStops[position]);
- this.colorStops.push({
- offset: parseFloat(position),
- color: color.toRgb(),
- opacity: color.getAlpha()
- });
- }
- return this;
- },
-
- /**
- * Returns object representation of a gradient
- * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
- * @return {Object}
- */
- toObject: function(propertiesToInclude) {
- var object = {
- type: this.type,
- coords: this.coords,
- colorStops: this.colorStops,
- offsetX: this.offsetX,
- offsetY: this.offsetY,
- gradientUnits: this.gradientUnits,
- gradientTransform: this.gradientTransform ? this.gradientTransform.concat() : this.gradientTransform
- };
- fabric.util.populateWithProperties(this, object, propertiesToInclude);
-
- return object;
- },
-
- /* _TO_SVG_START_ */
- /**
- * Returns SVG representation of an gradient
- * @param {Object} object Object to create a gradient for
- * @return {String} SVG representation of an gradient (linear/radial)
- */
- toSVG: function(object, options) {
- var coords = clone(this.coords, true), i, len, options = options || {},
- markup, commonAttributes, colorStops = clone(this.colorStops, true),
- needsSwap = coords.r1 > coords.r2,
- transform = this.gradientTransform ? this.gradientTransform.concat() : fabric.iMatrix.concat(),
- offsetX = -this.offsetX, offsetY = -this.offsetY,
- withViewport = !!options.additionalTransform,
- gradientUnits = this.gradientUnits === 'pixels' ? 'userSpaceOnUse' : 'objectBoundingBox';
- // colorStops must be sorted ascending
- colorStops.sort(function(a, b) {
- return a.offset - b.offset;
- });
-
- if (gradientUnits === 'objectBoundingBox') {
- offsetX /= object.width;
- offsetY /= object.height;
- }
- else {
- offsetX += object.width / 2;
- offsetY += object.height / 2;
- }
- if (object.type === 'path') {
- offsetX -= object.pathOffset.x;
- offsetY -= object.pathOffset.y;
- }
-
-
- transform[4] -= offsetX;
- transform[5] -= offsetY;
-
- commonAttributes = 'id="SVGID_' + this.id +
- '" gradientUnits="' + gradientUnits + '"';
- commonAttributes += ' gradientTransform="' + (withViewport ?
- options.additionalTransform + ' ' : '') + fabric.util.matrixToSVG(transform) + '" ';
-
- if (this.type === 'linear') {
- markup = [
- '<linearGradient ',
- commonAttributes,
- ' x1="', coords.x1,
- '" y1="', coords.y1,
- '" x2="', coords.x2,
- '" y2="', coords.y2,
- '">\n'
- ];
- }
- else if (this.type === 'radial') {
- // svg radial gradient has just 1 radius. the biggest.
- markup = [
- '<radialGradient ',
- commonAttributes,
- ' cx="', needsSwap ? coords.x1 : coords.x2,
- '" cy="', needsSwap ? coords.y1 : coords.y2,
- '" r="', needsSwap ? coords.r1 : coords.r2,
- '" fx="', needsSwap ? coords.x2 : coords.x1,
- '" fy="', needsSwap ? coords.y2 : coords.y1,
- '">\n'
- ];
- }
-
- if (this.type === 'radial') {
- if (needsSwap) {
- // svg goes from internal to external radius. if radius are inverted, swap color stops.
- colorStops = colorStops.concat();
- colorStops.reverse();
- for (i = 0, len = colorStops.length; i < len; i++) {
- colorStops[i].offset = 1 - colorStops[i].offset;
- }
- }
- var minRadius = Math.min(coords.r1, coords.r2);
- if (minRadius > 0) {
- // i have to shift all colorStops and add new one in 0.
- var maxRadius = Math.max(coords.r1, coords.r2),
- percentageShift = minRadius / maxRadius;
- for (i = 0, len = colorStops.length; i < len; i++) {
- colorStops[i].offset += percentageShift * (1 - colorStops[i].offset);
- }
- }
- }
-
- for (i = 0, len = colorStops.length; i < len; i++) {
- var colorStop = colorStops[i];
- markup.push(
- '<stop ',
- 'offset="', (colorStop.offset * 100) + '%',
- '" style="stop-color:', colorStop.color,
- (typeof colorStop.opacity !== 'undefined' ? ';stop-opacity: ' + colorStop.opacity : ';'),
- '"/>\n'
- );
- }
-
- markup.push((this.type === 'linear' ? '</linearGradient>\n' : '</radialGradient>\n'));
-
- return markup.join('');
- },
- /* _TO_SVG_END_ */
-
- /**
- * Returns an instance of CanvasGradient
- * @param {CanvasRenderingContext2D} ctx Context to render on
- * @return {CanvasGradient}
- */
- toLive: function(ctx) {
- var gradient, coords = fabric.util.object.clone(this.coords), i, len;
-
- if (!this.type) {
- return;
- }
-
- if (this.type === 'linear') {
- gradient = ctx.createLinearGradient(
- coords.x1, coords.y1, coords.x2, coords.y2);
- }
- else if (this.type === 'radial') {
- gradient = ctx.createRadialGradient(
- coords.x1, coords.y1, coords.r1, coords.x2, coords.y2, coords.r2);
- }
-
- for (i = 0, len = this.colorStops.length; i < len; i++) {
- var color = this.colorStops[i].color,
- opacity = this.colorStops[i].opacity,
- offset = this.colorStops[i].offset;
-
- if (typeof opacity !== 'undefined') {
- color = new fabric.Color(color).setAlpha(opacity).toRgba();
- }
- gradient.addColorStop(offset, color);
- }
-
- return gradient;
- }
- });
-
- fabric.util.object.extend(fabric.Gradient, {
-
- /* _FROM_SVG_START_ */
- /**
- * Returns {@link fabric.Gradient} instance from an SVG element
- * @static
- * @memberOf fabric.Gradient
- * @param {SVGGradientElement} el SVG gradient element
- * @param {fabric.Object} instance
- * @param {String} opacityAttr A fill-opacity or stroke-opacity attribute to multiply to each stop's opacity.
- * @param {Object} svgOptions an object containing the size of the SVG in order to parse correctly graidents
- * that uses gradientUnits as 'userSpaceOnUse' and percentages.
- * @param {Object.number} viewBoxWidth width part of the viewBox attribute on svg
- * @param {Object.number} viewBoxHeight height part of the viewBox attribute on svg
- * @param {Object.number} width width part of the svg tag if viewBox is not specified
- * @param {Object.number} height height part of the svg tag if viewBox is not specified
- * @return {fabric.Gradient} Gradient instance
- * @see http://www.w3.org/TR/SVG/pservers.html#LinearGradientElement
- * @see http://www.w3.org/TR/SVG/pservers.html#RadialGradientElement
- */
- fromElement: function(el, instance, opacityAttr, svgOptions) {
- /**
- * @example:
- *
- * <linearGradient id="linearGrad1">
- * <stop offset="0%" stop-color="white"/>
- * <stop offset="100%" stop-color="black"/>
- * </linearGradient>
- *
- * OR
- *
- * <linearGradient id="linearGrad2">
- * <stop offset="0" style="stop-color:rgb(255,255,255)"/>
- * <stop offset="1" style="stop-color:rgb(0,0,0)"/>
- * </linearGradient>
- *
- * OR
- *
- * <radialGradient id="radialGrad1">
- * <stop offset="0%" stop-color="white" stop-opacity="1" />
- * <stop offset="50%" stop-color="black" stop-opacity="0.5" />
- * <stop offset="100%" stop-color="white" stop-opacity="1" />
- * </radialGradient>
- *
- * OR
- *
- * <radialGradient id="radialGrad2">
- * <stop offset="0" stop-color="rgb(255,255,255)" />
- * <stop offset="0.5" stop-color="rgb(0,0,0)" />
- * <stop offset="1" stop-color="rgb(255,255,255)" />
- * </radialGradient>
- *
- */
-
- var multiplier = parseFloat(opacityAttr) / (/%$/.test(opacityAttr) ? 100 : 1);
- multiplier = multiplier < 0 ? 0 : multiplier > 1 ? 1 : multiplier;
- if (isNaN(multiplier)) {
- multiplier = 1;
- }
-
- var colorStopEls = el.getElementsByTagName('stop'),
- type,
- gradientUnits = el.getAttribute('gradientUnits') === 'userSpaceOnUse' ?
- 'pixels' : 'percentage',
- gradientTransform = el.getAttribute('gradientTransform') || '',
- colorStops = [],
- coords, i, offsetX = 0, offsetY = 0,
- transformMatrix;
- if (el.nodeName === 'linearGradient' || el.nodeName === 'LINEARGRADIENT') {
- type = 'linear';
- coords = getLinearCoords(el);
- }
- else {
- type = 'radial';
- coords = getRadialCoords(el);
- }
-
- for (i = colorStopEls.length; i--; ) {
- colorStops.push(getColorStop(colorStopEls[i], multiplier));
- }
-
- transformMatrix = fabric.parseTransformAttribute(gradientTransform);
-
- __convertPercentUnitsToValues(instance, coords, svgOptions, gradientUnits);
-
- if (gradientUnits === 'pixels') {
- offsetX = -instance.left;
- offsetY = -instance.top;
- }
-
- var gradient = new fabric.Gradient({
- id: el.getAttribute('id'),
- type: type,
- coords: coords,
- colorStops: colorStops,
- gradientUnits: gradientUnits,
- gradientTransform: transformMatrix,
- offsetX: offsetX,
- offsetY: offsetY,
- });
-
- return gradient;
- },
- /* _FROM_SVG_END_ */
-
- /**
- * Returns {@link fabric.Gradient} instance from its object representation
- * this function is uniquely used by Object.setGradient and is deprecated with it.
- * @static
- * @deprecated since 3.4.0
- * @memberOf fabric.Gradient
- * @param {Object} obj
- * @param {Object} [options] Options object
- */
- forObject: function(obj, options) {
- options || (options = { });
- __convertPercentUnitsToValues(obj, options.coords, options.gradientUnits, {
- // those values are to avoid errors. this function is uniquely used by
- viewBoxWidth: 100,
- viewBoxHeight: 100,
- });
- return new fabric.Gradient(options);
- }
- });
-
- /**
- * @private
- */
- function __convertPercentUnitsToValues(instance, options, svgOptions, gradientUnits) {
- var propValue, finalValue;
- Object.keys(options).forEach(function(prop) {
- propValue = options[prop];
- if (propValue === 'Infinity') {
- finalValue = 1;
- }
- else if (propValue === '-Infinity') {
- finalValue = 0;
- }
- else {
- finalValue = parseFloat(options[prop], 10);
- if (typeof propValue === 'string' && /^(\d+\.\d+)%|(\d+)%$/.test(propValue)) {
- finalValue *= 0.01;
- if (gradientUnits === 'pixels') {
- // then we need to fix those percentages here in svg parsing
- if (prop === 'x1' || prop === 'x2' || prop === 'r2') {
- finalValue *= svgOptions.viewBoxWidth || svgOptions.width;
- }
- if (prop === 'y1' || prop === 'y2') {
- finalValue *= svgOptions.viewBoxHeight || svgOptions.height;
- }
- }
- }
- }
- options[prop] = finalValue;
- });
- }
-})();
-
-
-(function() {
-
- 'use strict';
-
- var toFixed = fabric.util.toFixed;
-
- /**
- * Pattern class
- * @class fabric.Pattern
- * @see {@link http://fabricjs.com/patterns|Pattern demo}
- * @see {@link http://fabricjs.com/dynamic-patterns|DynamicPattern demo}
- * @see {@link fabric.Pattern#initialize} for constructor definition
- */
-
-
- fabric.Pattern = fabric.util.createClass(/** @lends fabric.Pattern.prototype */ {
-
- /**
- * Repeat property of a pattern (one of repeat, repeat-x, repeat-y or no-repeat)
- * @type String
- * @default
- */
- repeat: 'repeat',
-
- /**
- * Pattern horizontal offset from object's left/top corner
- * @type Number
- * @default
- */
- offsetX: 0,
-
- /**
- * Pattern vertical offset from object's left/top corner
- * @type Number
- * @default
- */
- offsetY: 0,
-
- /**
- * crossOrigin value (one of "", "anonymous", "use-credentials")
- * @see https://developer.mozilla.org/en-US/docs/HTML/CORS_settings_attributes
- * @type String
- * @default
- */
- crossOrigin: '',
-
- /**
- * transform matrix to change the pattern, imported from svgs.
- * @type Array
- * @default
- */
- patternTransform: null,
-
- /**
- * Constructor
- * @param {Object} [options] Options object
- * @param {Function} [callback] function to invoke after callback init.
- * @return {fabric.Pattern} thisArg
- */
- initialize: function(options, callback) {
- options || (options = { });
-
- this.id = fabric.Object.__uid++;
- this.setOptions(options);
- if (!options.source || (options.source && typeof options.source !== 'string')) {
- callback && callback(this);
- return;
- }
- // function string
- if (typeof fabric.util.getFunctionBody(options.source) !== 'undefined') {
- this.source = new Function(fabric.util.getFunctionBody(options.source));
- callback && callback(this);
- }
- else {
- // img src string
- var _this = this;
- this.source = fabric.util.createImage();
- fabric.util.loadImage(options.source, function(img) {
- _this.source = img;
- callback && callback(_this);
- }, null, this.crossOrigin);
- }
- },
-
- /**
- * Returns object representation of a pattern
- * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
- * @return {Object} Object representation of a pattern instance
- */
- toObject: function(propertiesToInclude) {
- var NUM_FRACTION_DIGITS = fabric.Object.NUM_FRACTION_DIGITS,
- source, object;
-
- // callback
- if (typeof this.source === 'function') {
- source = String(this.source);
- }
- // <img> element
- else if (typeof this.source.src === 'string') {
- source = this.source.src;
- }
- // <canvas> element
- else if (typeof this.source === 'object' && this.source.toDataURL) {
- source = this.source.toDataURL();
- }
-
- object = {
- type: 'pattern',
- source: source,
- repeat: this.repeat,
- crossOrigin: this.crossOrigin,
- offsetX: toFixed(this.offsetX, NUM_FRACTION_DIGITS),
- offsetY: toFixed(this.offsetY, NUM_FRACTION_DIGITS),
- patternTransform: this.patternTransform ? this.patternTransform.concat() : null
- };
- fabric.util.populateWithProperties(this, object, propertiesToInclude);
-
- return object;
- },
-
- /* _TO_SVG_START_ */
- /**
- * Returns SVG representation of a pattern
- * @param {fabric.Object} object
- * @return {String} SVG representation of a pattern
- */
- toSVG: function(object) {
- var patternSource = typeof this.source === 'function' ? this.source() : this.source,
- patternWidth = patternSource.width / object.width,
- patternHeight = patternSource.height / object.height,
- patternOffsetX = this.offsetX / object.width,
- patternOffsetY = this.offsetY / object.height,
- patternImgSrc = '';
- if (this.repeat === 'repeat-x' || this.repeat === 'no-repeat') {
- patternHeight = 1;
- if (patternOffsetY) {
- patternHeight += Math.abs(patternOffsetY);
- }
- }
- if (this.repeat === 'repeat-y' || this.repeat === 'no-repeat') {
- patternWidth = 1;
- if (patternOffsetX) {
- patternWidth += Math.abs(patternOffsetX);
- }
-
- }
- if (patternSource.src) {
- patternImgSrc = patternSource.src;
- }
- else if (patternSource.toDataURL) {
- patternImgSrc = patternSource.toDataURL();
- }
-
- return '<pattern id="SVGID_' + this.id +
- '" x="' + patternOffsetX +
- '" y="' + patternOffsetY +
- '" width="' + patternWidth +
- '" height="' + patternHeight + '">\n' +
- '<image x="0" y="0"' +
- ' width="' + patternSource.width +
- '" height="' + patternSource.height +
- '" xlink:href="' + patternImgSrc +
- '"></image>\n' +
- '</pattern>\n';
- },
- /* _TO_SVG_END_ */
-
- setOptions: function(options) {
- for (var prop in options) {
- this[prop] = options[prop];
- }
- },
-
- /**
- * Returns an instance of CanvasPattern
- * @param {CanvasRenderingContext2D} ctx Context to create pattern
- * @return {CanvasPattern}
- */
- toLive: function(ctx) {
- var source = typeof this.source === 'function' ? this.source() : this.source;
-
- // if the image failed to load, return, and allow rest to continue loading
- if (!source) {
- return '';
- }
-
- // if an image
- if (typeof source.src !== 'undefined') {
- if (!source.complete) {
- return '';
- }
- if (source.naturalWidth === 0 || source.naturalHeight === 0) {
- return '';
- }
- }
- return ctx.createPattern(source, this.repeat);
- }
- });
-})();
-
-
-(function(global) {
-
- 'use strict';
-
- var fabric = global.fabric || (global.fabric = { }),
- toFixed = fabric.util.toFixed;
-
- if (fabric.Shadow) {
- fabric.warn('fabric.Shadow is already defined.');
- return;
- }
-
- /**
- * Shadow class
- * @class fabric.Shadow
- * @see {@link http://fabricjs.com/shadows|Shadow demo}
- * @see {@link fabric.Shadow#initialize} for constructor definition
- */
- fabric.Shadow = fabric.util.createClass(/** @lends fabric.Shadow.prototype */ {
-
- /**
- * Shadow color
- * @type String
- * @default
- */
- color: 'rgb(0,0,0)',
-
- /**
- * Shadow blur
- * @type Number
- */
- blur: 0,
-
- /**
- * Shadow horizontal offset
- * @type Number
- * @default
- */
- offsetX: 0,
-
- /**
- * Shadow vertical offset
- * @type Number
- * @default
- */
- offsetY: 0,
-
- /**
- * Whether the shadow should affect stroke operations
- * @type Boolean
- * @default
- */
- affectStroke: false,
-
- /**
- * Indicates whether toObject should include default values
- * @type Boolean
- * @default
- */
- includeDefaultValues: true,
-
- /**
- * When `false`, the shadow will scale with the object.
- * When `true`, the shadow's offsetX, offsetY, and blur will not be affected by the object's scale.
- * default to false
- * @type Boolean
- * @default
- */
- nonScaling: false,
-
- /**
- * Constructor
- * @param {Object|String} [options] Options object with any of color, blur, offsetX, offsetY properties or string (e.g. "rgba(0,0,0,0.2) 2px 2px 10px")
- * @return {fabric.Shadow} thisArg
- */
- initialize: function(options) {
-
- if (typeof options === 'string') {
- options = this._parseShadow(options);
- }
-
- for (var prop in options) {
- this[prop] = options[prop];
- }
-
- this.id = fabric.Object.__uid++;
- },
-
- /**
- * @private
- * @param {String} shadow Shadow value to parse
- * @return {Object} Shadow object with color, offsetX, offsetY and blur
- */
- _parseShadow: function(shadow) {
- var shadowStr = shadow.trim(),
- offsetsAndBlur = fabric.Shadow.reOffsetsAndBlur.exec(shadowStr) || [],
- color = shadowStr.replace(fabric.Shadow.reOffsetsAndBlur, '') || 'rgb(0,0,0)';
-
- return {
- color: color.trim(),
- offsetX: parseInt(offsetsAndBlur[1], 10) || 0,
- offsetY: parseInt(offsetsAndBlur[2], 10) || 0,
- blur: parseInt(offsetsAndBlur[3], 10) || 0
- };
- },
-
- /**
- * Returns a string representation of an instance
- * @see http://www.w3.org/TR/css-text-decor-3/#text-shadow
- * @return {String} Returns CSS3 text-shadow declaration
- */
- toString: function() {
- return [this.offsetX, this.offsetY, this.blur, this.color].join('px ');
- },
-
- /* _TO_SVG_START_ */
- /**
- * Returns SVG representation of a shadow
- * @param {fabric.Object} object
- * @return {String} SVG representation of a shadow
- */
- toSVG: function(object) {
- var fBoxX = 40, fBoxY = 40, NUM_FRACTION_DIGITS = fabric.Object.NUM_FRACTION_DIGITS,
- offset = fabric.util.rotateVector(
- { x: this.offsetX, y: this.offsetY },
- fabric.util.degreesToRadians(-object.angle)),
- BLUR_BOX = 20, color = new fabric.Color(this.color);
-
- if (object.width && object.height) {
- //http://www.w3.org/TR/SVG/filters.html#FilterEffectsRegion
- // we add some extra space to filter box to contain the blur ( 20 )
- fBoxX = toFixed((Math.abs(offset.x) + this.blur) / object.width, NUM_FRACTION_DIGITS) * 100 + BLUR_BOX;
- fBoxY = toFixed((Math.abs(offset.y) + this.blur) / object.height, NUM_FRACTION_DIGITS) * 100 + BLUR_BOX;
- }
- if (object.flipX) {
- offset.x *= -1;
- }
- if (object.flipY) {
- offset.y *= -1;
- }
-
- return (
- '<filter id="SVGID_' + this.id + '" y="-' + fBoxY + '%" height="' + (100 + 2 * fBoxY) + '%" ' +
- 'x="-' + fBoxX + '%" width="' + (100 + 2 * fBoxX) + '%" ' + '>\n' +
- '\t<feGaussianBlur in="SourceAlpha" stdDeviation="' +
- toFixed(this.blur ? this.blur / 2 : 0, NUM_FRACTION_DIGITS) + '"></feGaussianBlur>\n' +
- '\t<feOffset dx="' + toFixed(offset.x, NUM_FRACTION_DIGITS) +
- '" dy="' + toFixed(offset.y, NUM_FRACTION_DIGITS) + '" result="oBlur" ></feOffset>\n' +
- '\t<feFlood flood-color="' + color.toRgb() + '" flood-opacity="' + color.getAlpha() + '"/>\n' +
- '\t<feComposite in2="oBlur" operator="in" />\n' +
- '\t<feMerge>\n' +
- '\t\t<feMergeNode></feMergeNode>\n' +
- '\t\t<feMergeNode in="SourceGraphic"></feMergeNode>\n' +
- '\t</feMerge>\n' +
- '</filter>\n');
- },
- /* _TO_SVG_END_ */
-
- /**
- * Returns object representation of a shadow
- * @return {Object} Object representation of a shadow instance
- */
- toObject: function() {
- if (this.includeDefaultValues) {
- return {
- color: this.color,
- blur: this.blur,
- offsetX: this.offsetX,
- offsetY: this.offsetY,
- affectStroke: this.affectStroke,
- nonScaling: this.nonScaling
- };
- }
- var obj = { }, proto = fabric.Shadow.prototype;
-
- ['color', 'blur', 'offsetX', 'offsetY', 'affectStroke', 'nonScaling'].forEach(function(prop) {
- if (this[prop] !== proto[prop]) {
- obj[prop] = this[prop];
- }
- }, this);
-
- return obj;
- }
- });
-
- /**
- * Regex matching shadow offsetX, offsetY and blur (ex: "2px 2px 10px rgba(0,0,0,0.2)", "rgb(0,255,0) 2px 2px")
- * @static
- * @field
- * @memberOf fabric.Shadow
- */
- // eslint-disable-next-line max-len
- fabric.Shadow.reOffsetsAndBlur = /(?:\s|^)(-?\d+(?:px)?(?:\s?|$))?(-?\d+(?:px)?(?:\s?|$))?(\d+(?:px)?)?(?:\s?|$)(?:$|\s)/;
-
-})(typeof exports !== 'undefined' ? exports : this);
-
-
-(function () {
-
- 'use strict';
-
- if (fabric.StaticCanvas) {
- fabric.warn('fabric.StaticCanvas is already defined.');
- return;
- }
-
- // aliases for faster resolution
- var extend = fabric.util.object.extend,
- getElementOffset = fabric.util.getElementOffset,
- removeFromArray = fabric.util.removeFromArray,
- toFixed = fabric.util.toFixed,
- transformPoint = fabric.util.transformPoint,
- invertTransform = fabric.util.invertTransform,
- getNodeCanvas = fabric.util.getNodeCanvas,
- createCanvasElement = fabric.util.createCanvasElement,
-
- CANVAS_INIT_ERROR = new Error('Could not initialize `canvas` element');
-
- /**
- * Static canvas class
- * @class fabric.StaticCanvas
- * @mixes fabric.Collection
- * @mixes fabric.Observable
- * @see {@link http://fabricjs.com/static_canvas|StaticCanvas demo}
- * @see {@link fabric.StaticCanvas#initialize} for constructor definition
- * @fires before:render
- * @fires after:render
- * @fires canvas:cleared
- * @fires object:added
- * @fires object:removed
- */
- fabric.StaticCanvas = fabric.util.createClass(fabric.CommonMethods, /** @lends fabric.StaticCanvas.prototype */ {
-
- /**
- * Constructor
- * @param {HTMLElement | String} el <canvas> element to initialize instance on
- * @param {Object} [options] Options object
- * @return {Object} thisArg
- */
- initialize: function(el, options) {
- options || (options = { });
- this.renderAndResetBound = this.renderAndReset.bind(this);
- this.requestRenderAllBound = this.requestRenderAll.bind(this);
- this._initStatic(el, options);
- },
-
- /**
- * Background color of canvas instance.
- * Should be set via {@link fabric.StaticCanvas#setBackgroundColor}.
- * @type {(String|fabric.Pattern)}
- * @default
- */
- backgroundColor: '',
-
- /**
- * Background image of canvas instance.
- * Should be set via {@link fabric.StaticCanvas#setBackgroundImage}.
- * <b>Backwards incompatibility note:</b> The "backgroundImageOpacity"
- * and "backgroundImageStretch" properties are deprecated since 1.3.9.
- * Use {@link fabric.Image#opacity}, {@link fabric.Image#width} and {@link fabric.Image#height}.
- * since 2.4.0 image caching is active, please when putting an image as background, add to the
- * canvas property a reference to the canvas it is on. Otherwise the image cannot detect the zoom
- * vale. As an alternative you can disable image objectCaching
- * @type fabric.Image
- * @default
- */
- backgroundImage: null,
-
- /**
- * Overlay color of canvas instance.
- * Should be set via {@link fabric.StaticCanvas#setOverlayColor}
- * @since 1.3.9
- * @type {(String|fabric.Pattern)}
- * @default
- */
- overlayColor: '',
-
- /**
- * Overlay image of canvas instance.
- * Should be set via {@link fabric.StaticCanvas#setOverlayImage}.
- * <b>Backwards incompatibility note:</b> The "overlayImageLeft"
- * and "overlayImageTop" properties are deprecated since 1.3.9.
- * Use {@link fabric.Image#left} and {@link fabric.Image#top}.
- * since 2.4.0 image caching is active, please when putting an image as overlay, add to the
- * canvas property a reference to the canvas it is on. Otherwise the image cannot detect the zoom
- * vale. As an alternative you can disable image objectCaching
- * @type fabric.Image
- * @default
- */
- overlayImage: null,
-
- /**
- * Indicates whether toObject/toDatalessObject should include default values
- * if set to false, takes precedence over the object value.
- * @type Boolean
- * @default
- */
- includeDefaultValues: true,
-
- /**
- * Indicates whether objects' state should be saved
- * @type Boolean
- * @default
- */
- stateful: false,
-
- /**
- * Indicates whether {@link fabric.Collection.add}, {@link fabric.Collection.insertAt} and {@link fabric.Collection.remove},
- * {@link fabric.StaticCanvas.moveTo}, {@link fabric.StaticCanvas.clear} and many more, should also re-render canvas.
- * Disabling this option will not give a performance boost when adding/removing a lot of objects to/from canvas at once
- * since the renders are quequed and executed one per frame.
- * Disabling is suggested anyway and managing the renders of the app manually is not a big effort ( canvas.requestRenderAll() )
- * Left default to true to do not break documentation and old app, fiddles.
- * @type Boolean
- * @default
- */
- renderOnAddRemove: true,
-
- /**
- * Function that determines clipping of entire canvas area
- * Being passed context as first argument.
- * If you are using code minification, ctx argument can be minified/manglied you should use
- * as a workaround `var ctx = arguments[0];` in the function;
- * See clipping canvas area in {@link https://github.com/kangax/fabric.js/wiki/FAQ}
- * @deprecated since 2.0.0
- * @type Function
- * @default
- */
- clipTo: null,
-
- /**
- * Indicates whether object controls (borders/controls) are rendered above overlay image
- * @type Boolean
- * @default
- */
- controlsAboveOverlay: false,
-
- /**
- * Indicates whether the browser can be scrolled when using a touchscreen and dragging on the canvas
- * @type Boolean
- * @default
- */
- allowTouchScrolling: false,
-
- /**
- * Indicates whether this canvas will use image smoothing, this is on by default in browsers
- * @type Boolean
- * @default
- */
- imageSmoothingEnabled: true,
-
- /**
- * The transformation (in the format of Canvas transform) which focuses the viewport
- * @type Array
- * @default
- */
- viewportTransform: fabric.iMatrix.concat(),
-
- /**
- * if set to false background image is not affected by viewport transform
- * @since 1.6.3
- * @type Boolean
- * @default
- */
- backgroundVpt: true,
-
- /**
- * if set to false overlya image is not affected by viewport transform
- * @since 1.6.3
- * @type Boolean
- * @default
- */
- overlayVpt: true,
-
- /**
- * Callback; invoked right before object is about to be scaled/rotated
- * @deprecated since 2.3.0
- * Use before:transform event
- */
- onBeforeScaleRotate: function () {
- /* NOOP */
- },
-
- /**
- * When true, canvas is scaled by devicePixelRatio for better rendering on retina screens
- * @type Boolean
- * @default
- */
- enableRetinaScaling: true,
-
- /**
- * Describe canvas element extension over design
- * properties are tl,tr,bl,br.
- * if canvas is not zoomed/panned those points are the four corner of canvas
- * if canvas is viewportTransformed you those points indicate the extension
- * of canvas element in plain untrasformed coordinates
- * The coordinates get updated with @method calcViewportBoundaries.
- * @memberOf fabric.StaticCanvas.prototype
- */
- vptCoords: { },
-
- /**
- * Based on vptCoords and object.aCoords, skip rendering of objects that
- * are not included in current viewport.
- * May greatly help in applications with crowded canvas and use of zoom/pan
- * If One of the corner of the bounding box of the object is on the canvas
- * the objects get rendered.
- * @memberOf fabric.StaticCanvas.prototype
- * @type Boolean
- * @default
- */
- skipOffscreen: true,
-
- /**
- * a fabricObject that, without stroke define a clipping area with their shape. filled in black
- * the clipPath object gets used when the canvas has rendered, and the context is placed in the
- * top left corner of the canvas.
- * clipPath will clip away controls, if you do not want this to happen use controlsAboveOverlay = true
- * @type fabric.Object
- */
- clipPath: undefined,
-
- /**
- * @private
- * @param {HTMLElement | String} el <canvas> element to initialize instance on
- * @param {Object} [options] Options object
- */
- _initStatic: function(el, options) {
- var cb = this.requestRenderAllBound;
- this._objects = [];
- this._createLowerCanvas(el);
- this._initOptions(options);
- this._setImageSmoothing();
- // only initialize retina scaling once
- if (!this.interactive) {
- this._initRetinaScaling();
- }
-
- if (options.overlayImage) {
- this.setOverlayImage(options.overlayImage, cb);
- }
- if (options.backgroundImage) {
- this.setBackgroundImage(options.backgroundImage, cb);
- }
- if (options.backgroundColor) {
- this.setBackgroundColor(options.backgroundColor, cb);
- }
- if (options.overlayColor) {
- this.setOverlayColor(options.overlayColor, cb);
- }
- this.calcOffset();
- },
-
- /**
- * @private
- */
- _isRetinaScaling: function() {
- return (fabric.devicePixelRatio !== 1 && this.enableRetinaScaling);
- },
-
- /**
- * @private
- * @return {Number} retinaScaling if applied, otherwise 1;
- */
- getRetinaScaling: function() {
- return this._isRetinaScaling() ? fabric.devicePixelRatio : 1;
- },
-
- /**
- * @private
- */
- _initRetinaScaling: function() {
- if (!this._isRetinaScaling()) {
- return;
- }
- var scaleRatio = fabric.devicePixelRatio;
- this.__initRetinaScaling(scaleRatio, this.lowerCanvasEl, this.contextContainer);
- if (this.upperCanvasEl) {
- this.__initRetinaScaling(scaleRatio, this.upperCanvasEl, this.contextTop);
- }
- },
-
- __initRetinaScaling: function(scaleRatio, canvas, context) {
- canvas.setAttribute('width', this.width * scaleRatio);
- canvas.setAttribute('height', this.height * scaleRatio);
- context.scale(scaleRatio, scaleRatio);
- },
-
-
- /**
- * Calculates canvas element offset relative to the document
- * This method is also attached as "resize" event handler of window
- * @return {fabric.Canvas} instance
- * @chainable
- */
- calcOffset: function () {
- this._offset = getElementOffset(this.lowerCanvasEl);
- return this;
- },
-
- /**
- * Sets {@link fabric.StaticCanvas#overlayImage|overlay image} for this canvas
- * @param {(fabric.Image|String)} image fabric.Image instance or URL of an image to set overlay to
- * @param {Function} callback callback to invoke when image is loaded and set as an overlay
- * @param {Object} [options] Optional options to set for the {@link fabric.Image|overlay image}.
- * @return {fabric.Canvas} thisArg
- * @chainable
- * @see {@link http://jsfiddle.net/fabricjs/MnzHT/|jsFiddle demo}
- * @example <caption>Normal overlayImage with left/top = 0</caption>
- * canvas.setOverlayImage('http://fabricjs.com/assets/jail_cell_bars.png', canvas.renderAll.bind(canvas), {
- * // Needed to position overlayImage at 0/0
- * originX: 'left',
- * originY: 'top'
- * });
- * @example <caption>overlayImage with different properties</caption>
- * canvas.setOverlayImage('http://fabricjs.com/assets/jail_cell_bars.png', canvas.renderAll.bind(canvas), {
- * opacity: 0.5,
- * angle: 45,
- * left: 400,
- * top: 400,
- * originX: 'left',
- * originY: 'top'
- * });
- * @example <caption>Stretched overlayImage #1 - width/height correspond to canvas width/height</caption>
- * fabric.Image.fromURL('http://fabricjs.com/assets/jail_cell_bars.png', function(img) {
- * img.set({width: canvas.width, height: canvas.height, originX: 'left', originY: 'top'});
- * canvas.setOverlayImage(img, canvas.renderAll.bind(canvas));
- * });
- * @example <caption>Stretched overlayImage #2 - width/height correspond to canvas width/height</caption>
- * canvas.setOverlayImage('http://fabricjs.com/assets/jail_cell_bars.png', canvas.renderAll.bind(canvas), {
- * width: canvas.width,
- * height: canvas.height,
- * // Needed to position overlayImage at 0/0
- * originX: 'left',
- * originY: 'top'
- * });
- * @example <caption>overlayImage loaded from cross-origin</caption>
- * canvas.setOverlayImage('http://fabricjs.com/assets/jail_cell_bars.png', canvas.renderAll.bind(canvas), {
- * opacity: 0.5,
- * angle: 45,
- * left: 400,
- * top: 400,
- * originX: 'left',
- * originY: 'top',
- * crossOrigin: 'anonymous'
- * });
- */
- setOverlayImage: function (image, callback, options) {
- return this.__setBgOverlayImage('overlayImage', image, callback, options);
- },
-
- /**
- * Sets {@link fabric.StaticCanvas#backgroundImage|background image} for this canvas
- * @param {(fabric.Image|String)} image fabric.Image instance or URL of an image to set background to
- * @param {Function} callback Callback to invoke when image is loaded and set as background
- * @param {Object} [options] Optional options to set for the {@link fabric.Image|background image}.
- * @return {fabric.Canvas} thisArg
- * @chainable
- * @see {@link http://jsfiddle.net/djnr8o7a/28/|jsFiddle demo}
- * @example <caption>Normal backgroundImage with left/top = 0</caption>
- * canvas.setBackgroundImage('http://fabricjs.com/assets/honey_im_subtle.png', canvas.renderAll.bind(canvas), {
- * // Needed to position backgroundImage at 0/0
- * originX: 'left',
- * originY: 'top'
- * });
- * @example <caption>backgroundImage with different properties</caption>
- * canvas.setBackgroundImage('http://fabricjs.com/assets/honey_im_subtle.png', canvas.renderAll.bind(canvas), {
- * opacity: 0.5,
- * angle: 45,
- * left: 400,
- * top: 400,
- * originX: 'left',
- * originY: 'top'
- * });
- * @example <caption>Stretched backgroundImage #1 - width/height correspond to canvas width/height</caption>
- * fabric.Image.fromURL('http://fabricjs.com/assets/honey_im_subtle.png', function(img) {
- * img.set({width: canvas.width, height: canvas.height, originX: 'left', originY: 'top'});
- * canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas));
- * });
- * @example <caption>Stretched backgroundImage #2 - width/height correspond to canvas width/height</caption>
- * canvas.setBackgroundImage('http://fabricjs.com/assets/honey_im_subtle.png', canvas.renderAll.bind(canvas), {
- * width: canvas.width,
- * height: canvas.height,
- * // Needed to position backgroundImage at 0/0
- * originX: 'left',
- * originY: 'top'
- * });
- * @example <caption>backgroundImage loaded from cross-origin</caption>
- * canvas.setBackgroundImage('http://fabricjs.com/assets/honey_im_subtle.png', canvas.renderAll.bind(canvas), {
- * opacity: 0.5,
- * angle: 45,
- * left: 400,
- * top: 400,
- * originX: 'left',
- * originY: 'top',
- * crossOrigin: 'anonymous'
- * });
- */
- // TODO: fix stretched examples
- setBackgroundImage: function (image, callback, options) {
- return this.__setBgOverlayImage('backgroundImage', image, callback, options);
- },
-
- /**
- * Sets {@link fabric.StaticCanvas#overlayColor|foreground color} for this canvas
- * @param {(String|fabric.Pattern)} overlayColor Color or pattern to set foreground color to
- * @param {Function} callback Callback to invoke when foreground color is set
- * @return {fabric.Canvas} thisArg
- * @chainable
- * @see {@link http://jsfiddle.net/fabricjs/pB55h/|jsFiddle demo}
- * @example <caption>Normal overlayColor - color value</caption>
- * canvas.setOverlayColor('rgba(255, 73, 64, 0.6)', canvas.renderAll.bind(canvas));
- * @example <caption>fabric.Pattern used as overlayColor</caption>
- * canvas.setOverlayColor({
- * source: 'http://fabricjs.com/assets/escheresque_ste.png'
- * }, canvas.renderAll.bind(canvas));
- * @example <caption>fabric.Pattern used as overlayColor with repeat and offset</caption>
- * canvas.setOverlayColor({
- * source: 'http://fabricjs.com/assets/escheresque_ste.png',
- * repeat: 'repeat',
- * offsetX: 200,
- * offsetY: 100
- * }, canvas.renderAll.bind(canvas));
- */
- setOverlayColor: function(overlayColor, callback) {
- return this.__setBgOverlayColor('overlayColor', overlayColor, callback);
- },
-
- /**
- * Sets {@link fabric.StaticCanvas#backgroundColor|background color} for this canvas
- * @param {(String|fabric.Pattern)} backgroundColor Color or pattern to set background color to
- * @param {Function} callback Callback to invoke when background color is set
- * @return {fabric.Canvas} thisArg
- * @chainable
- * @see {@link http://jsfiddle.net/fabricjs/hXzvk/|jsFiddle demo}
- * @example <caption>Normal backgroundColor - color value</caption>
- * canvas.setBackgroundColor('rgba(255, 73, 64, 0.6)', canvas.renderAll.bind(canvas));
- * @example <caption>fabric.Pattern used as backgroundColor</caption>
- * canvas.setBackgroundColor({
- * source: 'http://fabricjs.com/assets/escheresque_ste.png'
- * }, canvas.renderAll.bind(canvas));
- * @example <caption>fabric.Pattern used as backgroundColor with repeat and offset</caption>
- * canvas.setBackgroundColor({
- * source: 'http://fabricjs.com/assets/escheresque_ste.png',
- * repeat: 'repeat',
- * offsetX: 200,
- * offsetY: 100
- * }, canvas.renderAll.bind(canvas));
- */
- setBackgroundColor: function(backgroundColor, callback) {
- return this.__setBgOverlayColor('backgroundColor', backgroundColor, callback);
- },
-
- /**
- * @private
- * @see {@link http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-context-2d-imagesmoothingenabled|WhatWG Canvas Standard}
- */
- _setImageSmoothing: function() {
- var ctx = this.getContext();
-
- ctx.imageSmoothingEnabled = ctx.imageSmoothingEnabled || ctx.webkitImageSmoothingEnabled
- || ctx.mozImageSmoothingEnabled || ctx.msImageSmoothingEnabled || ctx.oImageSmoothingEnabled;
- ctx.imageSmoothingEnabled = this.imageSmoothingEnabled;
- },
-
- /**
- * @private
- * @param {String} property Property to set ({@link fabric.StaticCanvas#backgroundImage|backgroundImage}
- * or {@link fabric.StaticCanvas#overlayImage|overlayImage})
- * @param {(fabric.Image|String|null)} image fabric.Image instance, URL of an image or null to set background or overlay to
- * @param {Function} callback Callback to invoke when image is loaded and set as background or overlay
- * @param {Object} [options] Optional options to set for the {@link fabric.Image|image}.
- */
- __setBgOverlayImage: function(property, image, callback, options) {
- if (typeof image === 'string') {
- fabric.util.loadImage(image, function(img) {
- if (img) {
- var instance = new fabric.Image(img, options);
- this[property] = instance;
- instance.canvas = this;
- }
- callback && callback(img);
- }, this, options && options.crossOrigin);
- }
- else {
- options && image.setOptions(options);
- this[property] = image;
- image && (image.canvas = this);
- callback && callback(image);
- }
-
- return this;
- },
-
- /**
- * @private
- * @param {String} property Property to set ({@link fabric.StaticCanvas#backgroundColor|backgroundColor}
- * or {@link fabric.StaticCanvas#overlayColor|overlayColor})
- * @param {(Object|String|null)} color Object with pattern information, color value or null
- * @param {Function} [callback] Callback is invoked when color is set
- */
- __setBgOverlayColor: function(property, color, callback) {
- this[property] = color;
- this._initGradient(color, property);
- this._initPattern(color, property, callback);
- return this;
- },
-
- /**
- * @private
- */
- _createCanvasElement: function() {
- var element = createCanvasElement();
- if (!element) {
- throw CANVAS_INIT_ERROR;
- }
- if (!element.style) {
- element.style = { };
- }
- if (typeof element.getContext === 'undefined') {
- throw CANVAS_INIT_ERROR;
- }
- return element;
- },
-
- /**
- * @private
- * @param {Object} [options] Options object
- */
- _initOptions: function (options) {
- var lowerCanvasEl = this.lowerCanvasEl;
- this._setOptions(options);
-
- this.width = this.width || parseInt(lowerCanvasEl.width, 10) || 0;
- this.height = this.height || parseInt(lowerCanvasEl.height, 10) || 0;
-
- if (!this.lowerCanvasEl.style) {
- return;
- }
-
- lowerCanvasEl.width = this.width;
- lowerCanvasEl.height = this.height;
-
- lowerCanvasEl.style.width = this.width + 'px';
- lowerCanvasEl.style.height = this.height + 'px';
-
- this.viewportTransform = this.viewportTransform.slice();
- },
-
- /**
- * Creates a bottom canvas
- * @private
- * @param {HTMLElement} [canvasEl]
- */
- _createLowerCanvas: function (canvasEl) {
- // canvasEl === 'HTMLCanvasElement' does not work on jsdom/node
- if (canvasEl && canvasEl.getContext) {
- this.lowerCanvasEl = canvasEl;
- }
- else {
- this.lowerCanvasEl = fabric.util.getById(canvasEl) || this._createCanvasElement();
- }
-
- fabric.util.addClass(this.lowerCanvasEl, 'lower-canvas');
-
- if (this.interactive) {
- this._applyCanvasStyle(this.lowerCanvasEl);
- }
-
- this.contextContainer = this.lowerCanvasEl.getContext('2d');
- },
-
- /**
- * Returns canvas width (in px)
- * @return {Number}
- */
- getWidth: function () {
- return this.width;
- },
-
- /**
- * Returns canvas height (in px)
- * @return {Number}
- */
- getHeight: function () {
- return this.height;
- },
-
- /**
- * Sets width of this canvas instance
- * @param {Number|String} value Value to set width to
- * @param {Object} [options] Options object
- * @param {Boolean} [options.backstoreOnly=false] Set the given dimensions only as canvas backstore dimensions
- * @param {Boolean} [options.cssOnly=false] Set the given dimensions only as css dimensions
- * @return {fabric.Canvas} instance
- * @chainable true
- */
- setWidth: function (value, options) {
- return this.setDimensions({ width: value }, options);
- },
-
- /**
- * Sets height of this canvas instance
- * @param {Number|String} value Value to set height to
- * @param {Object} [options] Options object
- * @param {Boolean} [options.backstoreOnly=false] Set the given dimensions only as canvas backstore dimensions
- * @param {Boolean} [options.cssOnly=false] Set the given dimensions only as css dimensions
- * @return {fabric.Canvas} instance
- * @chainable true
- */
- setHeight: function (value, options) {
- return this.setDimensions({ height: value }, options);
- },
-
- /**
- * Sets dimensions (width, height) of this canvas instance. when options.cssOnly flag active you should also supply the unit of measure (px/%/em)
- * @param {Object} dimensions Object with width/height properties
- * @param {Number|String} [dimensions.width] Width of canvas element
- * @param {Number|String} [dimensions.height] Height of canvas element
- * @param {Object} [options] Options object
- * @param {Boolean} [options.backstoreOnly=false] Set the given dimensions only as canvas backstore dimensions
- * @param {Boolean} [options.cssOnly=false] Set the given dimensions only as css dimensions
- * @return {fabric.Canvas} thisArg
- * @chainable
- */
- setDimensions: function (dimensions, options) {
- var cssValue;
-
- options = options || {};
-
- for (var prop in dimensions) {
- cssValue = dimensions[prop];
-
- if (!options.cssOnly) {
- this._setBackstoreDimension(prop, dimensions[prop]);
- cssValue += 'px';
- this.hasLostContext = true;
- }
-
- if (!options.backstoreOnly) {
- this._setCssDimension(prop, cssValue);
- }
- }
- if (this._isCurrentlyDrawing) {
- this.freeDrawingBrush && this.freeDrawingBrush._setBrushStyles();
- }
- this._initRetinaScaling();
- this._setImageSmoothing();
- this.calcOffset();
-
- if (!options.cssOnly) {
- this.requestRenderAll();
- }
-
- return this;
- },
-
- /**
- * Helper for setting width/height
- * @private
- * @param {String} prop property (width|height)
- * @param {Number} value value to set property to
- * @return {fabric.Canvas} instance
- * @chainable true
- */
- _setBackstoreDimension: function (prop, value) {
- this.lowerCanvasEl[prop] = value;
-
- if (this.upperCanvasEl) {
- this.upperCanvasEl[prop] = value;
- }
-
- if (this.cacheCanvasEl) {
- this.cacheCanvasEl[prop] = value;
- }
-
- this[prop] = value;
-
- return this;
- },
-
- /**
- * Helper for setting css width/height
- * @private
- * @param {String} prop property (width|height)
- * @param {String} value value to set property to
- * @return {fabric.Canvas} instance
- * @chainable true
- */
- _setCssDimension: function (prop, value) {
- this.lowerCanvasEl.style[prop] = value;
-
- if (this.upperCanvasEl) {
- this.upperCanvasEl.style[prop] = value;
- }
-
- if (this.wrapperEl) {
- this.wrapperEl.style[prop] = value;
- }
-
- return this;
- },
-
- /**
- * Returns canvas zoom level
- * @return {Number}
- */
- getZoom: function () {
- return this.viewportTransform[0];
- },
-
- /**
- * Sets viewport transform of this canvas instance
- * @param {Array} vpt the transform in the form of context.transform
- * @return {fabric.Canvas} instance
- * @chainable true
- */
- setViewportTransform: function (vpt) {
- var activeObject = this._activeObject, object, ignoreVpt = false, skipAbsolute = true, i, len;
- this.viewportTransform = vpt;
- for (i = 0, len = this._objects.length; i < len; i++) {
- object = this._objects[i];
- object.group || object.setCoords(ignoreVpt, skipAbsolute);
- }
- if (activeObject && activeObject.type === 'activeSelection') {
- activeObject.setCoords(ignoreVpt, skipAbsolute);
- }
- this.calcViewportBoundaries();
- this.renderOnAddRemove && this.requestRenderAll();
- return this;
- },
-
- /**
- * Sets zoom level of this canvas instance, zoom centered around point
- * @param {fabric.Point} point to zoom with respect to
- * @param {Number} value to set zoom to, less than 1 zooms out
- * @return {fabric.Canvas} instance
- * @chainable true
- */
- zoomToPoint: function (point, value) {
- // TODO: just change the scale, preserve other transformations
- var before = point, vpt = this.viewportTransform.slice(0);
- point = transformPoint(point, invertTransform(this.viewportTransform));
- vpt[0] = value;
- vpt[3] = value;
- var after = transformPoint(point, vpt);
- vpt[4] += before.x - after.x;
- vpt[5] += before.y - after.y;
- return this.setViewportTransform(vpt);
- },
-
- /**
- * Sets zoom level of this canvas instance
- * @param {Number} value to set zoom to, less than 1 zooms out
- * @return {fabric.Canvas} instance
- * @chainable true
- */
- setZoom: function (value) {
- this.zoomToPoint(new fabric.Point(0, 0), value);
- return this;
- },
-
- /**
- * Pan viewport so as to place point at top left corner of canvas
- * @param {fabric.Point} point to move to
- * @return {fabric.Canvas} instance
- * @chainable true
- */
- absolutePan: function (point) {
- var vpt = this.viewportTransform.slice(0);
- vpt[4] = -point.x;
- vpt[5] = -point.y;
- return this.setViewportTransform(vpt);
- },
-
- /**
- * Pans viewpoint relatively
- * @param {fabric.Point} point (position vector) to move by
- * @return {fabric.Canvas} instance
- * @chainable true
- */
- relativePan: function (point) {
- return this.absolutePan(new fabric.Point(
- -point.x - this.viewportTransform[4],
- -point.y - this.viewportTransform[5]
- ));
- },
-
- /**
- * Returns <canvas> element corresponding to this instance
- * @return {HTMLCanvasElement}
- */
- getElement: function () {
- return this.lowerCanvasEl;
- },
-
- /**
- * @private
- * @param {fabric.Object} obj Object that was added
- */
- _onObjectAdded: function(obj) {
- this.stateful && obj.setupState();
- obj._set('canvas', this);
- obj.setCoords();
- this.fire('object:added', { target: obj });
- obj.fire('added');
- },
-
- /**
- * @private
- * @param {fabric.Object} obj Object that was removed
- */
- _onObjectRemoved: function(obj) {
- this.fire('object:removed', { target: obj });
- obj.fire('removed');
- delete obj.canvas;
- },
-
- /**
- * Clears specified context of canvas element
- * @param {CanvasRenderingContext2D} ctx Context to clear
- * @return {fabric.Canvas} thisArg
- * @chainable
- */
- clearContext: function(ctx) {
- ctx.clearRect(0, 0, this.width, this.height);
- return this;
- },
-
- /**
- * Returns context of canvas where objects are drawn
- * @return {CanvasRenderingContext2D}
- */
- getContext: function () {
- return this.contextContainer;
- },
-
- /**
- * Clears all contexts (background, main, top) of an instance
- * @return {fabric.Canvas} thisArg
- * @chainable
- */
- clear: function () {
- this._objects.length = 0;
- this.backgroundImage = null;
- this.overlayImage = null;
- this.backgroundColor = '';
- this.overlayColor = '';
- if (this._hasITextHandlers) {
- this.off('mouse:up', this._mouseUpITextHandler);
- this._iTextInstances = null;
- this._hasITextHandlers = false;
- }
- this.clearContext(this.contextContainer);
- this.fire('canvas:cleared');
- this.renderOnAddRemove && this.requestRenderAll();
- return this;
- },
-
- /**
- * Renders the canvas
- * @return {fabric.Canvas} instance
- * @chainable
- */
- renderAll: function () {
- var canvasToDrawOn = this.contextContainer;
- this.renderCanvas(canvasToDrawOn, this._objects);
- return this;
- },
-
- /**
- * Function created to be instance bound at initialization
- * used in requestAnimationFrame rendering
- * Let the fabricJS call it. If you call it manually you could have more
- * animationFrame stacking on to of each other
- * for an imperative rendering, use canvas.renderAll
- * @private
- * @return {fabric.Canvas} instance
- * @chainable
- */
- renderAndReset: function() {
- this.isRendering = 0;
- this.renderAll();
- },
-
- /**
- * Append a renderAll request to next animation frame.
- * unless one is already in progress, in that case nothing is done
- * a boolean flag will avoid appending more.
- * @return {fabric.Canvas} instance
- * @chainable
- */
- requestRenderAll: function () {
- if (!this.isRendering) {
- this.isRendering = fabric.util.requestAnimFrame(this.renderAndResetBound);
- }
- return this;
- },
-
- /**
- * Calculate the position of the 4 corner of canvas with current viewportTransform.
- * helps to determinate when an object is in the current rendering viewport using
- * object absolute coordinates ( aCoords )
- * @return {Object} points.tl
- * @chainable
- */
- calcViewportBoundaries: function() {
- var points = { }, width = this.width, height = this.height,
- iVpt = invertTransform(this.viewportTransform);
- points.tl = transformPoint({ x: 0, y: 0 }, iVpt);
- points.br = transformPoint({ x: width, y: height }, iVpt);
- points.tr = new fabric.Point(points.br.x, points.tl.y);
- points.bl = new fabric.Point(points.tl.x, points.br.y);
- this.vptCoords = points;
- return points;
- },
-
- cancelRequestedRender: function() {
- if (this.isRendering) {
- fabric.util.cancelAnimFrame(this.isRendering);
- this.isRendering = 0;
- }
- },
-
- /**
- * Renders background, objects, overlay and controls.
- * @param {CanvasRenderingContext2D} ctx
- * @param {Array} objects to render
- * @return {fabric.Canvas} instance
- * @chainable
- */
- renderCanvas: function(ctx, objects) {
- var v = this.viewportTransform, path = this.clipPath;
- this.cancelRequestedRender();
- this.calcViewportBoundaries();
- this.clearContext(ctx);
- this.fire('before:render', { ctx: ctx, });
- if (this.clipTo) {
- fabric.util.clipContext(this, ctx);
- }
- this._renderBackground(ctx);
-
- ctx.save();
- //apply viewport transform once for all rendering process
- ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]);
- this._renderObjects(ctx, objects);
- ctx.restore();
- if (!this.controlsAboveOverlay && this.interactive) {
- this.drawControls(ctx);
- }
- if (this.clipTo) {
- ctx.restore();
- }
- if (path) {
- path.canvas = this;
- // needed to setup a couple of variables
- path.shouldCache();
- path._transformDone = true;
- path.renderCache({ forClipping: true });
- this.drawClipPathOnCanvas(ctx);
- }
- this._renderOverlay(ctx);
- if (this.controlsAboveOverlay && this.interactive) {
- this.drawControls(ctx);
- }
- this.fire('after:render', { ctx: ctx, });
- },
-
- /**
- * Paint the cached clipPath on the lowerCanvasEl
- * @param {CanvasRenderingContext2D} ctx Context to render on
- */
- drawClipPathOnCanvas: function(ctx) {
- var v = this.viewportTransform, path = this.clipPath;
- ctx.save();
- ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]);
- // DEBUG: uncomment this line, comment the following
- // ctx.globalAlpha = 0.4;
- ctx.globalCompositeOperation = 'destination-in';
- path.transform(ctx);
- ctx.scale(1 / path.zoomX, 1 / path.zoomY);
- ctx.drawImage(path._cacheCanvas, -path.cacheTranslationX, -path.cacheTranslationY);
- ctx.restore();
- },
-
- /**
- * @private
- * @param {CanvasRenderingContext2D} ctx Context to render on
- * @param {Array} objects to render
- */
- _renderObjects: function(ctx, objects) {
- var i, len;
- for (i = 0, len = objects.length; i < len; ++i) {
- objects[i] && objects[i].render(ctx);
- }
- },
-
- /**
- * @private
- * @param {CanvasRenderingContext2D} ctx Context to render on
- * @param {string} property 'background' or 'overlay'
- */
- _renderBackgroundOrOverlay: function(ctx, property) {
- var fill = this[property + 'Color'], object = this[property + 'Image'],
- v = this.viewportTransform, needsVpt = this[property + 'Vpt'];
- if (!fill && !object) {
- return;
- }
- if (fill) {
- ctx.save();
- ctx.beginPath();
- ctx.moveTo(0, 0);
- ctx.lineTo(this.width, 0);
- ctx.lineTo(this.width, this.height);
- ctx.lineTo(0, this.height);
- ctx.closePath();
- ctx.fillStyle = fill.toLive
- ? fill.toLive(ctx, this)
- : fill;
- if (needsVpt) {
- ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]);
- }
- ctx.transform(1, 0, 0, 1, fill.offsetX || 0, fill.offsetY || 0);
- var m = fill.gradientTransform || fill.patternTransform;
- m && ctx.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
- ctx.fill();
- ctx.restore();
- }
- if (object) {
- ctx.save();
- if (needsVpt) {
- ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]);
- }
- object.render(ctx);
- ctx.restore();
- }
- },
-
- /**
- * @private
- * @param {CanvasRenderingContext2D} ctx Context to render on
- */
- _renderBackground: function(ctx) {
- this._renderBackgroundOrOverlay(ctx, 'background');
- },
-
- /**
- * @private
- * @param {CanvasRenderingContext2D} ctx Context to render on
- */
- _renderOverlay: function(ctx) {
- this._renderBackgroundOrOverlay(ctx, 'overlay');
- },
-
- /**
- * Returns coordinates of a center of canvas.
- * Returned value is an object with top and left properties
- * @return {Object} object with "top" and "left" number values
- */
- getCenter: function () {
- return {
- top: this.height / 2,
- left: this.width / 2
- };
- },
-
- /**
- * Centers object horizontally in the canvas
- * @param {fabric.Object} object Object to center horizontally
- * @return {fabric.Canvas} thisArg
- */
- centerObjectH: function (object) {
- return this._centerObject(object, new fabric.Point(this.getCenter().left, object.getCenterPoint().y));
- },
-
- /**
- * Centers object vertically in the canvas
- * @param {fabric.Object} object Object to center vertically
- * @return {fabric.Canvas} thisArg
- * @chainable
- */
- centerObjectV: function (object) {
- return this._centerObject(object, new fabric.Point(object.getCenterPoint().x, this.getCenter().top));
- },
-
- /**
- * Centers object vertically and horizontally in the canvas
- * @param {fabric.Object} object Object to center vertically and horizontally
- * @return {fabric.Canvas} thisArg
- * @chainable
- */
- centerObject: function(object) {
- var center = this.getCenter();
-
- return this._centerObject(object, new fabric.Point(center.left, center.top));
- },
-
- /**
- * Centers object vertically and horizontally in the viewport
- * @param {fabric.Object} object Object to center vertically and horizontally
- * @return {fabric.Canvas} thisArg
- * @chainable
- */
- viewportCenterObject: function(object) {
- var vpCenter = this.getVpCenter();
-
- return this._centerObject(object, vpCenter);
- },
-
- /**
- * Centers object horizontally in the viewport, object.top is unchanged
- * @param {fabric.Object} object Object to center vertically and horizontally
- * @return {fabric.Canvas} thisArg
- * @chainable
- */
- viewportCenterObjectH: function(object) {
- var vpCenter = this.getVpCenter();
- this._centerObject(object, new fabric.Point(vpCenter.x, object.getCenterPoint().y));
- return this;
- },
-
- /**
- * Centers object Vertically in the viewport, object.top is unchanged
- * @param {fabric.Object} object Object to center vertically and horizontally
- * @return {fabric.Canvas} thisArg
- * @chainable
- */
- viewportCenterObjectV: function(object) {
- var vpCenter = this.getVpCenter();
-
- return this._centerObject(object, new fabric.Point(object.getCenterPoint().x, vpCenter.y));
- },
-
- /**
- * Calculate the point in canvas that correspond to the center of actual viewport.
- * @return {fabric.Point} vpCenter, viewport center
- * @chainable
- */
- getVpCenter: function() {
- var center = this.getCenter(),
- iVpt = invertTransform(this.viewportTransform);
- return transformPoint({ x: center.left, y: center.top }, iVpt);
- },
-
- /**
- * @private
- * @param {fabric.Object} object Object to center
- * @param {fabric.Point} center Center point
- * @return {fabric.Canvas} thisArg
- * @chainable
- */
- _centerObject: function(object, center) {
- object.setPositionByOrigin(center, 'center', 'center');
- object.setCoords();
- this.renderOnAddRemove && this.requestRenderAll();
- return this;
- },
-
- /**
- * Returs dataless JSON representation of canvas
- * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
- * @return {String} json string
- */
- toDatalessJSON: function (propertiesToInclude) {
- return this.toDatalessObject(propertiesToInclude);
- },
-
- /**
- * Returns object representation of canvas
- * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
- * @return {Object} object representation of an instance
- */
- toObject: function (propertiesToInclude) {
- return this._toObjectMethod('toObject', propertiesToInclude);
- },
-
- /**
- * Returns dataless object representation of canvas
- * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
- * @return {Object} object representation of an instance
- */
- toDatalessObject: function (propertiesToInclude) {
- return this._toObjectMethod('toDatalessObject', propertiesToInclude);
- },
-
- /**
- * @private
- */
- _toObjectMethod: function (methodName, propertiesToInclude) {
-
- var clipPath = this.clipPath, data = {
- version: fabric.version,
- objects: this._toObjects(methodName, propertiesToInclude),
- };
- if (clipPath) {
- data.clipPath = this._toObject(this.clipPath, methodName, propertiesToInclude);
- }
- extend(data, this.__serializeBgOverlay(methodName, propertiesToInclude));
-
- fabric.util.populateWithProperties(this, data, propertiesToInclude);
-
- return data;
- },
-
- /**
- * @private
- */
- _toObjects: function(methodName, propertiesToInclude) {
- return this._objects.filter(function(object) {
- return !object.excludeFromExport;
- }).map(function(instance) {
- return this._toObject(instance, methodName, propertiesToInclude);
- }, this);
- },
-
- /**
- * @private
- */
- _toObject: function(instance, methodName, propertiesToInclude) {
- var originalValue;
-
- if (!this.includeDefaultValues) {
- originalValue = instance.includeDefaultValues;
- instance.includeDefaultValues = false;
- }
-
- var object = instance[methodName](propertiesToInclude);
- if (!this.includeDefaultValues) {
- instance.includeDefaultValues = originalValue;
- }
- return object;
- },
-
- /**
- * @private
- */
- __serializeBgOverlay: function(methodName, propertiesToInclude) {
- var data = { }, bgImage = this.backgroundImage, overlay = this.overlayImage;
-
- if (this.backgroundColor) {
- data.background = this.backgroundColor.toObject
- ? this.backgroundColor.toObject(propertiesToInclude)
- : this.backgroundColor;
- }
-
- if (this.overlayColor) {
- data.overlay = this.overlayColor.toObject
- ? this.overlayColor.toObject(propertiesToInclude)
- : this.overlayColor;
- }
- if (bgImage && !bgImage.excludeFromExport) {
- data.backgroundImage = this._toObject(bgImage, methodName, propertiesToInclude);
- }
- if (overlay && !overlay.excludeFromExport) {
- data.overlayImage = this._toObject(overlay, methodName, propertiesToInclude);
- }
-
- return data;
- },
-
- /* _TO_SVG_START_ */
- /**
- * When true, getSvgTransform() will apply the StaticCanvas.viewportTransform to the SVG transformation. When true,
- * a zoomed canvas will then produce zoomed SVG output.
- * @type Boolean
- * @default
- */
- svgViewportTransformation: true,
-
- /**
- * Returns SVG representation of canvas
- * @function
- * @param {Object} [options] Options object for SVG output
- * @param {Boolean} [options.suppressPreamble=false] If true xml tag is not included
- * @param {Object} [options.viewBox] SVG viewbox object
- * @param {Number} [options.viewBox.x] x-cooridnate of viewbox
- * @param {Number} [options.viewBox.y] y-coordinate of viewbox
- * @param {Number} [options.viewBox.width] Width of viewbox
- * @param {Number} [options.viewBox.height] Height of viewbox
- * @param {String} [options.encoding=UTF-8] Encoding of SVG output
- * @param {String} [options.width] desired width of svg with or without units
- * @param {String} [options.height] desired height of svg with or without units
- * @param {Function} [reviver] Method for further parsing of svg elements, called after each fabric object converted into svg representation.
- * @return {String} SVG string
- * @tutorial {@link http://fabricjs.com/fabric-intro-part-3#serialization}
- * @see {@link http://jsfiddle.net/fabricjs/jQ3ZZ/|jsFiddle demo}
- * @example <caption>Normal SVG output</caption>
- * var svg = canvas.toSVG();
- * @example <caption>SVG output without preamble (without <?xml ../>)</caption>
- * var svg = canvas.toSVG({suppressPreamble: true});
- * @example <caption>SVG output with viewBox attribute</caption>
- * var svg = canvas.toSVG({
- * viewBox: {
- * x: 100,
- * y: 100,
- * width: 200,
- * height: 300
- * }
- * });
- * @example <caption>SVG output with different encoding (default: UTF-8)</caption>
- * var svg = canvas.toSVG({encoding: 'ISO-8859-1'});
- * @example <caption>Modify SVG output with reviver function</caption>
- * var svg = canvas.toSVG(null, function(svg) {
- * return svg.replace('stroke-dasharray: ; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; ', '');
- * });
- */
- toSVG: function(options, reviver) {
- options || (options = { });
- options.reviver = reviver;
- var markup = [];
-
- this._setSVGPreamble(markup, options);
- this._setSVGHeader(markup, options);
- if (this.clipPath) {
- markup.push('<g clip-path="url(#' + this.clipPath.clipPathId + ')" >\n');
- }
- this._setSVGBgOverlayColor(markup, 'background');
- this._setSVGBgOverlayImage(markup, 'backgroundImage', reviver);
- this._setSVGObjects(markup, reviver);
- if (this.clipPath) {
- markup.push('</g>\n');
- }
- this._setSVGBgOverlayColor(markup, 'overlay');
- this._setSVGBgOverlayImage(markup, 'overlayImage', reviver);
-
- markup.push('</svg>');
... 23281 lines suppressed ...