diff --git a/fabricjs/fabricjs-tests.ts b/fabricjs/fabricjs-tests.ts
index e59212d80..c3dfd8d6d 100644
--- a/fabricjs/fabricjs-tests.ts
+++ b/fabricjs/fabricjs-tests.ts
@@ -1,1065 +1,1063 @@
///
function sample1() {
- var canvas = new fabric.Canvas('c', {
- hoverCursor: 'pointer',
- selection: false,
+ var canvas = new fabric.Canvas('c', {
+ hoverCursor: 'pointer',
+ selection: false,
+ });
+
+ canvas.on('object:moving', function(e: fabric.IEvent) {
+ e.target.opacity = 0.5;
+ });
+ canvas.on('object:modified', function(e: fabric.IEvent) {
+ e.target.opacity = 1;
+ });
+
+ for (var i = 0, len = 15; i < len; i++) {
+ fabric.Image.fromURL('../assets/ladybug.png', function(img) {
+ img.set({
+ left: fabric.util.getRandomInt(0, 600),
+ top: fabric.util.getRandomInt(0, 500),
+ angle: fabric.util.getRandomInt(0, 90)
+ });
+
+ img.perPixelTargetFind = true;
+ // img.targetFindTolerance = 4;
+ img.hasControls = img.hasBorders = false;
+
+ img.scale(fabric.util.getRandomInt(50, 100) / 100);
+
+ canvas.add(img);
});
-
- canvas.on({
- 'object:moving': function (e) {
- (e.target).opacity = 0.5;
- },
- 'object:modified': function (e) {
- (e.target).opacity = 1;
- }
- });
-
- for (var i = 0, len = 15; i < len; i++) {
- fabric.Image.fromURL('../assets/ladybug.png', function (img) {
- img.set({
- left: fabric.util.getRandomInt(0, 600),
- top: fabric.util.getRandomInt(0, 500),
- angle: fabric.util.getRandomInt(0, 90)
- });
-
- img.perPixelTargetFind = true;
- // img.targetFindTolerance = 4;
- img.hasControls = img.hasBorders = false;
-
- img.scale(fabric.util.getRandomInt(50, 100) / 100);
-
- canvas.add(img);
- });
- }
+ }
}
function sample2() {
- var dot, i,
- t1, t2,
- startTimer = function () {
- t1 = new Date().getTime();
- return t1;
- },
- stopTimer = function () {
- t2 = new Date().getTime();
- return t2 - t1;
- },
- getRandomInt = fabric.util.getRandomInt,
- rainbow = ["#ffcc66", "#ccff66", "#66ccff", "#ff6fcf", "#ff6666"],
- rainbowEnd = rainbow.length - 1;
+ var dot, i,
+ t1, t2,
+ startTimer = function() {
+ t1 = new Date().getTime();
+ return t1;
+ },
+ stopTimer = function() {
+ t2 = new Date().getTime();
+ return t2 - t1;
+ },
+ getRandomInt = fabric.util.getRandomInt,
+ rainbow = ["#ffcc66", "#ccff66", "#66ccff", "#ff6fcf", "#ff6666"],
+ rainbowEnd = rainbow.length - 1;
- //
- // Rendering canvas #1
- //
- var canvas1 = new fabric.Canvas('c1', { backgroundColor: "#000" }),
- results1 = document.getElementById('results-c1');
+ //
+ // Rendering canvas #1
+ //
+ var canvas1 = new fabric.Canvas('c1', { backgroundColor: "#000" }),
+ results1 = document.getElementById('results-c1');
- startTimer();
- for (i = 100; i >= 0; i--) {
- dot = new fabric.Circle({
- left: getRandomInt(0, 400),
- top: getRandomInt(0, 350),
- radius: 3,
- fill: rainbow[getRandomInt(0, rainbowEnd)]
- });
- canvas1.add(dot);
- }
- results1.innerHTML = 'Regular rendering of 100 elements in ' + stopTimer() + 'ms';
+ startTimer();
+ for (i = 100; i >= 0; i--) {
+ dot = new fabric.Circle({
+ left: getRandomInt(0, 400),
+ top: getRandomInt(0, 350),
+ radius: 3,
+ fill: rainbow[getRandomInt(0, rainbowEnd)]
+ });
+ canvas1.add(dot);
+ }
+ results1.innerHTML = 'Regular rendering of 100 elements in ' + stopTimer() + 'ms';
- //
- // Rendering canvas #2
- //
- var canvas2 = new fabric.Canvas('c2', { backgroundColor: "#000", renderOnAddition: false }),
- results2 = document.getElementById('results-c2');
+ //
+ // Rendering canvas #2
+ //
+ var canvas2 = new fabric.Canvas('c2', { backgroundColor: "#000", renderOnAddition: false }),
+ results2 = document.getElementById('results-c2');
- startTimer();
- for (i = 1000; i >= 0; i--) {
- dot = new fabric.Circle({
- left: getRandomInt(0, 400),
- top: getRandomInt(0, 350),
- radius: 3,
- fill: rainbow[getRandomInt(0, rainbowEnd)]
- });
- canvas2.add(dot);
- }
- canvas2.renderAll(); // Note, calling renderAll() is important in this case
- results2.innerHTML = 'Rendering 1000 elements using canvas.renderOnAddition = false in ' + stopTimer() + 'ms';
+ startTimer();
+ for (i = 1000; i >= 0; i--) {
+ dot = new fabric.Circle({
+ left: getRandomInt(0, 400),
+ top: getRandomInt(0, 350),
+ radius: 3,
+ fill: rainbow[getRandomInt(0, rainbowEnd)]
+ });
+ canvas2.add(dot);
+ }
+ canvas2.renderAll(); // Note, calling renderAll() is important in this case
+ results2.innerHTML = 'Rendering 1000 elements using canvas.renderOnAddition = false in ' + stopTimer() + 'ms';
}
function sample3() {
- var $ = function (id) {return document.getElementById(id) };
+ var $ = function(id) { return document.getElementById(id) };
- function applyFilter(index, filter) {
- var obj = canvas.getActiveObject();
- obj.filters[index] = filter;
- obj.applyFilters(canvas.renderAll.bind(canvas));
- }
-
- function applyFilterValue(index, prop, value) {
- var obj = canvas.getActiveObject();
- if (obj.filters[index]) {
- obj.filters[index][prop] = value;
- obj.applyFilters(canvas.renderAll.bind(canvas));
- }
- }
-
- var canvas = new fabric.Canvas('c', { backgroundImage: '../lib/bg.png' }),
- f = fabric.Image.filters;
-
- canvas.on({
- 'object:selected': function () {
- fabric.util.toArray(document.getElementsByTagName('input')).forEach(function (el) { el.disabled = false; })
-
- var filters = ['grayscale', 'invert', 'remove-white', 'sepia', 'sepia2', 'brightness',
- 'noise', 'gradient-transparency', 'pixelate', 'blur', 'sharpen'];
-
- for (var i = 0; i < filters.length; i++) {
- var checkBox = $(filters[i]);
- var image = canvas.getActiveObject();
- checkBox.checked = !!image.filters[i];
- }
- },
- 'selection:cleared': function () {
- fabric.util.toArray(document.getElementsByTagName('input')).forEach(function (el) { el.disabled = true; })
+ function applyFilter(index, filter) {
+ var obj = canvas.getActiveObject();
+ obj.filters[index] = filter;
+ obj.applyFilters(canvas.renderAll.bind(canvas));
}
- });
- fabric.Image.fromURL('../assets/printio.png', function (img) {
- var oImg = img.set({ left: 300, top: 300, angle: -15 }).scale(0.9);
- canvas.add(oImg).renderAll();
- canvas.setActiveObject(oImg);
- });
+ function applyFilterValue(index, prop, value) {
+ var obj = canvas.getActiveObject();
+ if (obj.filters[index]) {
+ obj.filters[index][prop] = value;
+ obj.applyFilters(canvas.renderAll.bind(canvas));
+ }
+ }
- $('grayscale').onclick = function () {
- applyFilter(0, this.checked && new f.Grayscale());
- };
- $('invert').onclick = function () {
- applyFilter(1, this.checked && new f.Invert());
- };
- $('remove-white').onclick = function () {
- applyFilter(2, this.checked && new f.RemoveWhite({
- threshold: ($('remove-white-threshold')).value,
- distance: ($('remove-white-distance')).value
- }));
- };
- $('remove-white-threshold').onchange = function () {
- applyFilterValue(2, 'threshold', this.value);
- };
- $('remove-white-distance').onchange = function () {
- applyFilterValue(2, 'distance', this.value);
- };
- $('sepia').onclick = function () {
- applyFilter(3, this.checked && new f.Sepia());
- };
- $('sepia2').onclick = function () {
- applyFilter(4, this.checked && new f.Sepia2());
- };
- $('brightness').onclick = function () {
- applyFilter(5, this.checked && new f.Brightness({
- brightness: parseInt(($('brightness-value')).value, 10)
- }));
- };
- $('brightness-value').onchange = function () {
- applyFilterValue(5, 'brightness', parseInt(this.value, 10));
- };
- $('noise').onclick = function () {
- applyFilter(6, this.checked && new f.Noise({
- noise: parseInt(($('noise-value')).value, 10)
- }));
- };
- $('noise-value').onchange = function () {
- applyFilterValue(6, 'noise', parseInt(this.value, 10));
- };
- $('gradient-transparency').onclick = function () {
- applyFilter(7, this.checked && new f.GradientTransparency({
- threshold: parseInt(($('gradient-transparency-value')).value, 10)
- }));
- };
- $('gradient-transparency-value').onchange = function () {
- applyFilterValue(7, 'threshold', parseInt(this.value, 10));
- };
- $('pixelate').onclick = function () {
- applyFilter(8, this.checked && new f.Pixelate({
- blocksize: parseInt(($('pixelate-value')).value, 10)
- }));
- };
- $('pixelate-value').onchange = function () {
- applyFilterValue(8, 'blocksize', parseInt(this.value, 10));
- };
- $('blur').onclick = function () {
- applyFilter(9, this.checked && new f.Convolute({
- matrix: [1 / 9, 1 / 9, 1 / 9,
- 1 / 9, 1 / 9, 1 / 9,
- 1 / 9, 1 / 9, 1 / 9]
- }));
- };
- $('sharpen').onclick = function () {
- applyFilter(10, this.checked && new f.Convolute({
- matrix: [0, -1, 0,
- -1, 5, -1,
- 0, -1, 0]
- }));
- };
- $('emboss').onclick = function () {
- applyFilter(11, this.checked && new f.Convolute({
- matrix: [1, 1, 1,
- 1, 0.7, -1,
- -1, -1, -1]
- }));
- };
+ var canvas = new fabric.Canvas('c', { backgroundImage: '../lib/bg.png' }),
+ f = fabric.Image.filters;
+
+ canvas.on({
+ 'object:selected': function() {
+ fabric.util.toArray(document.getElementsByTagName('input')).forEach(function(el) { el.disabled = false; })
+
+ var filters = ['grayscale', 'invert', 'remove-white', 'sepia', 'sepia2', 'brightness',
+ 'noise', 'gradient-transparency', 'pixelate', 'blur', 'sharpen'];
+
+ for (var i = 0; i < filters.length; i++) {
+ var checkBox = $(filters[i]);
+ var image = canvas.getActiveObject();
+ checkBox.checked = !!image.filters[i];
+ }
+ },
+ 'selection:cleared': function() {
+ fabric.util.toArray(document.getElementsByTagName('input')).forEach(function(el) { el.disabled = true; })
+ }
+ });
+
+ fabric.Image.fromURL('../assets/printio.png', function(img) {
+ var oImg = img.set({ left: 300, top: 300, angle: -15 }).scale(0.9);
+ canvas.add(oImg).renderAll();
+ canvas.setActiveObject(oImg);
+ });
+
+ $('grayscale').onclick = function() {
+ applyFilter(0, this.checked && new f.Grayscale());
+ };
+ $('invert').onclick = function() {
+ applyFilter(1, this.checked && new f.Invert());
+ };
+ $('remove-white').onclick = function() {
+ applyFilter(2, this.checked && new f.RemoveWhite({
+ threshold: parseInt(($('remove-white-threshold')).value),
+ distance: parseInt(($('remove-white-distance')).value)
+ }));
+ };
+ $('remove-white-threshold').onchange = function() {
+ applyFilterValue(2, 'threshold', this.value);
+ };
+ $('remove-white-distance').onchange = function() {
+ applyFilterValue(2, 'distance', this.value);
+ };
+ $('sepia').onclick = function() {
+ applyFilter(3, this.checked && new f.Sepia());
+ };
+ $('sepia2').onclick = function() {
+ applyFilter(4, this.checked && new f.Sepia2());
+ };
+ $('brightness').onclick = function() {
+ applyFilter(5, this.checked && new f.Brightness({
+ brightness: parseInt(($('brightness-value')).value, 10)
+ }));
+ };
+ $('brightness-value').onchange = function() {
+ applyFilterValue(5, 'brightness', parseInt(this.value, 10));
+ };
+ $('noise').onclick = function() {
+ applyFilter(6, this.checked && new f.Noise({
+ noise: parseInt(($('noise-value')).value, 10)
+ }));
+ };
+ $('noise-value').onchange = function() {
+ applyFilterValue(6, 'noise', parseInt(this.value, 10));
+ };
+ $('gradient-transparency').onclick = function() {
+ applyFilter(7, this.checked && new f.GradientTransparency({
+ threshold: parseInt(($('gradient-transparency-value')).value, 10)
+ }));
+ };
+ $('gradient-transparency-value').onchange = function() {
+ applyFilterValue(7, 'threshold', parseInt(this.value, 10));
+ };
+ $('pixelate').onclick = function() {
+ applyFilter(8, this.checked && new f.Pixelate({
+ blocksize: parseInt(($('pixelate-value')).value, 10)
+ }));
+ };
+ $('pixelate-value').onchange = function() {
+ applyFilterValue(8, 'blocksize', parseInt(this.value, 10));
+ };
+ $('blur').onclick = function() {
+ applyFilter(9, this.checked && new f.Convolute({
+ matrix: [1 / 9, 1 / 9, 1 / 9,
+ 1 / 9, 1 / 9, 1 / 9,
+ 1 / 9, 1 / 9, 1 / 9]
+ }));
+ };
+ $('sharpen').onclick = function() {
+ applyFilter(10, this.checked && new f.Convolute({
+ matrix: [0, -1, 0,
+ -1, 5, -1,
+ 0, -1, 0]
+ }));
+ };
+ $('emboss').onclick = function() {
+ applyFilter(11, this.checked && new f.Convolute({
+ matrix: [1, 1, 1,
+ 1, 0.7, -1,
+ -1, -1, -1]
+ }));
+ };
}
function sample4() {
- var canvas = new fabric.Canvas('c');
- var $ = function (id) { return document.getElementById(id); };
+ var canvas = new fabric.Canvas('c');
+ var $ = function(id) { return document.getElementById(id); };
- var rect = new fabric.Rect({
- width: 100,
- height: 100,
- top: 150,
- left: 150,
- fill: 'rgba(255,0,0,0.5)'
- });
+ var rect = new fabric.Rect({
+ width: 100,
+ height: 100,
+ top: 150,
+ left: 150,
+ fill: 'rgba(255,0,0,0.5)'
+ });
- canvas.add(rect);
+ canvas.add(rect);
- var angleControl = $('angle-control');
- angleControl.onchange = function () {
- rect.setAngle(this.value).setCoords();
- canvas.renderAll();
- };
+ var angleControl = $('angle-control');
+ angleControl.onchange = function() {
+ rect.setAngle(this.value).setCoords();
+ canvas.renderAll();
+ };
- var scaleControl = $('scale-control');
- scaleControl.onchange = function () {
- rect.scale(this.value).setCoords();
- canvas.renderAll();
- };
+ var scaleControl = $('scale-control');
+ scaleControl.onchange = function() {
+ rect.scale(this.value).setCoords();
+ canvas.renderAll();
+ };
- var topControl = $('top-control');
- topControl.onchange = function () {
- rect.setTop(this.value).setCoords();
- canvas.renderAll();
- };
+ var topControl = $('top-control');
+ topControl.onchange = function() {
+ rect.setTop(this.value).setCoords();
+ canvas.renderAll();
+ };
- var leftControl = $('left-control');
- leftControl.onchange = function () {
- rect.setLeft(this.value).setCoords();
- canvas.renderAll();
- };
+ var leftControl = $('left-control');
+ leftControl.onchange = function() {
+ rect.setLeft(this.value).setCoords();
+ canvas.renderAll();
+ };
- function updateControls() {
+ function updateControls() {
- scaleControl.value = rect.getScaleX().toString();
- angleControl.value = rect.getAngle().toString();
- leftControl.value = rect.getLeft().toString();
- topControl.value = rect.getTop().toString();
- }
- canvas.on({
- 'object:moving': updateControls,
- 'object:scaling': updateControls,
- 'object:resizing': updateControls
- });
+ scaleControl.value = rect.getScaleX().toString();
+ angleControl.value = rect.getAngle().toString();
+ leftControl.value = rect.getLeft().toString();
+ topControl.value = rect.getTop().toString();
+ }
+ canvas.on({
+ 'object:moving': updateControls,
+ 'object:scaling': updateControls,
+ 'object:resizing': updateControls
+ });
}
module fabric {
- export interface CircleWithLineInfos extends ICircle {
- line1?: ILine;
- line2?: ILine;
- line3?: ILine;
- line4?: ILine;
- }
+ export interface CircleWithLineInfos extends ICircle {
+ line1?: ILine;
+ line2?: ILine;
+ line3?: ILine;
+ line4?: ILine;
+ }
}
function sample5() {
- var makeCircle = function (left: number, top: number, line1?: fabric.ILine, line2?: fabric.ILine, line3?: fabric.ILine, line4?: fabric.ILine): fabric.ICircle {
- var c = new fabric.Circle({
- left: left,
- top: top,
- strokeWidth: 5,
- radius: 12,
- fill: '#fff',
- stroke: '#666'
- });
-
- c.line1 = line1;
- c.line2 = line2;
- c.line3 = line3;
- c.line4 = line4;
- c.hasControls = c.hasBorders = false;
- return c;
- }
-
-function makeLine(coords: number[]) {
- return new fabric.Line(coords, {
- fill: 'red',
- strokeWidth: 5,
- selectable: false
- });
- }
-
- var canvas = new fabric.Canvas('c', { selection: false });
-
- var line = makeLine([250, 125, 250, 175]),
- line2 = makeLine([250, 175, 250, 250]),
- line3 = makeLine([250, 250, 300, 350]),
- line4 = makeLine([250, 250, 200, 350]),
- line5 = makeLine([250, 175, 175, 225]),
- line6 = makeLine([250, 175, 325, 225]);
-
- canvas.add(line, line2, line3, line4, line5, line6);
-
- canvas.add(
- makeCircle(line.x1, line.y1, null, line),
- makeCircle(line.x2, line.y2, line, line2, line5, line6),
- makeCircle(line2.x2, line2.y2, line2, line3, line4),
- makeCircle(line3.x2, line3.y2, line3),
- makeCircle(line4.x2, line4.y2, line4),
- makeCircle(line5.x2, line5.y2, line5),
- makeCircle(line6.x2, line6.y2, line6)
- );
-
- canvas.on('object:moving', function (e) {
- var p = e.target;
- p.line1 && p.line1.set({ 'x2': p.left, 'y2': p.top });
- p.line2 && p.line2.set({ 'x1': p.left, 'y1': p.top });
- p.line3 && p.line3.set({ 'x1': p.left, 'y1': p.top });
- p.line4 && p.line4.set({ 'x1': p.left, 'y1': p.top });
- canvas.renderAll();
+ var makeCircle = function(left: number, top: number, line1?: fabric.ILine, line2?: fabric.ILine, line3?: fabric.ILine, line4?: fabric.ILine): fabric.ICircle {
+ var c = new fabric.Circle({
+ left: left,
+ top: top,
+ strokeWidth: 5,
+ radius: 12,
+ fill: '#fff',
+ stroke: '#666'
});
+
+ c.line1 = line1;
+ c.line2 = line2;
+ c.line3 = line3;
+ c.line4 = line4;
+ c.hasControls = c.hasBorders = false;
+ return c;
+ }
+
+ function makeLine(coords: number[]) {
+ return new fabric.Line(coords, {
+ fill: 'red',
+ strokeWidth: 5,
+ selectable: false
+ });
+ }
+
+ var canvas = new fabric.Canvas('c', { selection: false });
+
+ var line = makeLine([250, 125, 250, 175]),
+ line2 = makeLine([250, 175, 250, 250]),
+ line3 = makeLine([250, 250, 300, 350]),
+ line4 = makeLine([250, 250, 200, 350]),
+ line5 = makeLine([250, 175, 175, 225]),
+ line6 = makeLine([250, 175, 325, 225]);
+
+ canvas.add(line, line2, line3, line4, line5, line6);
+
+ canvas.add(
+ makeCircle(line.x1, line.y1, null, line),
+ makeCircle(line.x2, line.y2, line, line2, line5, line6),
+ makeCircle(line2.x2, line2.y2, line2, line3, line4),
+ makeCircle(line3.x2, line3.y2, line3),
+ makeCircle(line4.x2, line4.y2, line4),
+ makeCircle(line5.x2, line5.y2, line5),
+ makeCircle(line6.x2, line6.y2, line6)
+ );
+
+ canvas.on('object:moving', function(e) {
+ var p = e.target;
+ p.line1 && p.line1.set({ 'x2': p.left, 'y2': p.top });
+ p.line2 && p.line2.set({ 'x1': p.left, 'y1': p.top });
+ p.line3 && p.line3.set({ 'x1': p.left, 'y1': p.top });
+ p.line4 && p.line4.set({ 'x1': p.left, 'y1': p.top });
+ canvas.renderAll();
+ });
}
function sample6() {
- var canvas = new fabric.Canvas('c');
- fabric.loadSVGFromURL('../assets/135.svg', function (objects) {
- var obj = objects[0].scale(0.25);
- canvas.centerObject(obj);
- canvas.add(obj);
+ var canvas = new fabric.Canvas('c');
+ fabric.loadSVGFromURL('../assets/135.svg', function(objects) {
+ var obj = objects[0].scale(0.25);
+ canvas.centerObject(obj);
+ canvas.add(obj);
- canvas.add(obj.clone().set({ left: 100, top: 100, angle: -15 }));
- canvas.add(obj.clone().set({ left: 480, top: 100, angle: 15 }));
- canvas.add(obj.clone().set({ left: 100, top: 400, angle: -15 }));
- canvas.add(obj.clone().set({ left: 480, top: 400, angle: 15 }));
+ canvas.add(obj.clone(() => {}).set({ left: 100, top: 100, angle: -15 }));
+ canvas.add(obj.clone(() => {}).set({ left: 480, top: 100, angle: 15 }));
+ canvas.add(obj.clone(() => {}).set({ left: 100, top: 400, angle: -15 }));
+ canvas.add(obj.clone(() => {}).set({ left: 480, top: 400, angle: 15 }));
- canvas.on('mouse:move', function (options) {
- var p = canvas.getPointer(options.e);
+ canvas.on('mouse:move', function(options) {
+ var p = canvas.getPointer(options.e);
- canvas.forEachObject(function (obj) {
- var distX = Math.abs(p.x - obj.left),
- distY = Math.abs(p.y - obj.top),
- dist = Math.round(Math.sqrt(Math.pow(distX, 2) + Math.pow(distY, 2)));
- obj.setOpacity(1 / (dist / 20));
- });
-
- });
+ canvas.forEachObject(function(obj) {
+ var distX = Math.abs(p.x - obj.left),
+ distY = Math.abs(p.y - obj.top),
+ dist = Math.round(Math.sqrt(Math.pow(distX, 2) + Math.pow(distY, 2)));
+ obj.setOpacity(1 / (dist / 20));
+ });
});
+
+ });
}
module fabric {
- export interface ImageWithInfo extends IImage {
- movingLeft: boolean;
- }
+ export interface ImageWithInfo extends IImage {
+ movingLeft: boolean;
+ }
}
function sample7() {
- var canvas = new fabric.Canvas('c', { selection: false });
+ var canvas = new fabric.Canvas('c', { selection: false });
- setInterval(function () {
- fabric.Image.fromURL('../assets/ladybug.png', function (obj) {
- var img = obj;
- img.set('left', fabric.util.getRandomInt(200, 600)).set('top', -50);
- img.movingLeft = !!Math.round(Math.random());
- canvas.add(img);
- });
- }, 1000);
-
-
- var animate = (function animate() {
- canvas.forEachObject(function (obj) {
- var img = obj;
- img.left += (img.movingLeft ? -1 : 1);
- img.top += 1;
- if (img.left > 900 || img.top > 500) {
- canvas.remove(img);
- }
- else {
- img.setAngle(img.getAngle() + 2);
- }
- });
- canvas.renderAll();
- window.requestAnimationFrame(animate);
+ setInterval(function() {
+ fabric.Image.fromURL('../assets/ladybug.png', function(obj) {
+ var img = obj;
+ img.set('left', fabric.util.getRandomInt(200, 600)).set('top', -50);
+ img.movingLeft = !!Math.round(Math.random());
+ canvas.add(img);
});
+ }, 1000);
- animate();
+
+ var animate = (function animate() {
+ canvas.forEachObject(function(obj) {
+ var img = obj;
+ img.left += (img.movingLeft ? -1 : 1);
+ img.top += 1;
+ if (img.left > 900 || img.top > 500) {
+ canvas.remove(img);
+ }
+ else {
+ img.setAngle(img.getAngle() + 2);
+ }
+ });
+ canvas.renderAll();
+ window.requestAnimationFrame(animate);
+ });
+
+ animate();
}
function sample8() {
- function pad(str: string, length: number): string {
- while (str.length < length) {
- str = '0' + str;
- }
- return str;
- };
+ function pad(str: string, length: number): string {
+ while (str.length < length) {
+ str = '0' + str;
+ }
+ return str;
+ };
- var getRandomInt = fabric.util.getRandomInt;
+ var getRandomInt = fabric.util.getRandomInt;
- function getRandomColor() {
- return (
- pad(getRandomInt(0, 255).toString(16), 2) +
- pad(getRandomInt(0, 255).toString(16), 2) +
- pad(getRandomInt(0, 255).toString(16), 2)
- );
+ function getRandomColor() {
+ return (
+ pad(getRandomInt(0, 255).toString(16), 2) +
+ pad(getRandomInt(0, 255).toString(16), 2) +
+ pad(getRandomInt(0, 255).toString(16), 2)
+ );
+ }
+
+ function getRandomNum(min: number, max: number): number {
+ return Math.random() * (max - min) + min;
+ }
+
+ if (/(iPhone|iPod|iPad)/i.test(navigator.userAgent)) {
+ fabric.Object.prototype.cornersize = 30;
+ }
+
+ var canvas = new fabric.Canvas('canvas');
+ // canvas.controlsAboveOverlay = true;
+
+ function updateComplexity() {
+ setTimeout(function() {
+ var element = document.getElementById('complexity').childNodes[1];
+ element.innerHTML = ' ' + canvas.complexity();
+ }, 100);
+ }
+
+ document.getElementById('commands').onclick = function(ev: any) {
+ var ev: any = ev || window.event;
+
+ if (ev.preventDefault) {
+ ev.preventDefault()
+ }
+ else if (ev.returnValue) {
+ ev.returnValue = false;
}
- function getRandomNum(min: number, max: number): number {
- return Math.random() * (max - min) + min;
+ var element: any = ev.target || ev.srcElement;
+ if (element.nodeName.toLowerCase() === 'strong') {
+ element = element.parentNode;
}
- if (/(iPhone|iPod|iPad)/i.test(navigator.userAgent)) {
- fabric.Object.prototype.cornersize = 30;
- }
-
- var canvas = new fabric.Canvas('canvas');
- // canvas.controlsAboveOverlay = true;
-
- function updateComplexity() {
- setTimeout(function () {
- var element = document.getElementById('complexity').childNodes[1];
- element.innerHTML = ' ' + canvas.complexity();
- }, 100);
- }
-
- document.getElementById('commands').onclick = function (ev: any) {
- var ev: any = ev || window.event;
-
- if (ev.preventDefault) {
- ev.preventDefault()
- }
- else if (ev.returnValue) {
- ev.returnValue = false;
- }
-
- var element: any = ev.target || ev.srcElement;
- if (element.nodeName.toLowerCase() === 'strong') {
- element = element.parentNode;
- }
-
- var className = element.className,
- offset = 50,
- left = fabric.util.getRandomInt(0 + offset, 700 - offset),
- top = fabric.util.getRandomInt(0 + offset, 500 - offset),
- angle = fabric.util.getRandomInt(-20, 40),
- width = fabric.util.getRandomInt(30, 50),
- opacity = (function (min, max) { return Math.random() * (max - min) + min; })(0.5, 1);
+ var className = element.className,
+ offset = 50,
+ left = fabric.util.getRandomInt(0 + offset, 700 - offset),
+ top = fabric.util.getRandomInt(0 + offset, 500 - offset),
+ angle = fabric.util.getRandomInt(-20, 40),
+ width = fabric.util.getRandomInt(30, 50),
+ opacity = (function(min, max) { return Math.random() * (max - min) + min; })(0.5, 1);
- switch (className) {
- case 'rect':
- canvas.add(new fabric.Rect({
- left: left,
- top: top,
- fill: '#' + getRandomColor(),
- width: 50,
- height: 50,
- opacity: 0.8
- }));
- break;
+ switch (className) {
+ case 'rect':
+ canvas.add(new fabric.Rect({
+ left: left,
+ top: top,
+ fill: '#' + getRandomColor(),
+ width: 50,
+ height: 50,
+ opacity: 0.8
+ }));
+ break;
- case 'circle':
- canvas.add(new fabric.Circle({
- left: left,
- top: top,
- fill: '#' + getRandomColor(),
- radius: 50,
- opacity: 0.8
- }));
- break;
+ case 'circle':
+ canvas.add(new fabric.Circle({
+ left: left,
+ top: top,
+ fill: '#' + getRandomColor(),
+ radius: 50,
+ opacity: 0.8
+ }));
+ break;
- case 'triangle':
- canvas.add(new fabric.Triangle({
- left: left,
- top: top,
- fill: '#' + getRandomColor(),
- width: 50,
- height: 50,
- opacity: 0.8
- }));
- break;
+ case 'triangle':
+ canvas.add(new fabric.Triangle({
+ left: left,
+ top: top,
+ fill: '#' + getRandomColor(),
+ width: 50,
+ height: 50,
+ opacity: 0.8
+ }));
+ break;
- case 'image1':
- fabric.Image.fromURL('../assets/pug.jpg', function (image) {
- image.set({
- left: left,
- top: top,
- angle: angle,
- padding: 10,
- cornersize: 10
- });
- image.scale(getRandomNum(0.1, 0.25)).setCoords();
- canvas.add(image);
- });
- break;
+ case 'image1':
+ fabric.Image.fromURL('../assets/pug.jpg', function(image) {
+ image.set({
+ left: left,
+ top: top,
+ angle: angle,
+ padding: 10,
+ cornersize: 10
+ });
+ image.scale(getRandomNum(0.1, 0.25)).setCoords();
+ canvas.add(image);
+ });
+ break;
- case 'image2':
- fabric.Image.fromURL('../assets/logo.png', function (image) {
- image.set({
- left: left,
- top: top,
- angle: angle,
- padding: 10,
- cornersize: 10
- });
- image.scale(getRandomNum(0.1, 1)).setCoords();
- canvas.add(image);
- updateComplexity();
- });
- break;
+ case 'image2':
+ fabric.Image.fromURL('../assets/logo.png', function(image) {
+ image.set({
+ left: left,
+ top: top,
+ angle: angle,
+ padding: 10,
+ cornersize: 10
+ });
+ image.scale(getRandomNum(0.1, 1)).setCoords();
+ canvas.add(image);
+ updateComplexity();
+ });
+ break;
- case 'shape':
- var id = element.id, match;
- if (match = /\d+$/.exec(id)) {
- fabric.loadSVGFromURL('../assets/' + match[0] + '.svg', function (objects, options) {
- var loadedObject = fabric.util.groupSVGElements(objects, options);
+ case 'shape':
+ var id = element.id, match;
+ if (match = /\d+$/.exec(id)) {
+ fabric.loadSVGFromURL('../assets/' + match[0] + '.svg', function(objects, options) {
+ var loadedObject = fabric.util.groupSVGElements(objects, options);
- loadedObject.set({
- left: left,
- top: top,
- angle: angle,
- padding: 10,
- cornersize: 10
- });
- loadedObject/*.scaleToWidth(300)*/.setCoords();
-
- // loadedObject.hasRotatingPoint = true;
-
- canvas.add(loadedObject);
- updateComplexity();
- canvas.calcOffset();
- });
- }
- break;
-
- case 'clear':
- if (confirm('Are you sure?')) {
- canvas.clear();
- }
- }
- updateComplexity();
- };
-
- document.getElementById('execute').onclick = function () {
- var code = (document.getElementById('canvas-console')).value;
- if (!(/^\s+$/).test(code)) {
- eval(code);
- }
- };
-
-
- document.getElementById('rasterize').onclick = function () {
- if (!fabric.Canvas.supports('toDataURL')) {
- alert('This browser doesn\'t provide means to serialize canvas to an image');
- }
- else {
- window.open(canvas.toDataURL('png'));
- }
- };
-
- var removeSelectedEl = document.getElementById('remove-selected');
- removeSelectedEl.onclick = function () {
- var activeObject = canvas.getActiveObject(),
- activeGroup = canvas.getActiveGroup();
- if (activeObject) {
- canvas.remove(activeObject);
- }
- else if (activeGroup) {
- var objectsInGroup = activeGroup.getObjects();
- canvas.discardActiveGroup();
- objectsInGroup.forEach(function (object) {
- canvas.remove(object);
+ loadedObject.set({
+ left: left,
+ top: top,
+ angle: angle,
+ padding: 10,
+ cornersize: 10
});
- }
- };
+ loadedObject/*.scaleToWidth(300)*/.setCoords();
- var supportsInputOfType = function (type) {
- return function () {
- var el = document.createElement('input');
- try {
- el.type = type;
- }
- catch (err) { }
- return el.type === type;
- };
- };
-
- var supportsSlider = supportsInputOfType('range'),
- supportsColorpicker = supportsInputOfType('color');
-
- if (supportsSlider()) {
- (function () {
- var controls = document.getElementById('controls');
-
- var sliderLabel = document.createElement('label');
- sliderLabel.htmlFor = 'opacity';
- sliderLabel.innerHTML = 'Opacity: ';
-
- var slider = document.createElement('input');
-
- try { slider.type = 'range'; } catch (err) { }
-
- slider.id = 'opacity';
- slider.value = "100";
-
- controls.appendChild(sliderLabel);
- controls.appendChild(slider);
+ // loadedObject.hasRotatingPoint = true;
+ canvas.add(loadedObject);
+ updateComplexity();
canvas.calcOffset();
+ });
+ }
+ break;
- slider.onchange = function () {
- var activeObject = canvas.getActiveObject(),
- activeGroup = canvas.getActiveGroup();
-
- if (activeObject || activeGroup) {
- (activeObject || activeGroup).setOpacity(parseInt(this.value, 10) / 100);
- canvas.renderAll();
- }
- };
- })();
+ case 'clear':
+ if (confirm('Are you sure?')) {
+ canvas.clear();
+ }
}
+ updateComplexity();
+ };
- if (supportsColorpicker()) {
- (function () {
- var controls = document.getElementById('controls');
-
- var label = document.createElement('label');
- label.htmlFor = 'color';
- label.innerHTML = 'Color: ';
- label.style.marginLeft = '10px';
-
- var colorpicker = document.createElement('input');
- colorpicker.type = 'color';
- colorpicker.id = 'color';
- colorpicker.style.width = '40px';
-
- controls.appendChild(label);
- controls.appendChild(colorpicker);
-
- canvas.calcOffset();
-
- colorpicker.onchange = function () {
- var activeObject = canvas.getActiveObject(),
- activeGroup = canvas.getActiveGroup();
-
- if (activeObject || activeGroup) {
- (activeObject || activeGroup).setFill(this.value);
- canvas.renderAll();
- }
- };
- })();
+ document.getElementById('execute').onclick = function() {
+ var code = (document.getElementById('canvas-console')).value;
+ if (!(/^\s+$/).test(code)) {
+ eval(code);
}
+ };
- var lockHorizontallyEl = document.getElementById('lock-horizontally');
- lockHorizontallyEl.onclick = function () {
- var activeObject: any = canvas.getActiveObject();
- if (activeObject) {
- activeObject.lockMovementX = !activeObject.lockMovementX;
- lockHorizontallyEl.innerHTML = activeObject.lockMovementX
- ? 'Unlock horizontal movement'
- : 'Lock horizontal movement';
- }
- };
- var lockVerticallyEl = document.getElementById('lock-vertically');
- lockVerticallyEl.onclick = function () {
- var activeObject: any = canvas.getActiveObject();
- if (activeObject) {
- activeObject.lockMovementY = !activeObject.lockMovementY;
- lockVerticallyEl.innerHTML = activeObject.lockMovementY
- ? 'Unlock vertical movement'
- : 'Lock vertical movement';
- }
- };
-
- var lockScalingXEl = document.getElementById('lock-scaling-x');
- lockScalingXEl.onclick = function () {
- var activeObject: any = canvas.getActiveObject();
- if (activeObject) {
- activeObject.lockScalingX = !activeObject.lockScalingX;
- lockScalingXEl.innerHTML = activeObject.lockScalingX
- ? 'Unlock horizontal scaling'
- : 'Lock horizontal scaling';
- }
- };
-
- var lockScalingYEl = document.getElementById('lock-scaling-y');
- lockScalingYEl.onclick = function () {
- var activeObject: any = canvas.getActiveObject();
- if (activeObject) {
- activeObject.lockScalingY = !activeObject.lockScalingY;
- lockScalingYEl.innerHTML = activeObject.lockScalingY
- ? 'Unlock vertical scaling'
- : 'Lock vertical scaling';
- }
- };
-
- var lockRotationEl = document.getElementById('lock-rotation');
- lockRotationEl.onclick = function () {
- var activeObject: any = canvas.getActiveObject();
- if (activeObject) {
- activeObject.lockRotation = !activeObject.lockRotation;
- lockRotationEl.innerHTML = activeObject.lockRotation
- ? 'Unlock rotation'
- : 'Lock rotation';
- }
- };
-
- var gradientifyBtn = document.getElementById('gradientify');
-
- var activeObjectButtons = [
- lockHorizontallyEl,
- lockVerticallyEl,
- lockScalingXEl,
- lockScalingYEl,
- lockRotationEl,
- removeSelectedEl,
- gradientifyBtn
- ];
-
- var opacityEl = document.getElementById('opacity');
- if (opacityEl) {
- activeObjectButtons.push(opacityEl);
+ document.getElementById('rasterize').onclick = function() {
+ if (!fabric.Canvas.supports('toDataURL')) {
+ alert('This browser doesn\'t provide means to serialize canvas to an image');
}
- var colorEl = document.getElementById('color');
- if (colorEl) {
- activeObjectButtons.push(colorEl);
+ else {
+ window.open(canvas.toDataURL('png'));
}
+ };
+
+ var removeSelectedEl = document.getElementById('remove-selected');
+ removeSelectedEl.onclick = function() {
+ var activeObject = canvas.getActiveObject(),
+ activeGroup = canvas.getActiveGroup();
+ if (activeObject) {
+ canvas.remove(activeObject);
+ }
+ else if (activeGroup) {
+ var objectsInGroup = activeGroup.getObjects();
+ canvas.discardActiveGroup();
+ objectsInGroup.forEach(function(object) {
+ canvas.remove(object);
+ });
+ }
+ };
+
+ var supportsInputOfType = function(type) {
+ return function() {
+ var el = document.createElement('input');
+ try {
+ el.type = type;
+ }
+ catch (err) { }
+ return el.type === type;
+ };
+ };
+
+ var supportsSlider = supportsInputOfType('range'),
+ supportsColorpicker = supportsInputOfType('color');
+
+ if (supportsSlider()) {
+ (function() {
+ var controls = document.getElementById('controls');
+
+ var sliderLabel = document.createElement('label');
+ sliderLabel.htmlFor = 'opacity';
+ sliderLabel.innerHTML = 'Opacity: ';
+
+ var slider = document.createElement('input');
+
+ try { slider.type = 'range'; } catch (err) { }
+
+ slider.id = 'opacity';
+ slider.value = "100";
+
+ controls.appendChild(sliderLabel);
+ controls.appendChild(slider);
+
+ canvas.calcOffset();
+
+ slider.onchange = function() {
+ var activeObject = canvas.getActiveObject(),
+ activeGroup = canvas.getActiveGroup();
+
+ if (activeObject || activeGroup) {
+ (activeObject || activeGroup).setOpacity(parseInt(this.value, 10) / 100);
+ canvas.renderAll();
+ }
+ };
+ })();
+ }
+
+ if (supportsColorpicker()) {
+ (function() {
+ var controls = document.getElementById('controls');
+
+ var label = document.createElement('label');
+ label.htmlFor = 'color';
+ label.innerHTML = 'Color: ';
+ label.style.marginLeft = '10px';
+
+ var colorpicker = document.createElement('input');
+ colorpicker.type = 'color';
+ colorpicker.id = 'color';
+ colorpicker.style.width = '40px';
+
+ controls.appendChild(label);
+ controls.appendChild(colorpicker);
+
+ canvas.calcOffset();
+
+ colorpicker.onchange = function() {
+ var activeObject = canvas.getActiveObject(),
+ activeGroup = canvas.getActiveGroup();
+
+ if (activeObject || activeGroup) {
+ (activeObject || activeGroup).setFill(this.value);
+ canvas.renderAll();
+ }
+ };
+ })();
+ }
+
+ var lockHorizontallyEl = document.getElementById('lock-horizontally');
+ lockHorizontallyEl.onclick = function() {
+ var activeObject: any = canvas.getActiveObject();
+ if (activeObject) {
+ activeObject.lockMovementX = !activeObject.lockMovementX;
+ lockHorizontallyEl.innerHTML = activeObject.lockMovementX
+ ? 'Unlock horizontal movement'
+ : 'Lock horizontal movement';
+ }
+ };
+
+ var lockVerticallyEl = document.getElementById('lock-vertically');
+ lockVerticallyEl.onclick = function() {
+ var activeObject: any = canvas.getActiveObject();
+ if (activeObject) {
+ activeObject.lockMovementY = !activeObject.lockMovementY;
+ lockVerticallyEl.innerHTML = activeObject.lockMovementY
+ ? 'Unlock vertical movement'
+ : 'Lock vertical movement';
+ }
+ };
+
+ var lockScalingXEl = document.getElementById('lock-scaling-x');
+ lockScalingXEl.onclick = function() {
+ var activeObject: any = canvas.getActiveObject();
+ if (activeObject) {
+ activeObject.lockScalingX = !activeObject.lockScalingX;
+ lockScalingXEl.innerHTML = activeObject.lockScalingX
+ ? 'Unlock horizontal scaling'
+ : 'Lock horizontal scaling';
+ }
+ };
+
+ var lockScalingYEl = document.getElementById('lock-scaling-y');
+ lockScalingYEl.onclick = function() {
+ var activeObject: any = canvas.getActiveObject();
+ if (activeObject) {
+ activeObject.lockScalingY = !activeObject.lockScalingY;
+ lockScalingYEl.innerHTML = activeObject.lockScalingY
+ ? 'Unlock vertical scaling'
+ : 'Lock vertical scaling';
+ }
+ };
+
+ var lockRotationEl = document.getElementById('lock-rotation');
+ lockRotationEl.onclick = function() {
+ var activeObject: any = canvas.getActiveObject();
+ if (activeObject) {
+ activeObject.lockRotation = !activeObject.lockRotation;
+ lockRotationEl.innerHTML = activeObject.lockRotation
+ ? 'Unlock rotation'
+ : 'Lock rotation';
+ }
+ };
+
+ var gradientifyBtn = document.getElementById('gradientify');
+
+ var activeObjectButtons = [
+ lockHorizontallyEl,
+ lockVerticallyEl,
+ lockScalingXEl,
+ lockScalingYEl,
+ lockRotationEl,
+ removeSelectedEl,
+ gradientifyBtn
+ ];
+
+ var opacityEl = document.getElementById('opacity');
+ if (opacityEl) {
+ activeObjectButtons.push(opacityEl);
+ }
+ var colorEl = document.getElementById('color');
+ if (colorEl) {
+ activeObjectButtons.push(colorEl);
+ }
+
+ for (var i = activeObjectButtons.length; i--;) {
+ activeObjectButtons[i].disabled = true;
+ }
+
+ canvas.on('object:selected', onObjectSelected);
+ canvas.on('group:selected', onObjectSelected);
+
+ function onObjectSelected(e) {
+ var selectedObject = e.target;
for (var i = activeObjectButtons.length; i--;) {
- activeObjectButtons[i].disabled = true;
+ activeObjectButtons[i].disabled = false;
}
- canvas.on('object:selected', onObjectSelected);
- canvas.on('group:selected', onObjectSelected);
+ lockHorizontallyEl.innerHTML = (selectedObject.lockMovementX ? 'Unlock horizontal movement' : 'Lock horizontal movement');
+ lockVerticallyEl.innerHTML = (selectedObject.lockMovementY ? 'Unlock vertical movement' : 'Lock vertical movement');
+ lockScalingXEl.innerHTML = (selectedObject.lockScalingX ? 'Unlock horizontal scaling' : 'Lock horizontal scaling');
+ lockScalingYEl.innerHTML = (selectedObject.lockScalingY ? 'Unlock vertical scaling' : 'Lock vertical scaling');
+ lockRotationEl.innerHTML = (selectedObject.lockRotation ? 'Unlock rotation' : 'Lock rotation');
+ }
- function onObjectSelected(e) {
- var selectedObject = e.target;
-
- for (var i = activeObjectButtons.length; i--;) {
- activeObjectButtons[i].disabled = false;
- }
-
- lockHorizontallyEl.innerHTML = (selectedObject.lockMovementX ? 'Unlock horizontal movement' : 'Lock horizontal movement');
- lockVerticallyEl.innerHTML = (selectedObject.lockMovementY ? 'Unlock vertical movement' : 'Lock vertical movement');
- lockScalingXEl.innerHTML = (selectedObject.lockScalingX ? 'Unlock horizontal scaling' : 'Lock horizontal scaling');
- lockScalingYEl.innerHTML = (selectedObject.lockScalingY ? 'Unlock vertical scaling' : 'Lock vertical scaling');
- lockRotationEl.innerHTML = (selectedObject.lockRotation ? 'Unlock rotation' : 'Lock rotation');
+ canvas.on('selection:cleared', function(e) {
+ for (var i = activeObjectButtons.length; i--;) {
+ activeObjectButtons[i].disabled = true;
}
+ });
- canvas.on('selection:cleared', function (e) {
- for (var i = activeObjectButtons.length; i--;) {
- activeObjectButtons[i].disabled = true;
- }
+ var drawingModeEl = document.getElementById('drawing-mode'),
+ drawingOptionsEl = document.getElementById('drawing-mode-options'),
+ drawingColorEl = document.getElementById('drawing-color'),
+ drawingLineWidthEl = document.getElementById('drawing-line-width');
+
+ drawingModeEl.onclick = function() {
+ var canvasWithDrawingMode: any = canvas;
+ canvasWithDrawingMode.isDrawingMode = !canvasWithDrawingMode.isDrawingMode;
+ if (canvasWithDrawingMode.isDrawingMode) {
+ drawingModeEl.innerHTML = 'Cancel drawing mode';
+ drawingModeEl.className = 'is-drawing';
+ drawingOptionsEl.style.display = '';
+ }
+ else {
+ drawingModeEl.innerHTML = 'Enter drawing mode';
+ drawingModeEl.className = '';
+ drawingOptionsEl.style.display = 'none';
+ }
+ };
+
+ canvas.on('path:created', function() {
+ updateComplexity();
+ });
+
+ drawingColorEl.onchange = function() {
+ canvas.freeDrawingColor = drawingColorEl.value;
+ };
+ drawingLineWidthEl.onchange = function() {
+ canvas.freeDrawingLineWidth = parseInt(drawingLineWidthEl.value, 10) || 1; // disallow 0, NaN, etc.
+ };
+
+ canvas.freeDrawingColor = drawingColorEl.value;
+ canvas.freeDrawingLineWidth = parseInt(drawingLineWidthEl.value, 10) || 1;
+
+
+ var text = 'Lorem ipsum dolor sit amet,\nconsectetur adipisicing elit,\nsed do eiusmod tempor incididunt\nut labore et dolore magna aliqua.\n' +
+ 'Ut enim ad minim veniam,\nquis nostrud exercitation ullamco\nlaboris nisi ut aliquip ex ea commodo consequat.';
+
+ document.getElementById('add-text').onclick = function() {
+ var textSample = new fabric.Text(text.slice(0, getRandomInt(0, text.length)), {
+ left: getRandomInt(350, 400),
+ top: getRandomInt(350, 400),
+ fontFamily: 'helvetica',
+ angle: getRandomInt(-10, 10),
+ fill: '#' + getRandomColor(),
+ scaleX: 0.5,
+ scaleY: 0.5,
+ fontWeight: ''
});
+ canvas.add(textSample);
+ updateComplexity();
+ };
- var drawingModeEl = document.getElementById('drawing-mode'),
- drawingOptionsEl = document.getElementById('drawing-mode-options'),
- drawingColorEl = document.getElementById('drawing-color'),
- drawingLineWidthEl = document.getElementById('drawing-line-width');
- drawingModeEl.onclick = function () {
- var canvasWithDrawingMode: any = canvas;
- canvasWithDrawingMode.isDrawingMode = !canvasWithDrawingMode.isDrawingMode;
- if (canvasWithDrawingMode.isDrawingMode) {
- drawingModeEl.innerHTML = 'Cancel drawing mode';
- drawingModeEl.className = 'is-drawing';
- drawingOptionsEl.style.display = '';
+ document.onkeydown = function(e) {
+ var obj = canvas.getActiveObject() || canvas.getActiveGroup();
+ if (obj && e.keyCode === 8) {
+ // this is horrible. need to fix, so that unified interface can be used
+ if (obj.type === 'group') {
+ // var groupObjects = obj.getObjects();
+ // canvas.discardActiveGroup();
+ // groupObjects.forEach(function(obj) {
+ // canvas.remove(obj);
+ // });
+ }
+ else {
+ //canvas.remove(obj);
+ }
+ canvas.renderAll();
+ // return false;
+ }
+ };
+
+ setTimeout(function() {
+ canvas.calcOffset();
+ }, 100);
+
+ if (document.location.search.indexOf('guidelines') > -1) {
+ //initCenteringGuidelines(canvas);
+ //initAligningGuidelines(canvas);
+ }
+
+ gradientifyBtn.onclick = function() {
+ var obj = canvas.getActiveObject();
+ if (obj) {
+ obj.setGradient("fill", {
+ x2: (getRandomInt(0, 1) ? 0 : obj.width),
+ y2: (getRandomInt(0, 1) ? 0 : obj.height),
+ colorStops: {
+ 0: '#' + getRandomColor(),
+ 1: '#' + getRandomColor()
+ }
+ });
+ canvas.renderAll();
+ }
+ };
+
+ var textEl = document.getElementById('text');
+ if (textEl) {
+ textEl.onfocus = function() {
+ var activeObject = canvas.getActiveObject();
+
+ if (activeObject && activeObject.type === 'text') {
+ this.value = (activeObject).text;
+ }
+ };
+ textEl.onkeyup = function(e) {
+ var activeObject = canvas.getActiveObject();
+ if (activeObject) {
+ if (!this.value) {
+ canvas.discardActiveObject();
}
else {
- drawingModeEl.innerHTML = 'Enter drawing mode';
- drawingModeEl.className = '';
- drawingOptionsEl.style.display = 'none';
+ (activeObject).text = this.value;
}
+ canvas.renderAll();
+ }
};
+ }
- canvas.on('path:created', function () {
- updateComplexity();
+ var cmdUnderlineBtn = document.getElementById('text-cmd-underline');
+ if (cmdUnderlineBtn) {
+ activeObjectButtons.push(cmdUnderlineBtn);
+ cmdUnderlineBtn.disabled = true;
+ cmdUnderlineBtn.onclick = function() {
+ var activeObject = canvas.getActiveObject();
+ if (activeObject && activeObject.type === 'text') {
+ activeObject.textDecoration = (activeObject.textDecoration == 'underline' ? '' : 'underline');
+ this.className = activeObject.textDecoration ? 'selected' : '';
+ canvas.renderAll();
+ }
+ };
+ }
+
+ var cmdLinethroughBtn = document.getElementById('text-cmd-linethrough');
+ if (cmdLinethroughBtn) {
+ activeObjectButtons.push(cmdLinethroughBtn);
+ cmdLinethroughBtn.disabled = true;
+ cmdLinethroughBtn.onclick = function() {
+ var activeObject = canvas.getActiveObject();
+ if (activeObject && activeObject.type === 'text') {
+ activeObject.textDecoration = (activeObject.textDecoration == 'line-through' ? '' : 'line-through');
+ this.className = activeObject.textDecoration ? 'selected' : '';
+ canvas.renderAll();
+ }
+ };
+ }
+
+ var cmdOverlineBtn = document.getElementById('text-cmd-overline');
+ if (cmdOverlineBtn) {
+ activeObjectButtons.push(cmdOverlineBtn);
+ cmdOverlineBtn.disabled = true;
+ cmdOverlineBtn.onclick = function() {
+ var activeObject = canvas.getActiveObject();
+ if (activeObject && activeObject.type === 'text') {
+ activeObject.textDecoration = (activeObject.textDecoration == 'overline' ? '' : 'overline');
+ this.className = activeObject.textDecoration ? 'selected' : '';
+ canvas.renderAll();
+ }
+ };
+ }
+
+ var cmdBoldBtn = document.getElementById('text-cmd-bold');
+ if (cmdBoldBtn) {
+ activeObjectButtons.push(cmdBoldBtn);
+ cmdBoldBtn.disabled = true;
+ cmdBoldBtn.onclick = function() {
+ var activeObject = canvas.getActiveObject();
+ if (activeObject && activeObject.type === 'text') {
+ activeObject.fontWeight = (activeObject.fontWeight == 'bold' ? '' : 'bold');
+ this.className = activeObject.fontWeight ? 'selected' : '';
+ canvas.renderAll();
+ }
+ };
+ }
+
+ var cmdItalicBtn = document.getElementById('text-cmd-italic');
+ if (cmdItalicBtn) {
+ activeObjectButtons.push(cmdItalicBtn);
+ cmdItalicBtn.disabled = true;
+ cmdItalicBtn.onclick = function() {
+ var activeObject = canvas.getActiveObject();
+ if (activeObject && activeObject.type === 'text') {
+ activeObject.fontStyle = (activeObject.fontStyle == 'italic' ? '' : 'italic');
+ this.className = activeObject.fontStyle ? 'selected' : '';
+ canvas.renderAll();
+ }
+ };
+ }
+
+ var cmdShadowBtn = document.getElementById('text-cmd-shadow');
+ if (cmdShadowBtn) {
+ activeObjectButtons.push(cmdShadowBtn);
+ cmdShadowBtn.disabled = true;
+ cmdShadowBtn.onclick = function() {
+ var activeObject = canvas.getActiveObject();
+ if (activeObject && activeObject.type === 'text') {
+ activeObject.shadow = !activeObject.shadow ? 'rgba(0,0,0,0.2) 2px 2px 10px' : '';
+ this.className = activeObject.shadow ? 'selected' : '';
+ canvas.renderAll();
+ }
+ };
+ }
+
+ var textAlignSwitch = document.getElementById('text-align');
+ if (textAlignSwitch) {
+ activeObjectButtons.push(textAlignSwitch);
+ textAlignSwitch.disabled = true;
+ textAlignSwitch.onchange = function() {
+ var activeObject = canvas.getActiveObject();
+ if (activeObject && activeObject.type === 'text') {
+ activeObject.textAlign = this.value.toLowerCase();
+ canvas.renderAll();
+ }
+ };
+ }
+
+ var fontFamilySwitch = document.getElementById('font-family');
+ if (fontFamilySwitch) {
+ activeObjectButtons.push(fontFamilySwitch);
+ fontFamilySwitch.disabled = true;
+ fontFamilySwitch.onchange = function() {
+ var activeObject = canvas.getActiveObject();
+ if (activeObject && activeObject.type === 'text') {
+ activeObject.fontFamily = this.value;
+ canvas.renderAll();
+ }
+ };
+ }
+
+ var bgColorField = document.getElementById('text-bg-color');
+ if (bgColorField) {
+ bgColorField.onchange = function() {
+ var activeObject = canvas.getActiveObject();
+ if (activeObject && activeObject.type === 'text') {
+ activeObject.backgroundColor = this.value;
+ canvas.renderAll();
+ }
+ };
+ }
+
+ var strokeColorField = document.getElementById('text-stroke-color');
+ if (strokeColorField) {
+ strokeColorField.onchange = function() {
+ var activeObject = canvas.getActiveObject();
+ if (activeObject && activeObject.type === 'text') {
+ activeObject.stroke = this.value;
+ canvas.renderAll();
+ }
+ };
+ }
+
+ if (supportsSlider) {
+ (function() {
+ var container = document.getElementById('text-controls');
+ var slider = document.createElement('input');
+ var label = document.createElement('label');
+ label.innerHTML = 'Line height: ';
+ try { slider.type = 'range'; } catch (err) { }
+ slider.min = "0";
+ slider.max = "10";
+ slider.step = "0.1";
+ slider.value = "1.5";
+ container.appendChild(label);
+ label.appendChild(slider);
+ slider.title = "Line height";
+ slider.onchange = function() {
+ var activeObject = canvas.getActiveObject();
+ if (activeObject && activeObject.type === 'text') {
+ activeObject.lineHeight = this.value;
+ canvas.renderAll();
+ }
+ };
+
+ canvas.on('object:selected', function(e: fabric.IEvent) {
+ slider.value = String((e.target).lineHeight );
+ });
+ })();
+ }
+
+ document.getElementById('load-svg').onclick = function() {
+ var svg = (document.getElementById('svg-console')).value;
+ fabric.loadSVGFromString(svg, function(objects, options) {
+ var obj = fabric.util.groupSVGElements(objects, options);
+ canvas.add(obj).centerObject(obj).renderAll();
+ obj.setCoords();
});
-
- drawingColorEl.onchange = function () {
- canvas.freeDrawingColor = drawingColorEl.value;
- };
- drawingLineWidthEl.onchange = function () {
- canvas.freeDrawingLineWidth = parseInt(drawingLineWidthEl.value, 10) || 1; // disallow 0, NaN, etc.
- };
-
- canvas.freeDrawingColor = drawingColorEl.value;
- canvas.freeDrawingLineWidth = parseInt(drawingLineWidthEl.value, 10) || 1;
-
-
- var text = 'Lorem ipsum dolor sit amet,\nconsectetur adipisicing elit,\nsed do eiusmod tempor incididunt\nut labore et dolore magna aliqua.\n' +
- 'Ut enim ad minim veniam,\nquis nostrud exercitation ullamco\nlaboris nisi ut aliquip ex ea commodo consequat.';
-
- document.getElementById('add-text').onclick = function () {
- var textSample = new fabric.Text(text.slice(0, getRandomInt(0, text.length)), {
- left: getRandomInt(350, 400),
- top: getRandomInt(350, 400),
- fontFamily: 'helvetica',
- angle: getRandomInt(-10, 10),
- fill: '#' + getRandomColor(),
- scaleX: 0.5,
- scaleY: 0.5,
- fontWeight: ''
- });
- canvas.add(textSample);
- updateComplexity();
- };
-
-
- document.onkeydown = function (e) {
- var obj = canvas.getActiveObject() || canvas.getActiveGroup();
- if (obj && e.keyCode === 8) {
- // this is horrible. need to fix, so that unified interface can be used
- if (obj.type === 'group') {
- // var groupObjects = obj.getObjects();
- // canvas.discardActiveGroup();
- // groupObjects.forEach(function(obj) {
- // canvas.remove(obj);
- // });
- }
- else {
- //canvas.remove(obj);
- }
- canvas.renderAll();
- // return false;
- }
- };
-
- setTimeout(function () {
- canvas.calcOffset();
- }, 100);
-
- if (document.location.search.indexOf('guidelines') > -1) {
- //initCenteringGuidelines(canvas);
- //initAligningGuidelines(canvas);
- }
-
- gradientifyBtn.onclick = function () {
- var obj = canvas.getActiveObject();
- if (obj) {
- obj.setGradientFill({
- x2: (getRandomInt(0, 1) ? 0 : obj.width),
- y2: (getRandomInt(0, 1) ? 0 : obj.height),
- colorStops: {
- 0: '#' + getRandomColor(),
- 1: '#' + getRandomColor()
- }
- });
- canvas.renderAll();
- }
- };
-
- var textEl = document.getElementById('text');
- if (textEl) {
- textEl.onfocus = function () {
- var activeObject = canvas.getActiveObject();
-
- if (activeObject && activeObject.type === 'text') {
- this.value = (activeObject).text;
- }
- };
- textEl.onkeyup = function (e) {
- var activeObject = canvas.getActiveObject();
- if (activeObject) {
- if (!this.value) {
- canvas.discardActiveObject();
- }
- else {
- (activeObject).text = this.value;
- }
- canvas.renderAll();
- }
- };
- }
-
- var cmdUnderlineBtn = document.getElementById('text-cmd-underline');
- if (cmdUnderlineBtn) {
- activeObjectButtons.push(cmdUnderlineBtn);
- cmdUnderlineBtn.disabled = true;
- cmdUnderlineBtn.onclick = function () {
- var activeObject = canvas.getActiveObject();
- if (activeObject && activeObject.type === 'text') {
- activeObject.textDecoration = (activeObject.textDecoration == 'underline' ? '' : 'underline');
- this.className = activeObject.textDecoration ? 'selected' : '';
- canvas.renderAll();
- }
- };
- }
-
- var cmdLinethroughBtn = document.getElementById('text-cmd-linethrough');
- if (cmdLinethroughBtn) {
- activeObjectButtons.push(cmdLinethroughBtn);
- cmdLinethroughBtn.disabled = true;
- cmdLinethroughBtn.onclick = function () {
- var activeObject = canvas.getActiveObject();
- if (activeObject && activeObject.type === 'text') {
- activeObject.textDecoration = (activeObject.textDecoration == 'line-through' ? '' : 'line-through');
- this.className = activeObject.textDecoration ? 'selected' : '';
- canvas.renderAll();
- }
- };
- }
-
- var cmdOverlineBtn = document.getElementById('text-cmd-overline');
- if (cmdOverlineBtn) {
- activeObjectButtons.push(cmdOverlineBtn);
- cmdOverlineBtn.disabled = true;
- cmdOverlineBtn.onclick = function () {
- var activeObject = canvas.getActiveObject();
- if (activeObject && activeObject.type === 'text') {
- activeObject.textDecoration = (activeObject.textDecoration == 'overline' ? '' : 'overline');
- this.className = activeObject.textDecoration ? 'selected' : '';
- canvas.renderAll();
- }
- };
- }
-
- var cmdBoldBtn = document.getElementById('text-cmd-bold');
- if (cmdBoldBtn) {
- activeObjectButtons.push(cmdBoldBtn);
- cmdBoldBtn.disabled = true;
- cmdBoldBtn.onclick = function () {
- var activeObject = canvas.getActiveObject();
- if (activeObject && activeObject.type === 'text') {
- activeObject.fontWeight = (activeObject.fontWeight == 'bold' ? '' : 'bold');
- this.className = activeObject.fontWeight ? 'selected' : '';
- canvas.renderAll();
- }
- };
- }
-
- var cmdItalicBtn = document.getElementById('text-cmd-italic');
- if (cmdItalicBtn) {
- activeObjectButtons.push(cmdItalicBtn);
- cmdItalicBtn.disabled = true;
- cmdItalicBtn.onclick = function () {
- var activeObject = canvas.getActiveObject();
- if (activeObject && activeObject.type === 'text') {
- activeObject.fontStyle = (activeObject.fontStyle == 'italic' ? '' : 'italic');
- this.className = activeObject.fontStyle ? 'selected' : '';
- canvas.renderAll();
- }
- };
- }
-
- var cmdShadowBtn = document.getElementById('text-cmd-shadow');
- if (cmdShadowBtn) {
- activeObjectButtons.push(cmdShadowBtn);
- cmdShadowBtn.disabled = true;
- cmdShadowBtn.onclick = function () {
- var activeObject = canvas.getActiveObject();
- if (activeObject && activeObject.type === 'text') {
- activeObject.textShadow = !activeObject.textShadow ? 'rgba(0,0,0,0.2) 2px 2px 10px' : '';
- this.className = activeObject.textShadow ? 'selected' : '';
- canvas.renderAll();
- }
- };
- }
-
- var textAlignSwitch = document.getElementById('text-align');
- if (textAlignSwitch) {
- activeObjectButtons.push(textAlignSwitch);
- textAlignSwitch.disabled = true;
- textAlignSwitch.onchange = function () {
- var activeObject = canvas.getActiveObject();
- if (activeObject && activeObject.type === 'text') {
- activeObject.textAlign = this.value.toLowerCase();
- canvas.renderAll();
- }
- };
- }
-
- var fontFamilySwitch = document.getElementById('font-family');
- if (fontFamilySwitch) {
- activeObjectButtons.push(fontFamilySwitch);
- fontFamilySwitch.disabled = true;
- fontFamilySwitch.onchange = function () {
- var activeObject = canvas.getActiveObject();
- if (activeObject && activeObject.type === 'text') {
- activeObject.fontFamily = this.value;
- canvas.renderAll();
- }
- };
- }
-
- var bgColorField = document.getElementById('text-bg-color');
- if (bgColorField) {
- bgColorField.onchange = function () {
- var activeObject = canvas.getActiveObject();
- if (activeObject && activeObject.type === 'text') {
- activeObject.backgroundColor = this.value;
- canvas.renderAll();
- }
- };
- }
-
- var strokeColorField = document.getElementById('text-stroke-color');
- if (strokeColorField) {
- strokeColorField.onchange = function () {
- var activeObject = canvas.getActiveObject();
- if (activeObject && activeObject.type === 'text') {
- activeObject.strokeStyle = this.value;
- canvas.renderAll();
- }
- };
- }
-
- if (supportsSlider) {
- (function () {
- var container = document.getElementById('text-controls');
- var slider = document.createElement('input');
- var label = document.createElement('label');
- label.innerHTML = 'Line height: ';
- try { slider.type = 'range'; } catch (err) { }
- slider.min = "0";
- slider.max = "10";
- slider.step = "0.1";
- slider.value = "1.5";
- container.appendChild(label);
- label.appendChild(slider);
- slider.title = "Line height";
- slider.onchange = function () {
- var activeObject = canvas.getActiveObject();
- if (activeObject && activeObject.type === 'text') {
- activeObject.lineHeight = this.value;
- canvas.renderAll();
- }
- };
-
- canvas.on('object:selected', function (e) {
- slider.value = e.target.lineHeight;
- });
- })();
- }
-
- document.getElementById('load-svg').onclick = function () {
- var svg = (document.getElementById('svg-console')).value;
- fabric.loadSVGFromString(svg, function (objects, options) {
- var obj = fabric.util.groupSVGElements(objects, options);
- canvas.add(obj).centerObject(obj).renderAll();
- obj.setCoords();
- });
- };
+ };
}
function sample9() {
- var canvas = new fabric.Canvas('c');
- canvas.setBackgroundImage('yolo.jpg', () => {"a"}, {opacity: 45});
- canvas.setBackgroundImage('yolo.jpg', () => {"a"});
+ var canvas = new fabric.Canvas('c');
+ canvas.setBackgroundImage('yolo.jpg',() => { "a" }, { opacity: 45 });
+ canvas.setBackgroundImage('yolo.jpg',() => { "a" });
}
diff --git a/fabricjs/fabricjs.d.ts b/fabricjs/fabricjs.d.ts
index f764d4768..503b8c7db 100644
--- a/fabricjs/fabricjs.d.ts
+++ b/fabricjs/fabricjs.d.ts
@@ -1,899 +1,4596 @@
-// Type definitions for FabricJS
+// Type definitions for FabricJS v1.5.0
// Project: http://fabricjs.com/
-// Definitions by: Oliver Klemencic
+// Definitions by: Oliver Klemencic , Joseph Livecchi
// Definitions: https://github.com/borisyankov/DefinitelyTyped
+/* tslint:disable:no-unused-variable */
+/* tslint:disable:whitespace */
+/* tslint:disable:typedef */
+
+// Support AMD require
+declare module "fabric" {
+ export = fabric;
+}
+
declare module fabric {
- function createCanvasForNode(width: number, height: number): ICanvas;
- function getCSSRules(doc: SVGElement);
- function getGradientDefs(doc: SVGElement);
- function loadSVGFromString(text: string, callback: (results: IObject[], options) => void , reviver?: (el, obj) => void );
- function loadSVGFromURL(url, callback: (results: IObject[], options) => void , reviver?: (el, obj) => void );
- function log(values);
- function parseAttributes(element, attributes: any[]): any;
- function parseElements(elements: any[], callback, options, reviver);
- function parsePointsAttribute(points: string): any[];
- function parseStyleAttribute(element: SVGElement);
- function parseSVGDocument(doc: SVGElement, callback: (results, options) => void , reviver?: (el, obj) => void );
- function parseTransformAttribute(attributeValue: string);
- function warn(values);
-
- var isLikelyNode: boolean;
- var isTouchSupported: boolean;
-
- export interface IObservable {
- observe(eventCollection: IEventList);
- on(eventCollection: IEventList);
-
- observe(eventName: string, handler: (e) => any);
- on(eventName: string, handler: (e) => any);
-
- fire(eventName: string, options);
- stopObserving(eventName: string, handler: (e) => any);
-
- off(eventName, handler);
- }
-
- export interface IFilter {
- new (): IFilter;
- new (options: any): IFilter;
- }
-
- export interface IEventList {
- [index: string]: (e: Event) => void;
- }
-
- export interface IObjectOptions {
- angle?: number;
- borderColor?: string;
- borderOpacityWhenMoving?: number;
- borderScaleFactor?: number;
- cornerColor?: string;
- cornersize?: number;
- fill?: string;
- fillRule?: string;
- flipX?: boolean;
- flipY?: boolean;
- hasBorders?: boolean;
- hasControls?: boolean;
- hasRotatingPoint?: boolean;
- height?: number;
- includeDefaultValues?: boolean;
- left?: number;
- lockMovementX?: boolean;
- lockMovementY?: boolean;
- lockScalingX?: boolean;
- lockScalingY?: boolean;
- lockUniScaling?: boolean;
- lockRotation?: boolean;
- opacity?: number;
- originX?: string;
- originY?: string;
- overlayFill?: string;
- padding?: number;
- perPixelTargetFind?: boolean;
- rotatingPointOffset?: number;
- scaleX?: number;
- scaleY?: number;
- selectable?: boolean;
- stateProperties?: any[];
- stroke?: string;
- strokeDashArray?: any[];
- strokeWidth?: number;
- top?: number;
- transformMatrix?: any[];
- transparentCorners?: boolean;
- type?: string;
- width?: number;
- }
-
- export interface ITextOptions extends IObjectOptions {
- fontSize?: number;
- fontWeight?: any;
- fontFamily?: string;
- textDecoration?: string;
- textShadow?: string;
- textAlign?: string;
- fontStyle?: string;
- lineHeight?: number;
- strokeStyle?: string;
- strokeWidth?: number;
- backgroundColor?: string;
- textBackgroundColor?: string;
- path?: string;
- type?: string;
- useNative?: Boolean;
- }
-
- export interface ICircleOptions extends IObjectOptions {
- radius?: number;
- }
-
- export interface IPoint {
- add(that: IPoint): IPoint;
- addEquals(that: IPoint): IPoint;
- distanceFrom(that: IPoint);
- divide(scalar: number);
- divideEquals(scalar: number);
- eq(that: IPoint);
- gt(that: IPoint);
- gte(that: IPoint);
- init(x, y);
- lerp(that: IPoint, t);
- lt(that: IPoint);
- lte(that: IPoint);
- max(that: IPoint);
- min(that: IPoint);
- multiply(scalar);
- multiplyEquals(scalar);
- scalarAdd(scalar): IPoint;
- scalarAddEquals(scalar: number, thisArg: IPoint);
- scalarSubtract(scalar: number);
- scalarSubtractEquals(scalar);
- setFromPoint(that: IPoint);
- setXY(x, y);
- subtract(that: IPoint): IPoint;
- subtractEquals(that: IPoint): IPoint;
- swap(that: IPoint);
- tostring(): string;
- }
-
- export interface IRect extends IObject {
- x: number;
- y: number;
- rx: number;
- ry: number;
-
- complexity(): number;
- initialize(options: any);
- initialize(points: number[], options: any): IRect;
- toObject(propertiesToInclude: any[]): any;
- toSVG(): string;
- }
-
- export interface IText extends IObject {
- fontSize: number;
- fontWeight: any;
- fontFamily: string;
- text: string;
- textDecoration: string;
- textShadow?: string;
- textAlign: string;
- fontStyle: string;
- lineHeight: number;
- strokeStyle: string;
- strokeWidth: number;
- backgroundColor: string;
- textBackgroundColor: string;
- path?: string;
- type: string;
- useNative: Boolean;
-
- initialize(options: any);
- initialize(text: string, options: any): IText;
- toString(): string;
- render(ctx: CanvasRenderingContext2D, noTransform: boolean);
- toObject(propertiesToInclude: any[]): IObject;
- toSVG(): string;
- setColor(value: string): IText;
- setFontsize(value: number): IText;
- getText(): string;
- setText(value: string): IText;
- }
-
- export interface ITriangle extends IObject {
- complexity(): number;
- initialize(options: any): ITriangle;
- toSVG(): string;
- }
-
- export interface IEllipse {
- initialize(options: any): any;
- toObject(propertiesToInclude: any[]): any;
- toSVG(): string;
- render(ctx: CanvasRenderingContext2D, noTransform: boolean);
- complexity(): number;
- }
-
- export interface IGradient {
- initialize(options): any;
- toObject(): any;
- toLiveGradient(ctx: CanvasRenderingContext2D): any;
- }
-
- export interface IColor {
- getSource(): any[];
- setSource(source: any[]): any;
- toRgb(): string;
- toRgba(): string;
- toHex(): string;
- getAlpha(): number;
- setAlpha(alpha: number): IColor;
- toGrayscale(): IColor;
- toBlackWhite(threshold): IColor;
- overlayWith(otherColor: string): IColor;
- overlayWith(otherColor: IColor): IColor;
- }
-
- export interface IElement {
- }
-
- export interface IObject extends IObservable {
-
- // constraint properties
- lockMovementX: boolean;
- lockMovementY: boolean;
- lockScalingX: boolean;
- lockScalingY: boolean;
- lockScaling: boolean;
- lockUniScaling: boolean;
- lockRotation: boolean;
-
- getCurrentWidth(): number;
- getCurrentHeight(): number;
-
- originX: string;
- originY: string;
-
- angle: number;
- getAngle(): number;
- setAngle(value: number): IObject;
-
- borderColor: string;
- getBorderColor(): string;
- setBorderColor(value: string): IObject;
-
- borderOpacityWhenMoving: number;
- borderScaleFactor: number;
- getBorderScaleFactor(): number;
-
- cornerColor: string;
-
- cornersize: number;
- getCornersize(): number;
- setCornersize(value: number): IObject;
-
- fill: string;
- getFill(): string;
- setFill(value: string): IObject;
-
- fillRule: string;
- getFillRule(): string;
- setFillRule(value: string): IObject;
-
- flipX: boolean;
- getFlipX(): boolean;
- setFlipX(value: boolean): IObject;
-
- flipY: boolean;
- getFlipY(): boolean;
- setFlipY(value: boolean): IObject;
-
- hasBorders: boolean;
-
- hasControls: boolean;
- hasRotatingPoint: boolean;
-
- height: number;
- getHeight(): number;
- setHeight(value: number): IObject;
-
- includeDefaultValues: boolean;
-
- left: number;
- getLeft(): number;
- setLeft(value: number): IObject;
-
- opacity: number;
- getOpacity(): number;
- setOpacity(value: number): IObject;
-
- overlayFill: string;
- getOverlayFill(): string;
- setOverlayFill(value: string): IObject;
-
- padding: number;
- perPixelTargetFind: boolean;
- rotatingPointOffset: number;
-
- scaleX: number;
- getScaleX(): number;
- setScaleX(value: number): IObject;
-
- scaleY: number;
- getScaleY(): number;
- setScaleY(value: number): IObject;
-
- selectable: boolean;
- stateProperties: any[];
- stroke: string;
- strokeDashArray: any[];
- strokeWidth: number;
-
- top: number;
- getTop(): number;
- setTop(value: number): IObject;
-
- transformMatrix: any[];
- transparentCorners: boolean;
- type: string;
-
- width: number;
- getWidth(): number;
- setWidth(value: number): IObject;
-
- // methods
- bringForward(intersecting?: boolean): IObject;
- bringToFront(): IObject;
- center(): IObject;
- centerH(): IObject;
- centerV(): IObject;
- clone(callback?, propertiesToInclude?): IObject;
- cloneAsImage(callback): IObject;
- complexity(): number;
- drawBorders(context: CanvasRenderingContext2D): IObject;
- drawCorners(context: CanvasRenderingContext2D): IObject;
- get (property: string): any;
- getBoundingRect(): {left:number; top:number; width:number; height:number};
- getBoundingRectHeight(): number;
- getBoundingRectWidth(): number;
- getSvgStyles(): string;
- getSvgTransform(): string;
- hasStateChanged(): boolean;
- initialize(options: any);
- intersectsWithObject(other: IObject): boolean;
- intersectsWithRect(selectionTL: any, selectionBR: any): boolean;
- isActive(): boolean;
- isContainedWithinObject(other: IObject): boolean;
- isContainedWithinRect(selectionTL: any, selectionBR: any): boolean;
- isType(type: string): boolean;
- remove(): IObject;
- render(ctx: CanvasRenderingContext2D, noTransform: boolean);
- rotate(value: number): IObject;
- saveState(): IObject;
- scale(value: number): IObject;
- scaleToHeight(value: number): IObject;
- scaleToWidth(value: number): IObject;
- sendBackwards(intersecting?: boolean): IObject;
- sendToBack(): IObject;
-
- set (properties: IObjectOptions): IObject;
- set (name: string, value: any): IObject;
- setActive(active: boolean): IObject;
- setCoords();
- setGradientFill(options);
- setOptions(options: any);
- setSourcePath(value: string): IObject;
- toDatalessObject(propertiesToInclude): any;
- toDataURL(callback): string;
- toggle(property): IObject;
- toGrayscale(): IObject;
- toJSON(propertiesToInclude): string;
- toObject(propertiesToInclude): any;
- tostring(): string;
- transform(ctx: CanvasRenderingContext2D);
- }
-
- export interface IGroup extends IObject {
- type: string;
-
- activateAllObjects(): IGroup;
- add(object): IGroup;
- addWithUpdate(object): IGroup;
- complexity(): number;
- contains(object): boolean;
- containsPoint(point): boolean;
- destroy(): IGroup;
- getObjects(): IObject[];
- hasMoved(): boolean;
- initialize(options: any);
- initialize(objects, options): any;
- item(index): IObject;
- remove(object?): IGroup;
- removeWithUpdate(object): IGroup;
- render(ctx, noTransform): void;
- saveCoords(): IGroup;
- setObjectsCoords(): IGroup;
- size(): number;
- toGrayscale(): IGroup;
- toObject(propertiesToInclude: any[]): any;
- tostring(): string;
- toSVG(): string;
- }
-
-
- export interface ILine extends IObject {
- x1: number;
- x2: number;
- y1: number;
- y2: number;
-
- complexity(): number;
- initialize(options: any);
- initialize(points: number[], options: any): ILine;
- toObject(propertiesToInclude: any[]): any;
- toSVG(): string;
- }
-
- export interface IIntersection {
- appendPoint(status: string);
- appendPoints(status: string);
- init(status: string);
- }
-
- export interface IImage extends IObject {
- filters: any;
-
- applyFilters(callback);
- clone(callback?, propertiesToInclude?): IObject;
- clone(propertiesToInclude, callback);
- complexity(): number;
- getElement(): HTMLImageElement;
- getOriginalSize(): { width: number; height: number; };
- getSrc(): string;
- initialize(options: any);
- initialize(element: string, options: any);
- initialize(element: HTMLImageElement, options: any);
- render(ctx: CanvasRenderingContext2D, noTransform: boolean);
- setElement(element): IImage;
- toObject(propertiesToInclude): any;
- tostring(): string;
- toSVG(): string;
- }
-
- export interface ICircle extends IObject {
- // methods
- complexity(): number;
- getRadiusX(): number;
- getRadiusY(): number;
- initialize(options: ICircleOptions): ICircle;
- setRadius(value: number): number;
- toObject(propertiesToInclude): any;
- toSVG(): string;
- }
-
-
-
- export interface IPath extends IObject {
- complexity(): number;
- initialize(options: any);
- initialize(path, options);
- render(ctx: CanvasRenderingContext2D, noTransform: boolean);
- toDatalessObject(propertiesToInclude): any;
- toObject(propertiesToInclude): any;
- tostring(): string;
- toSVG(): string;
- }
-
- export interface IPolygon extends IObject {
- complexity(): number;
- initialize(options: any);
- initialize(points, options);
- toObject(propertiesToInclude): any;
- toSVG(): string;
- }
-
- export interface IPolyline extends IObject {
- complexity(): number;
- initialize(options: any);
- initialize(points, options);
- toObject(propertiesToInclude): any;
- toSVG(): string;
- }
-
- export interface IPathGroup extends IObject {
- complexity(): number;
- initialize(options: any);
- initialize(paths, options);
- isSameColor(): boolean;
- render(ctx: CanvasRenderingContext2D);
- toDatalessObject(propertiesToInclude): any;
- toGrayscale(): IPathGroup;
- toObject(propertiesToInclude): any;
- tostring(): string;
- toSVG(): string;
- }
-
- export interface IStaticCanvas extends IObservable {
-
- // fields
- backgroundColor: string;
- backgroundImage: string;
- backgroundImageOpacity: number;
- backgroundImageStretch: number;
- clipTo(clipFunction: (context: CanvasRenderingContext2D) => void );
- controlsAboveOverlay: boolean;
- includeDefaultValues: boolean;
- overlayImage: string;
- overlayImageLeft: number;
- overlayImageTop: number;
- renderOnAddition: boolean;
- stateful: boolean;
-
- // static
- EMPTY_JSON: string;
- supports(methodName: string): boolean;
-
- // methods
- add(...object: IObject[]): ICanvas;
- bringForward(object: IObject): ICanvas;
- calcOffset(): ICanvas;
- centerObject(object: IObject): ICanvas;
- centerObjectH(object: IObject): ICanvas;
- centerObjectV(object: IObject): ICanvas;
- clear(): ICanvas;
- clearContext(context: CanvasRenderingContext2D): ICanvas;
- complexity(): number;
- dispose(): ICanvas;
- drawControls();
- forEachObject(callback: (object: IObject) => void , context?: CanvasRenderingContext2D): ICanvas;
- getActiveGroup(): IGroup;
- getActiveObject(): IObject;
- getCenter(): IObject;
- getContext(): CanvasRenderingContext2D;
- getElement(): HTMLCanvasElement;
- getHeight(): number;
- getObjects(): IObject[];
- getWidth(): number;
- insertAt(object: IObject, index: number, nonSplicing: boolean): ICanvas;
- isEmpty(): boolean;
- item(index: number): IObject;
- onBeforeScaleRotate(target: IObject);
- remove(object: IObject): IObject;
- renderAll(allOnTop?: boolean): ICanvas;
- renderTop(): ICanvas;
-
- sendBackwards(object: IObject): ICanvas;
- sendToBack(object: IObject): ICanvas;
- setBackgroundImage(image: any, callback: () => any, options?): ICanvas;
- setDimensions(object: { width: number; height: number; }): ICanvas;
- setHeight(height: number): ICanvas;
- setOverlayImage(url: string, callback: () => any, options): ICanvas;
- setWidth(width: number): ICanvas;
- toDatalessJSON(propertiesToInclude?: any[]): string;
- toDatalessObject(propertiesToInclude?: any[]): string;
- toDataURL(format: string, quality?: number): string;
- toDataURLWithMultiplier(propertiesToInclude: any[]): string;
- toGrayscale(propertiesToInclude: any[]): string;
- toJSON(propertiesToInclude: any[]): string;
- toObject(propertiesToInclude: any[]): string;
- tostring(): string;
- toSVG(): string;
- }
-
- export interface ICanvas extends IStaticCanvas {
-
- // constructors
- (element: HTMLCanvasElement): ICanvas;
- (element: string): ICanvas;
-
- _objects: IObject[];
-
- // fields
- containerClass: string;
- defaultCursor: string;
- freeDrawingColor: string;
- freeDrawingLineWidth: number;
- hoverCursor: string;
- interactive: boolean;
- moveCursor: string;
- perPixelTargetFind: boolean;
- rotationCursor: string;
- selection: boolean;
- selectionBorderColor: string;
- selectionColor: string;
- selectionDashArray: number[];
- selectionLineWidth: number;
- targetFindTolerance: number;
-
- // methods
- containsPoint(e: Event, target: IObject): boolean;
- deactivateAll(): ICanvas;
- deactivateAllWithDispatch(): ICanvas;
- discardActiveGroup(): ICanvas;
- discardActiveObject(): ICanvas;
- drawDashedLine(ctx: CanvasRenderingContext2D, x: number, y: number, x2: number, y2: number, dashArray: number[]): ICanvas;
- findTarget(e: MouseEvent, skipGroup: boolean): ICanvas;
- getActiveGroup(): IGroup;
- getActiveObject(): IObject;
- getPointer(e): { x: number; y: number; };
- getSelectionContext(): CanvasRenderingContext2D;
- getSelectionElement(): HTMLCanvasElement;
- setActiveGroup(group: IGroup): ICanvas;
- setActiveObject(object: IObject, e?): ICanvas;
-
- loadFromJSON(json, callback: () => void): void;
- loadFromDatalessJSON(json, callback: () => void): void;
- }
-
- export interface IPattern {
- (options: IPatternOptions): IPattern;
-
- initialise(options: IPatternOptions): IPattern;
-
- toLive(ctx: CanvasRenderingContext2D): IPattern;
- toObject(): any;
- toSVG(): string;
-
- offsetX: number;
- offsetY: number;
- repeat: string;
- source: any;
- }
-
- export interface IBrightnessFilter {
- }
- export interface IInvertFilter {
- }
- export interface IRemoveWhiteFilter {
- }
- export interface IGrayscaleFilter {
- }
- export interface ISepiaFilter {
- }
- export interface ISepia2Filter {
- }
- export interface INoiseFilter {
- }
- export interface IGradientTransparencyFilter {
- }
- export interface IPixelateFilter {
- }
- export interface IConvoluteFilter {
- }
-
- export interface ICanvasOptions {
- containerClass?: string;
- defaultCursor?: string;
- freeDrawingColor?: string;
- freeDrawingLineWidth?: number;
- hoverCursor?: string;
- interactive?: boolean;
- moveCursor?: string;
- perPixelTargetFind?: boolean;
- rotationCursor?: string;
- selection?: boolean;
- selectionBorderColor?: string;
- selectionColor?: string;
- selectionDashArray?: number[];
- selectionLineWidth?: number;
- targetFindTolerance?: number;
-
- backgroundColor?: string;
- backgroundImage?: string;
- backgroundImageOpacity?: number;
- backgroundImageStretch?: number;
- controlsAboveOverlay?: boolean;
- includeDefaultValues?: boolean;
- overlayImage?: string;
- overlayImageLeft?: number;
- overlayImageTop?: number;
- renderOnAddition?: boolean;
- stateful?: boolean;
- }
-
- export interface IPatternOptions {
- source: any;
- offsetX: number;
- offsetY: number;
- repeat: string;
- }
-
- export interface IRectOptions extends IObjectOptions {
- x?: number;
- y?: number;
- rx?: number;
- ry?: number;
- }
-
- export interface ITriangleOptions extends IObjectOptions {
- }
-
- var Rect: {
- fromElement(element: SVGElement, options: IRectOptions): IRect;
- fromObject(object): IRect;
- new (options?: IRectOptions): IRect;
- prototype: any;
- }
-
- var Triangle: {
- new (options?: ITriangleOptions): ITriangle;
- }
-
- var Canvas: {
- new (element: HTMLCanvasElement, options?: ICanvasOptions): ICanvas;
- new (element: string, options?: ICanvasOptions): ICanvas;
-
- EMPTY_JSON: string;
- supports(methodName: string): boolean;
- prototype: any;
- }
-
- var StaticCanvas: {
- new (element: HTMLCanvasElement, options?: ICanvasOptions): ICanvas;
- new (element: string, options?: ICanvasOptions): ICanvas;
-
- EMPTY_JSON: string;
- supports(methodName: string): boolean;
- prototype: any;
- }
-
- var Pattern: {
- new (options: IPatternOptions): IPattern;
-
- prototype: any;
- }
-
- var Circle: {
- ATTRIBUTE_NAMES: string[];
- fromElement(element: SVGElement, options: ICircleOptions): ICircle;
- fromObject(object): ICircle;
- new (options?: ICircleOptions): ICircle;
- prototype: any;
- }
-
- var Group: {
- new (items?: any[], options?: IObjectOptions): IGroup;
- }
-
- var Line: {
- ATTRIBUTE_NAMES: string[];
- fromElement(element: SVGElement, options): ILine;
- fromObject(object): ILine;
- prototype: any;
- new (points: number[], objObjects?: IObjectOptions): ILine;
- }
-
- var Intersection: {
- intersectLineLine(a1, a2, b1, b2);
- intersectLinePolygon(a1, a2, points);
- intersectPolygonPolygon(points1, points2);
- intersectPolygonRectangle(points, r1, r2);
- }
-
- var Path: {
- fromElement(element: SVGElement, options): IPath;
- fromObject(object): IPath;
- new (): IPath;
- }
-
- var PathGroup: {
- fromObject(object): IPathGroup;
- new (): IPathGroup;
- prototype: any;
- }
-
- var Point: {
- new (x, y): IPoint;
- prototype: any;
- }
-
- var Object: {
- prototype: any;
- }
-
- var Polygon: {
- fromObject(object): IPolygon;
- fromElement(element: SVGElement, options): IPolygon;
- new (): IPolygon;
- prototype: any;
- }
-
- var Polyline: {
- fromObject(object): IPolyline;
- fromElement(element: SVGElement, options): IPolyline;
- new (): IPolyline;
- prototype: any;
- }
-
- var Text: {
- new (text: string, options?: ITextOptions): IText;
- }
-
- var Image: {
- fromURL(url: string): IImage;
- fromURL(url: string, callback: (image: IImage) => any): IImage;
- fromURL(url: string, callback: (image: IImage) => any, objObjects: IObjectOptions): IImage;
- new (element: HTMLImageElement, objObjects: IObjectOptions): IImage;
- prototype: any;
-
- filters:
- {
- Grayscale: {
- new (): IGrayscaleFilter;
- };
- Brightness: {
- new (options?: { brightness: number; }): IBrightnessFilter;
- };
- RemoveWhite: {
- new (options?: {
- threshold?: string; // TODO: Check this
- distance?: string; // TODO: Check this
- }): IRemoveWhiteFilter;
- };
- Invert: {
- new (): IInvertFilter;
- };
- Sepia: {
- new (): ISepiaFilter;
- };
- Sepia2: {
- new (): ISepia2Filter;
- };
- Noise: {
- new (options?: {
- noise?: number;
- }): INoiseFilter;
- };
- GradientTransparency: {
- new (options?: {
- threshold?: number;
- }): IGradientTransparencyFilter;
- };
- Pixelate: {
- new (options?: {
- color?: any;
- }): IPixelateFilter;
- };
- Convolute: {
- new (options?: {
- matrix: any;
- }): IConvoluteFilter;
- };
- };
-
- }
-
- var util: {
- addClass(element: HTMLElement, className: string);
- addListener(element, eventName: string, handler);
- animate(options: {
- onChange?: (value: number) => void;
- onComplete?: () => void;
- startValue?: number;
- endValue?: number;
- byValue?: number;
- easing?: (currentTime, startValue, byValue, duration) => number;
- duration?: number;
- });
- createClass(parent, properties);
- degreesToRadians(degrees: number): number;
- falseFunction(): () => boolean;
- getById(id: HTMLElement): HTMLElement;
- getById(id: string): HTMLElement;
- getElementOffset(element): { left: number; top: number; };
- getPointer(event: Event);
- getRandomInt(min: number, max: number);
- getScript(url: string, callback);
- groupSVGElements(elements: any[], options, path?: string);
- loadImage(url, callback, context);
- makeElement(tagName: string, attributes);
- makeElementSelectable(element: HTMLElement);
- makeElementUnselectable(element: HTMLElement);
- populateWithProperties(source, destination, properties): any[];
- radiansToDegrees(radians: number): number;
- removeFromArray(array: any[], value);
- removeListener(element: HTMLElement, eventName, handler);
- request(url, options);
- requestAnimFrame(callback, element);
- setStyle(element: HTMLElement, styles);
- toArray(arrayLike): any[];
- toFixed(number, fractionDigits);
- wrapElement(element: HTMLElement, wrapper, attributes);
- rotatePoint(point: IPoint, origin: IPoint, radians: number);
- transformPoint(p: IPoint, t: any[], ignoreOffset: boolean);
- invertTransform(t: any[]);
- parseUnit(value: number|string, fontSize?: number);
- getKlass(type: string, namespace: string);
- resolveNamespace(namespace: string);
- enlivenObjects(objects: any[], callback: Function, namespace: string, reviver: Function);
- drawDashedLine(ctx: CanvasRenderingContext2D, x: number, y: number, x2: number, y2: number, da: any[]);
- createCanvasElement(canvasEl?: HTMLElement);
- createImage();
- createAccessors(klass: Object);
- clipContext(receiver: IObject, ctx: CanvasRenderingContext2D);
- isTransparent(ctx: CanvasRenderingContext2D, x: number, y: number, tolerance: number);
-
- }
+ var isLikelyNode: boolean;
+ var isTouchSupported: boolean;
+
+ /////////////////////////////////////////////////////////////
+ // farbic Functions
+ /////////////////////////////////////////////////////////////
+
+ function createCanvasForNode(width: number, height: number): ICanvas;
+
+ // Parse
+ // ----------------------------------------------------------
+ /**
+ * Creates markup containing SVG referenced elements like patterns, gradients etc.
+ * @param {fabric.Canvas} canvas instance of fabric.Canvas
+ */
+ function createSVGRefElementsMarkup(canvas: IStaticCanvas): string;
+ /**
+ * Creates markup containing SVG font faces
+ * @param {Array} objects Array of fabric objects
+ */
+ function createSVGFontFacesMarkup(objects: IObject[]): string;
+ /**
+ * Takes string corresponding to an SVG document, and parses it into a set of fabric objects
+ * @param {String} string
+ * @param {Function} callback
+ * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
+ */
+ function loadSVGFromString(string: string, callback: (results: IObject[], options: any) => void, reviver?: Function);
+ /**
+ * 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)
+ * @param {String} url
+ * @param {Function} callback
+ * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
+ */
+ function loadSVGFromURL(url: string, callback: (results: IObject[], options: any) => void, reviver?: Function);
+ /**
+ * Returns CSS rules for a given SVG document
+ * @param {SVGDocument} doc SVG document to parse
+ */
+ function getCSSRules(doc: SVGElement): any;
+
+ function parseElements(elements: any[], callback: Function, options: any, reviver?: Function);
+ /**
+ * Parses "points" attribute, returning an array of values
+ * @param {String} points points attribute string
+ */
+ function parsePointsAttribute(points: string): any[];
+ /**
+ * Parses "style" attribute, retuning an object with values
+ * @param {SVGElement} element Element to parse
+ */
+ function parseStyleAttribute(element: SVGElement): any;
+ /**
+ * Transforms an array of svg elements to corresponding fabric.* instances
+ * @param {Array} elements Array of elements to parse
+ * @param {Function} callback Being passed an array of fabric instances (transformed from SVG elements)
+ * @param {Object} [options] Options object
+ * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
+ */
+ function parseElements(elements: any[], callback: Function, options?: any, reviver?: Function): void;
+ /**
+ * Returns an object of attributes' name/value, given element and an array of attribute names;
+ * Parses parent "g" nodes recursively upwards.
+ * @param {DOMElement} element Element to parse
+ * @param {Array} attributes Array of attributes to parse
+ */
+ function parseAttributes(elemen: HTMLElement, attributes: string[], svgUid?: string): { [key: string]: string }
+ /**
+ * Parses an SVG document, returning all of the gradient declarations found in it
+ * @param {SVGDocument} doc SVG document to parse
+ */
+ function getGradientDefs(doc: SVGElement): { [key: string]: any };
+ /**
+ * Parses a short font declaration, building adding its properties to a style object
+ * @param {String} value font declaration
+ * @param {Object} oStyle definition
+ */
+ function parseFontDeclaration(value: string, oStyle: any): void;
+ /**
+ * Parses an SVG document, converts it to an array of corresponding fabric.* instances and passes them to a callback
+ * @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.
+ */
+ function parseSVGDocument(doc: SVGElement, callback: (results: IObject[], options: any) => void, reviver?: Function);
+ /**
+ * Parses "transform" attribute, returning an array of values
+ * @param {String} attributeValue String containing attribute value
+ */
+ function parseTransformAttribute(attributeValue: string): number[];
+
+ // fabric Log
+ // ---------------
+ /**
+ * Wrapper around `console.log` (when available)
+ */
+ function log(...values: any[]);
+ /**
+ * Wrapper around `console.warn` (when available)
+ */
+ function warn(...values: any[]);
+
+ ////////////////////////////////////////////////////
+ // Classes
+ ////////////////////////////////////////////////////
+ var Canvas: ICanvasStatic;
+ var StaticCanvas: IStaticCanvasStatic;
+
+ var Color: IColorStatic;
+ var Pattern: IPatternStatic;
+ var Intersection: IIntersectionStatic;
+ var Point: IPointStatic;
+
+ var Circle: ICircleStatic;
+ var Ellipse: IEllipseStatic;
+ var Group: IGroupStatic;
+ var Image: IImageStatic;
+ var Line: ILineStatic;
+ var Object: IObjectStatic;
+ var Path: IPathStatic;
+ var PathGroup: IPathGroupStatic;
+ var Polygon: IPolygonStatic;
+ var Polyline: IPolylineStatic;
+ var Rect: IRectStatic;
+ var Shadow: IShadowStatic;
+ var Text: ITextStatic;
+ var IText: IITextStatic;
+ var Triangle: ITriangleStatic;
+
+ var util: IUtil;
+
+ ///////////////////////////////////////////////////////////////////////////////
+ // Data Object Interfaces - These intrface are not specific part of fabric,
+ // They are just helpful for for defining function paramters
+ //////////////////////////////////////////////////////////////////////////////
+ interface IDataURLOptions {
+ /**
+ * The format of the output image. Either "jpeg" or "png"
+ */
+ format?: string;
+ /**
+ * Quality level (0..1). Only used for jpeg
+ */
+ quality?: number;
+ /**
+ * Multiplier to scale by
+ */
+ multiplier?: number;
+ /**
+ * Cropping left offset. Introduced in v1.2.14
+ */
+ left?: number;
+ /**
+ * Cropping top offset. Introduced in v1.2.14
+ */
+ top?: number;
+ /**
+ * Cropping width. Introduced in v1.2.14
+ */
+ width?: number;
+ /**
+ * Cropping height. Introduced in v1.2.14
+ */
+ height?: number;
+ }
+
+ interface IEvent {
+ e: Event;
+ target?: IObject;
+ }
+
+ interface IFillOptions {
+ /**
+ * options.source Pattern source
+ */
+ source: string | HTMLImageElement;
+ /**
+ * Repeat property of a pattern (one of repeat, repeat-x, repeat-y or no-repeat)
+ */
+ repeat?: string;
+ /**
+ * Pattern horizontal offset from object's left/top corner
+ */
+ offsetX?: number;
+ /**
+ * Pattern vertical offset from object's left/top corner
+ */
+ offsetY?: number;
+ }
+
+ interface IToSVGOptions {
+ /**
+ * If true xml tag is not included
+ */
+ suppressPreamble: boolean;
+ /**
+ * SVG viewbox object
+ */
+ viewBox: IViewBox;
+ /**
+ * Encoding of SVG output
+ */
+ encoding: string;
+ }
+
+ interface IViewBox {
+ /**
+ * x-cooridnate of viewbox
+ */
+ x: number;
+ /**
+ * y-coordinate of viewbox
+ */
+ y: number;
+ /**
+ * Width of viewbox
+ */
+ width: number;
+ /**
+ * Height of viewbox
+ */
+ height: number;
+ }
+
+ ///////////////////////////////////////////////////////////////////////////////
+ // Mixins Interfaces
+ //////////////////////////////////////////////////////////////////////////////
+ interface ICollection {
+ /**
+ * Adds objects to collection, then renders canvas (if `renderOnAddRemove` is not `false`)
+ * Objects should be instances of (or inherit from) fabric.Object
+ * @param {...fabric.Object} object Zero or more fabric instances
+ */
+ add(...object: IObject[]): T;
+
+ /**
+ * Inserts an object into collection at specified index, then renders canvas (if `renderOnAddRemove` is not `false`)
+ * An object should be an instance of (or inherit from) fabric.Object
+ * @param {Object} object Object to insert
+ * @param {Number} index Index to insert object at
+ * @param {Boolean} nonSplicing When `true`, no splicing (shifting) of objects occurs
+ * @return {Self} thisArg
+ * @chainable
+ */
+ insertAt(object: IObject, index: number, nonSplicing: boolean): T;
+
+ /**
+ * 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(...object: IObject[]): T;
+
+ /**
+ * Executes given function for each object in this group
+ * @param {Function} callback
+ * @param {Object} context Context (aka thisObject)
+ * @return {Self} thisArg
+ */
+ forEachObject(callback: (element: IObject, index: number, array: IObject[]) => any, context?: any): T;
+
+ /**
+ * Returns an array of children objects of this instance
+ * Type parameter introduced in 1.3.10
+ * @param {String} [type] When specified, only objects of this type are returned
+ * @return {Array}
+ */
+ getObjects(type?: string): IObject[];
+
+ /**
+ * Returns object at specified index
+ * @param {Number} index
+ * @return {Self} thisArg
+ */
+ item(index: number): T;
+
+ /**
+ * Returns true if collection contains no objects
+ * @return {Boolean} true if collection is empty
+ */
+ isEmpty(): boolean;
+
+ /**
+ * Returns a size of a collection (i.e: length of an array containing its objects)
+ * @return {Number} Collection size
+ */
+ size(): number;
+
+ /**
+ * Returns true if collection contains an object
+ * @param {Object} object Object to check against
+ * @return {Boolean} `true` if collection contains an object
+ */
+ contains(object: IObject): boolean;
+
+ /**
+ * Returns number representation of a collection complexity
+ * @return {Number} complexity
+ */
+ complexity(): number;
+ }
+
+ interface IObservable {
+ /**
+ * Observes specified event
+ * @param eventName Event name (eg. 'after:render')
+ * @param handler Function that receives a notification when an event of the specified type occurs
+ */
+ on(eventName: string, handler: (e: IEvent) => any): T;
+
+ /**
+ * Observes specified event
+ * @param eventName Object with key/value pairs (eg. {'after:render': handler, 'selection:cleared': handler})
+ */
+ on(eventName: {[key:string] : Function}): T;
+ /**
+ * Fires event with an optional options object
+ * @deprecated `fire` deprecated since 1.0.7 (use `trigger` instead)
+ * @param {String} eventName Event name to fire
+ * @param {Object} [options] Options object
+ */
+ trigger(eventName: string, options?: any): T;
+ /**
+ * 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)
+ * @param eventName Event name (eg. 'after:render') or object with key/value pairs (eg. {'after:render': handler, 'selection:cleared': handler})
+ * @param handler Function to be deleted from EventListeners
+ */
+ off(eventName: string|any, handler: (e: IEvent) => any): T;
+ }
+
+ // animation mixin
+ // ----------------------------------------------------
+ interface ICanvasAnimation {
+ FX_DURATION: number;
+ /**
+ * Centers object horizontally with animation.
+ * @param {fabric.Object} object Object to center
+ * @param {Object} [callbacks] Callbacks object with optional "onComplete" and/or "onChange" properties
+ * @param {Function} [callbacks.onComplete] Invoked on completion
+ * @param {Function} [callbacks.onChange] Invoked on every step of animation
+ */
+ fxCenterObjectH(object: IObject, callbacks?: { onComplete: Function; onChange: Function; }): T;
+
+ /**
+ * Centers object vertically with animation.
+ * @param {fabric.Object} object Object to center
+ * @param {Object} [callbacks] Callbacks object with optional "onComplete" and/or "onChange" properties
+ * @param {Function} [callbacks.onComplete] Invoked on completion
+ * @param {Function} [callbacks.onChange] Invoked on every step of animation
+ */
+ fxCenterObjectV(object: IObject, callbacks?: { onComplete: Function; onChange: Function; }): T;
+
+ /**
+ * Same as `fabric.Canvas#remove` but animated
+ * @param {fabric.Object} object Object to remove
+ * @param {Object} [callbacks] Callbacks object with optional "onComplete" and/or "onChange" properties
+ * @param {Function} [callbacks.onComplete] Invoked on completion
+ * @param {Function} [callbacks.onChange] Invoked on every step of animation
+ * @return {fabric.Canvas} thisArg
+ * @chainable
+ */
+ fxRemove(object: IObject, callbacks?: { onComplete: Function; onChange: Function; }): T;
+ }
+ interface IObjectAnimation {
+ /**
+ * Animates object's properties
+ * object.animate('left', ..., {duration: ...});
+ * @param property Property to animate
+ * @param value Value to animate property
+ * @param options The animation options
+ */
+ animate(property: string, value: number|string, options?: IAnimationOptions): IObject;
+ /**
+ * Animates object's properties
+ * object.animate({ left: ..., top: ... }, { duration: ... });
+ * @param properties Properties to animate
+ * @param value Options object
+ */
+ animate(properties: any, options?: IAnimationOptions): IObject;
+ }
+ interface IAnimationOptions {
+ /**
+ * Allows to specify starting value of animatable property (if we don't want current value to be used).
+ */
+ from?: string|number;
+ /**
+ * Defaults to 500 (ms). Can be used to change duration of an animation.
+ */
+ duration?: number;
+ /**
+ * Callback; invoked on every value change
+ */
+ onChange?: Function;
+ /**
+ * Callback; invoked when value change is completed
+ */
+ onComplete?: Function;
+
+ /**
+ * Easing function. Default: fabric.util.ease.easeInSine
+ */
+ easing?: Function;
+ /**
+ * Value to modify the property by, default: end - start
+ */
+ by?: number;
+ }
+
+ ///////////////////////////////////////////////////////////////////////////////
+ // General Fabric Interfaces
+ //////////////////////////////////////////////////////////////////////////////
+ interface IColor {
+ /**
+ * Returns source of this color (where source is an array representation; ex: [200, 200, 100, 1])
+ */
+ getSource(): number[];
+
+ /**
+ * Sets source of this color (where source is an array representation; ex: [200, 200, 100, 1])
+ */
+ setSource(source: number[]);
+
+ /**
+ * Returns color represenation in RGB format ex: rgb(0-255,0-255,0-255)
+ */
+ toRgb(): string;
+
+ /**
+ * Returns color represenation in RGBA format ex: rgba(0-255,0-255,0-255,0-1)
+ */
+ toRgba(): string;
+
+ /**
+ * Returns color represenation in HSL format ex: hsl(0-360,0%-100%,0%-100%)
+ */
+ toHsl(): string;
+
+ /**
+ * Returns color represenation in HSLA format ex: hsla(0-360,0%-100%,0%-100%,0-1)
+ */
+ toHsla(): string;
+
+ /**
+ * Returns color represenation in HEX format ex: FF5555
+ */
+ toHex(): string;
+
+ /**
+ * Gets value of alpha channel for this color
+ */
+ getAlpha(): number;
+
+ /**
+ * Sets value of alpha channel for this color
+ * @param {Number} alpha Alpha value 0-1
+ */
+ setAlpha(alpha: number);
+
+ /**
+ * Transforms color to its grayscale representation
+ */
+ toGrayscale(): IColor;
+
+ /**
+ * Transforms color to its black and white representation
+ * @param {Number} threshold
+ */
+ toBlackWhite(threshold: number): IColor;
+ /**
+ * Overlays color with another color
+ * @param {String|fabric.Color} otherColor
+ */
+ overlayWith(otherColor: string|IColor): IColor;
+ }
+ interface IColorStatic {
+ /**
+ * Color class
+ * The purpose of Color is to abstract and encapsulate common color operations;
+ * @param {String} color optional in hex or rgb(a) format
+ */
+ new (color?: string): IColor;
+
+ /**
+ * Returns new color object, when given a color in RGB format
+ * @param {String} color Color value ex: rgb(0-255,0-255,0-255)
+ */
+ fromRgb(color: string): IColor;
+ /**
+ * Returns new color object, when given a color in RGBA format
+ * @param {String} color Color value ex: rgb(0-255,0-255,0-255)
+ */
+ fromRgba(color: string): IColor;
+ /**
+ * Returns array represenatation (ex: [100, 100, 200, 1]) of a color that's in RGB or RGBA format
+ * @param {String} color Color value ex: rgb(0-255,0-255,0-255), rgb(0%-100%,0%-100%,0%-100%)
+ */
+ sourceFromRgb(color: string): number[];
+ /**
+ * Returns new color object, when given a color in HSL format
+ * @param {String} color Color value ex: hsl(0-260,0%-100%,0%-100%)
+ */
+ fromHsl(color: string): IColor;
+ /**
+ * Returns new color object, when given a color in HSLA format
+ * @param {String} color Color value ex: hsl(0-260,0%-100%,0%-100%)
+ */
+ fromHsla(color: string): IColor;
+ /**
+ * Returns array represenatation (ex: [100, 100, 200, 1]) of a color that's in HSL or HSLA format.
+ * @param {String} color Color value ex: hsl(0-360,0%-100%,0%-100%) or hsla(0-360,0%-100%,0%-100%, 0-1)
+ */
+ sourceFromHsl(color: string): number[];
+ /**
+ * Returns new color object, when given a color in HEX format
+ * @param {String} color Color value ex: FF5555
+ */
+ fromHex(color: string): IColor;
+
+ /**
+ * Returns array represenatation (ex: [100, 100, 200, 1]) of a color that's in HEX format
+ * @param {String} color ex: FF5555
+ */
+ sourceFromHex(color: string): number[];
+ /**
+ * Returns new color object, when given color in array representation (ex: [200, 100, 100, 0.5])
+ * @param {Array} source
+ */
+ fromSource(source: number[]): IColor;
+ prototype: any;
+ }
+
+ interface IGradientOptions {
+ /**
+ * @param {String} [options.type] Type of gradient 'radial' or 'linear'
+ */
+ type?: string;
+ /**
+ * x-coordinate of start point
+ */
+ x1?: number;
+ /**
+ * y-coordinate of start point
+ */
+ y1?: number;
+ /**
+ * x-coordinate of end point
+ */
+ x2?: number;
+ /**
+ * y-coordinate of end point
+ */
+ y2?: number;
+ /**
+ * Radius of start point (only for radial gradients)
+ */
+ r1?: number;
+ /**
+ * Radius of end point (only for radial gradients)
+ */
+ r2?: number;
+ /**
+ * Color stops object eg. {0:string; 1:string;
+ */
+ colorStops?: any;
+ }
+ interface IGradient extends IGradientOptions {
+ /**
+ * Adds another colorStop
+ * @param {Object} colorStop Object with offset and color
+ */
+ addColorStop(colorStop: any): IGradient;
+ /**
+ * Returns object representation of a gradient
+ */
+ toObject(): any;
+ /**
+ * Returns SVG representation of an gradient
+ * @param {Object} object Object to create a gradient for
+ * @param {Boolean} normalize Whether coords should be normalized
+ * @return {String} SVG representation of an gradient (linear/radial)
+ */
+ toSVG(object: IObject, normalize?: boolean): string;
+
+ /**
+ * Returns an instance of CanvasGradient
+ * @param {CanvasRenderingContext2D} ctx Context to render on
+ */
+ toLive(ctx: CanvasRenderingContext2D, object?: IPathGroup): CanvasGradient;
+ }
+ interface IGrandientStatic {
+ new (options?: IGradientOptions): IGradient;
+ /**
+ * Returns instance from an SVG element
+ * @param {SVGGradientElement} el SVG gradient element
+ * @param {fabric.Object} instance
+ */
+ fromElement(el: SVGGradientElement, instance: IObject): IGradient;
+ /**
+ * Returns instance from its object representation
+ * @param {Object} obj
+ * @param {Object} [options] Options object
+ */
+ fromObject(obj: any, options: any[]): IGradient;
+ }
+
+ interface IIntersection {
+ /**
+ * Appends a point to intersection
+ */
+ appendPoint(point: IPoint);
+ /**
+ * Appends points to intersection
+ */
+ appendPoints(points: IPoint[]);
+ }
+ interface IIntersectionStatic {
+ /**
+ * Intersection class
+ */
+ new (status?: string);
+ /**
+ * Checks if polygon intersects another polygon
+ */
+ intersectPolygonPolygon(points1: IPoint[], points2: IPoint[]): IIntersection;
+ /**
+ * Checks if line intersects polygon
+ */
+ intersectLinePolygon(a1: IPoint, a2: IPoint, points: IPoint[]): IIntersection;
+ /**
+ * Checks if one line intersects another
+ */
+ intersectLineLine(a1: IPoint, a2: IPoint, b1: IPoint, b2: IPoint): IIntersection;
+ /**
+ * Checks if polygon intersects rectangle
+ */
+ intersectPolygonRectangle(points: IPoint[], r1: number, r2: number): IIntersection;
+ }
+
+ interface IPatternOptions {
+ /**
+ * Repeat property of a pattern (one of repeat, repeat-x, repeat-y or no-repeat)
+ */
+ repeat: string;
+
+ /**
+ * Pattern horizontal offset from object's left/top corner
+ */
+ offsetX: number;
+
+ /**
+ * Pattern vertical offset from object's left/top corner
+ */
+ offsetY: number;
+ /**
+ * The source for the pattern
+ */
+ source: string|HTMLImageElement;
+ }
+ interface IPattern extends IPatternOptions {
+ new (options?: IPatternOptions): IPattern;
+
+ initialise(options?: IPatternOptions): IPattern;
+ /**
+ * Returns an instance of CanvasPattern
+ */
+ toLive(ctx: CanvasRenderingContext2D): IPattern;
+
+ /**
+ * Returns object representation of a pattern
+ */
+ toObject(): any;
+ /**
+ * Returns SVG representation of a pattern
+ * @param {fabric.Object} object
+ */
+ toSVG(object: IObject): string;
+ }
+ interface IPatternStatic {
+ new (options?: IPatternOptions): IPattern;
+ prototype: any;
+ }
+
+ interface IPoint {
+ x: number;
+ y: number;
+ /**
+ * Adds another point to this one and returns another one
+ * @param {fabric.Point} that
+ */
+ add(that: IPoint): IPoint;
+
+ /**
+ * Adds another point to this one
+ * @param {fabric.Point} that
+ */
+ addEquals(that: IPoint): IPoint;
+
+ /**
+ * Adds value to this point and returns a new one
+ * @param {Number} scalar
+ */
+ scalarAdd(scalar: number): IPoint;
+
+ /**
+ * Adds value to this point
+ * @param {Number} scalar
+ */
+ scalarAddEquals(scalar: number): IPoint;
+
+ /**
+ * Subtracts another point from this point and returns a new one
+ * @param {fabric.Point} that
+ */
+ subtract(that: IPoint): IPoint;
+
+ /**
+ * Subtracts another point from this point
+ * @param {fabric.Point} that
+ */
+ subtractEquals(that: IPoint): IPoint;
+
+ /**
+ * Subtracts value from this point and returns a new one
+ * @param {Number} scalar
+ */
+ scalarSubtract(scalar: number): IPoint;
+
+ /**
+ * Subtracts value from this point
+ * @param {Number} scalar
+ */
+ scalarSubtractEquals(scalar: number): IPoint;
+
+ /**
+ * Miltiplies this point by a value and returns a new one
+ * @param {Number} scalar
+ */
+ multiply(scalar: number): IPoint;
+
+ /**
+ * Miltiplies this point by a value
+ * @param {Number} scalar
+ */
+ multiplyEquals(scalar: number): IPoint;
+
+ /**
+ * Divides this point by a value and returns a new one
+ * @param {Number} scalar
+ */
+ divide(scalar: number): IPoint;
+
+ /**
+ * Divides this point by a value
+ * @param {Number} scalar
+ */
+ divideEquals(scalar: number): IPoint;
+
+ /**
+ * Returns true if this point is equal to another one
+ * @param {fabric.Point} that
+ */
+ eq(that: IPoint): IPoint;
+
+ /**
+ * Returns true if this point is less than another one
+ * @param {fabric.Point} that
+ */
+ lt(that: IPoint): IPoint;
+
+ /**
+ * Returns true if this point is less than or equal to another one
+ * @param {fabric.Point} that
+ */
+ lte(that: IPoint): IPoint;
+
+ /**
+ * Returns true if this point is greater another one
+ * @param {fabric.Point} that
+ */
+ gt(that: IPoint): IPoint;
+
+ /**
+ * Returns true if this point is greater than or equal to another one
+ * @param {fabric.Point} that
+ */
+ gte(that: IPoint): IPoint;
+
+ /**
+ * Returns new point which is the result of linear interpolation with this one and another one
+ * @param {fabric.Point} that
+ * @param {Number} t
+ */
+ lerp(that: IPoint, t: number): IPoint;
+
+ /**
+ * Returns distance from this point and another one
+ * @param {fabric.Point} that
+ */
+ distanceFrom(that: IPoint): number;
+
+ /**
+ * Returns the point between this point and another one
+ * @param {fabric.Point} that
+ */
+ midPointFrom(that: IPoint): IPoint;
+
+ /**
+ * Returns a new point which is the min of this and another one
+ * @param {fabric.Point} that
+ */
+ min(that: IPoint): IPoint;
+
+ /**
+ * Returns a new point which is the max of this and another one
+ * @param {fabric.Point} that
+ */
+ max(that: IPoint): IPoint;
+
+ /**
+ * Returns string representation of this point
+ */
+ toString(): string;
+
+ /**
+ * Sets x/y of this point
+ * @param {Number} x
+ * @param {Number} y
+ */
+ setXY(x:number, y: number): IPoint;
+
+ /**
+ * Sets x/y of this point from another point
+ * @param {fabric.Point} that
+ */
+ setFromPoint(that: IPoint): IPoint;
+
+ /**
+ * Swaps x/y of this point and another point
+ * @param {fabric.Point} that
+ */
+ swap(that: IPoint): IPoint;
+ }
+ interface IPointStatic {
+ new (x: number, y: number): IPoint;
+ prototype: any;
+ }
+
+ interface IShadowOptions {
+ /**
+ * Whether the shadow should affect stroke operations
+ */
+ affectStrike: boolean;
+ /**
+ * Shadow blur
+ */
+ blur: number;
+ /**
+ * Shadow color
+ */
+ color: string;
+ /**
+ * Indicates whether toObject should include default values
+ */
+ includeDefaultValues: boolean;
+ /**
+ * Shadow horizontal offset
+ */
+ offsetX: number;
+ /**
+ * Shadow vertical offset
+ */
+ offsetY: number;
+ }
+ interface IShadow extends IShadowOptions {
+ initialize(options?: IShadowOptions|string): IShadow;
+ /**
+ * Returns object representation of a shadow
+ */
+ toObject(): IObject;
+ /**
+ * Returns a string representation of an instance, CSS3 text-shadow declaration
+ */
+ toString(): string;
+ /**
+ * Returns SVG representation of a shadow
+ * @param {fabric.Object} object
+ */
+ toSVG(object: IObject): string;
+
+ /**
+ * Regex matching shadow offsetX, offsetY and blur, Static
+ */
+ reOffsetsAndBlur: RegExp
+ }
+ interface IShadowStatic {
+ new (options?: IShadowOptions): IShadow;
+ reOffsetsAndBlur: RegExp;
+ }
+
+ ///////////////////////////////////////////////////////////////////////////////
+ // Canvas Interfaces
+ //////////////////////////////////////////////////////////////////////////////
+ interface ICanvasDimensions {
+ /**
+ * Width of canvas element
+ */
+ width: number;
+ /**
+ * Height of canvas element
+ */
+ height: number;
+ }
+ interface ICanvasDimensionsOptions {
+ /**
+ * Set the given dimensions only as canvas backstore dimensions
+ */
+ backstoreOnly?: boolean;
+ /**
+ * Set the given dimensions only as css dimensions
+ */
+ cssOnly?: boolean;
+ }
+
+ interface IStaticCanvasOptions {
+ /**
+ * Indicates whether the browser can be scrolled when using a touchscreen and dragging on the canvas
+ */
+ allowTouchScrolling?: boolean;
+ /**
+ * Indicates whether this canvas will use image smoothing, this is on by default in browsers
+ */
+ imageSmoothingEnabled?: boolean;
+
+ /**
+ * Indicates whether objects should remain in current stack position when selected.
+ * When false objects are brought to top and rendered as part of the selection group
+ */
+ preserveObjectStacking?: boolean;
+
+ /**
+ * The transformation (in the format of Canvas transform) which focuses the viewport
+ */
+ viewportTransform?: number[];
+
+ freeDrawingColor?: string;
+ freeDrawingLineWidth?: number;
+
+ /**
+ * Background color of canvas instance.
+ * Should be set via setBackgroundColor
+ */
+ backgroundColor?: string|IPattern;
+ /**
+ * Background image of canvas instance.
+ * Should be set via setBackgroundImage
+ * Backwards incompatibility note: The "backgroundImageOpacity" and "backgroundImageStretch" properties are deprecated since 1.3.9.
+ */
+ backgroundImage?: IImage | string;
+ backgroundImageOpacity?: number;
+ backgroundImageStretch?: number;
+ /**
+ * Function that determines clipping of entire canvas area
+ * Being passed context as first argument. See clipping canvas area
+ */
+ clipTo?: (context: CanvasRenderingContext2D) => void;
+
+ /**
+ * Indicates whether object controls (borders/controls) are rendered above overlay image
+ */
+ controlsAboveOverlay?: boolean;
+
+ /**
+ * Indicates whether toObject/toDatalessObject should include default values
+ */
+ includeDefaultValues?: boolean;
+ /**
+ * Overlay color of canvas instance.
+ * Should be set via setOverlayColor
+ */
+ overlayColor?: string|IPattern;
+ /**
+ * Overlay image of canvas instance.
+ * Should be set via setOverlayImage
+ * Backwards incompatibility note: The "overlayImageLeft" and "overlayImageTop" properties are deprecated since 1.3.9.
+ */
+ overlayImage?: IImage;
+ overlayImageLeft?: number;
+ overlayImageTop?: number;
+ /**
+ * Indicates whether add, insertAt and remove should also re-render canvas.
+ * Disabling this option could give a great performance boost when adding/removing a lot of objects to/from canvas at once
+ * (followed by a manual rendering after addition/deletion)
+ */
+ renderOnAddRemove?: boolean;
+ /**
+ * Indicates whether objects' state should be saved
+ */
+ stateful?: boolean;
+ }
+ interface IStaticCanvas extends IObservable, IStaticCanvasOptions, ICollection, ICanvasAnimation {
+ /**
+ * Calculates canvas element offset relative to the document
+ * This method is also attached as "resize" event handler of window
+ */
+ calcOffset(): IStaticCanvas;
+
+ /**
+ * 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}.
+ */
+ setOverlayImage(image: IImage|string, callback: Function, options?: IObjectOptions): IStaticCanvas;
+
+ /**
+ * 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}.
+ */
+ setBackgroundImage(image: IImage|string, callback: Function, options?: IObjectOptions): IStaticCanvas;
+
+ /**
+ * Sets {@link fabric.StaticCanvas#overlayColor|background color} for this canvas
+ * @param {(String|fabric.Pattern)} overlayColor Color or pattern to set background color to
+ * @param {Function} callback Callback to invoke when background color is set
+ */
+ setOverlayColor(overlayColor: string|IPattern, callback: Function): IStaticCanvas;
+
+ /**
+ * 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
+ */
+ setBackgroundColor(backgroundColor: string|IPattern, callback: Function): IStaticCanvas;
+
+ /**
+ * Returns canvas width (in px)
+ */
+ getWidth(): number;
+
+ /**
+ * Returns canvas height (in px)
+ */
+ getHeight(): number;
+
+ /**
+ * Sets width of this canvas instance
+ * @param {Number|String} value Value to set width to
+ * @param {Object} [options] Options object
+ */
+ setWidth(value: number|string, options?: ICanvasDimensionsOptions): IStaticCanvas
+
+ /**
+ * Sets height of this canvas instance
+ * @param {Number|String} value Value to set height to
+ * @param {Object} [options] Options object
+ */
+ setHeight(value: number|string, options?: ICanvasDimensionsOptions): IStaticCanvas;
+
+ /**
+ * 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 {Object} [options] Options object
+ */
+ setDimensions(dimensions: ICanvasDimensions, options?: ICanvasDimensionsOptions): IStaticCanvas;
+
+ /**
+ * Returns canvas zoom level
+ */
+ getZoom(): number;
+
+ /**
+ * Sets viewport transform of this canvas instance
+ * @param {Array} vpt the transform in the form of context.transform
+ */
+ setViewportTransform(vpt: number[]): IStaticCanvas;
+
+ /**
+ * 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
+ */
+ zoomToPoint(point: IPoint, value: number): IStaticCanvas;
+
+ /**
+ * Sets zoom level of this canvas instance
+ * @param {Number} value to set zoom to, less than 1 zooms out
+ */
+ setZoom(value: number): IStaticCanvas;
+
+ /**
+ * Pan viewport so as to place point at top left corner of canvas
+ * @param {fabric.Point} point to move to
+ */
+ absolutePan(point: IPoint): IStaticCanvas;
+
+ /**
+ * Pans viewpoint relatively
+ * @param {fabric.Point} point (position vector) to move by
+ */
+ relativePan(point: IPoint): IStaticCanvas;
+
+ /**
+ * Returns