diff --git a/fabricjs/fabricjs-tests.ts b/fabricjs/fabricjs-tests.ts index e59212d805..c3dfd8d6da 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 048c915dfe..503b8c7dbf 100644 --- a/fabricjs/fabricjs.d.ts +++ b/fabricjs/fabricjs.d.ts @@ -1,8 +1,12 @@ // Type definitions for FabricJS v1.5.0 // Project: http://fabricjs.com/ -// Definitions by: Oliver Klemencic , edited by Joseph Livecchi +// 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; @@ -32,61 +36,62 @@ declare module fabric { */ 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) => void, reviver?: (el, obj) => void); + * 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, callback: (results: IObject[], options) => void, reviver?: (el, obj) => void); + * 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 - */ + * 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, options, reviver); + function parseElements(elements: any[], callback: Function, options: any, reviver?: Function); /** - * Parses "points" attribute, returning an array of values - * @param {String} points points attribute string - */ + * 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 - */ + * 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. - */ + * 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 - */ + * 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 - */ + * 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 - */ + * 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 @@ -94,7 +99,7 @@ declare module fabric { * @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, options) => void, reviver?: (el, obj) => void); + 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 @@ -104,14 +109,13 @@ declare module fabric { // fabric Log // --------------- /** - * Wrapper around `console.log` (when available) - */ - function log(values); + * Wrapper around `console.log` (when available) + */ + function log(...values: any[]); /** - * Wrapper around `console.warn` (when available) - */ - function warn(values); - + * Wrapper around `console.warn` (when available) + */ + function warn(...values: any[]); //////////////////////////////////////////////////// // Classes @@ -122,25 +126,25 @@ declare module fabric { var Color: IColorStatic; var Pattern: IPatternStatic; var Intersection: IIntersectionStatic; - var Point: IPointStatic + var Point: IPointStatic; var Circle: ICircleStatic; var Ellipse: IEllipseStatic; var Group: IGroupStatic; - var Image: IImageStatic + var Image: IImageStatic; var Line: ILineStatic; var Object: IObjectStatic; var Path: IPathStatic; - var PathGroup: IPathGroupStatic - var Polygon: IPolygonStatic + 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 Triangle: ITriangleStatic; - var util: Util; + var util: IUtil; /////////////////////////////////////////////////////////////////////////////// // Data Object Interfaces - These intrface are not specific part of fabric, @@ -148,32 +152,32 @@ declare module fabric { ////////////////////////////////////////////////////////////////////////////// interface IDataURLOptions { /** - * The format of the output image. Either "jpeg" or "png" - */ + * The format of the output image. Either "jpeg" or "png" + */ format?: string; /** - * Quality level (0..1). Only used for jpeg - */ + * Quality level (0..1). Only used for jpeg + */ quality?: number; /** - * Multiplier to scale by - */ + * Multiplier to scale by + */ multiplier?: number; /** - * Cropping left offset. Introduced in v1.2.14 - */ + * Cropping left offset. Introduced in v1.2.14 + */ left?: number; /** - * Cropping top offset. Introduced in v1.2.14 - */ + * Cropping top offset. Introduced in v1.2.14 + */ top?: number; /** - * Cropping width. Introduced in v1.2.14 - */ + * Cropping width. Introduced in v1.2.14 + */ width?: number; /** - * Cropping height. Introduced in v1.2.14 - */ + * Cropping height. Introduced in v1.2.14 + */ height?: number; } @@ -184,169 +188,164 @@ declare module fabric { interface IFillOptions { /** - * options.source Pattern source - */ - source: string|HTMLImageElement; + * options.source Pattern source + */ + source: string | HTMLImageElement; /** - * Repeat property of a pattern (one of repeat, repeat-x, repeat-y or no-repeat) - */ + * 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 - */ + * Pattern horizontal offset from object's left/top corner + */ offsetX?: number; /** - * Pattern vertical offset from object's left/top corner - */ + * Pattern vertical offset from object's left/top corner + */ offsetY?: number; } - interface IToSVGOptions { /** - * If true xml tag is not included - */ + * If true xml tag is not included + */ suppressPreamble: boolean; /** - * SVG viewbox object - */ + * SVG viewbox object + */ viewBox: IViewBox; /** - * Encoding of SVG output - */ + * Encoding of SVG output + */ encoding: string; } interface IViewBox { /** - * x-cooridnate of viewbox - */ + * x-cooridnate of viewbox + */ x: number; /** - * y-coordinate of viewbox - */ + * y-coordinate of viewbox + */ y: number; /** - * Width of viewbox - */ + * Width of viewbox + */ width: number; - /**Height of viewbox */ + /** + * Height of viewbox + */ height: number; } - - interface IFilter { - new (): IFilter; - new (options: any): IFilter; - } - - interface IEventList { - [index: string]: (e: Event) => void; - } - /////////////////////////////////////////////////////////////////////////////// // 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 - */ + * 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 - */ + * 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 - */ + * 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 - */ + * 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} - */ + * 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 - */ + * 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 - */ + * 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 - */ + * 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 - */ + * 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 - */ + * Returns number representation of a collection complexity + * @return {Number} complexity + */ complexity(): number; } interface IObservable { /** * Observes specified event - * @deprecated `observe` deprecated since 0.8.34 (use `on` instead) - * @param {String|Object} eventName Event name (eg. 'after:render') or object with key/value pairs (eg. {'after:render': handler, 'selection:cleared': handler}) - * @param {Function} handler Function that receives a notification when an event of the specified type occurs + * @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|any, handler: (e: IEvent) => any): T; + on(eventName: string, handler: (e: IEvent) => any): 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 - */ + * 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 {String|Object} eventName Event name (eg. 'after:render') or object with key/value pairs (eg. {'after:render': handler, 'selection:cleared': handler}) - * @param {Function} handler Function to be deleted from EventListeners + * @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) => any): T; + off(eventName: string|any, handler: (e: IEvent) => any): T; } // animation mixin @@ -384,204 +383,204 @@ declare module fabric { } 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', ..., {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 - */ + * 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). - */ + * 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. - */ + * Defaults to 500 (ms). Can be used to change duration of an animation. + */ duration?: number; /** - * Callback; invoked on every value change - */ + * Callback; invoked on every value change + */ onChange?: Function; /** - * Callback; invoked when value change is completed - */ - onComplete?: Function + * Callback; invoked when value change is completed + */ + onComplete?: Function; + /** - * Easing function. Default: fabric.util.ease.easeInSine - */ + * 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]) - */ + * 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]) - */ + * 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) - */ + * 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) - */ + * 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%) - */ + * 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) - */ + * 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 - */ + * Returns color represenation in HEX format ex: FF5555 + */ toHex(): string; /** - * Gets value of alpha channel for this color - */ + * 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 - */ + * Sets value of alpha channel for this color + * @param {Number} alpha Alpha value 0-1 + */ setAlpha(alpha: number); /** - * Transforms color to its grayscale representation - */ + * Transforms color to its grayscale representation + */ toGrayscale(): IColor; /** - * Transforms color to its black and white representation - * @param {Number} threshold - */ + * 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 - */ + * 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 - */ + * 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): 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): 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%) - */ + * 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 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 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) - */ + * 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 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 - */ + * 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 - */ + * 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' - */ + * @param {String} [options.type] Type of gradient 'radial' or 'linear' + */ type?: string; /** - * x-coordinate of start point - */ + * x-coordinate of start point + */ x1?: number; /** - * y-coordinate of start point - */ + * y-coordinate of start point + */ y1?: number; /** - * x-coordinate of end point - */ + * x-coordinate of end point + */ x2?: number; /** - * y-coordinate of end point - */ + * y-coordinate of end point + */ y2?: number; /** - * Radius of start point (only for radial gradients) - */ + * Radius of start point (only for radial gradients) + */ r1?: number; /** - * Radius of end point (only for radial gradients) - */ + * Radius of end point (only for radial gradients) + */ r2?: number; /** - * Color stops object eg. {0:string; 1:string; - */ + * Color stops object eg. {0:string; 1:string; + */ colorStops?: any; } interface IGradient extends IGradientOptions { @@ -626,12 +625,12 @@ declare module fabric { interface IIntersection { /** - * Appends a point to intersection - */ + * Appends a point to intersection + */ appendPoint(point: IPoint); /** - * Appends points to intersection - */ + * Appends points to intersection + */ appendPoints(points: IPoint[]); } interface IIntersectionStatic { @@ -640,41 +639,41 @@ declare module fabric { */ new (status?: string); /** - * Checks if polygon intersects another polygon - */ + * 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 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 one line intersects another + */ + intersectLineLine(a1: IPoint, a2: IPoint, b1: IPoint, b2: IPoint): IIntersection; /** - * Checks if polygon intersects rectangle - */ + * 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 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 - */ + * Pattern horizontal offset from object's left/top corner + */ offsetX: number; /** - * Pattern vertical offset from object's left/top corner - */ + * Pattern vertical offset from object's left/top corner + */ offsetY: number; /** - * The source for the pattern - */ + * The source for the pattern + */ source: string|HTMLImageElement; } interface IPattern extends IPatternOptions { @@ -682,18 +681,18 @@ declare module fabric { initialise(options?: IPatternOptions): IPattern; /** - * Returns an instance of CanvasPattern - */ + * Returns an instance of CanvasPattern + */ toLive(ctx: CanvasRenderingContext2D): IPattern; /** - * Returns object representation of a pattern - */ + * Returns object representation of a pattern + */ toObject(): any; /** - * Returns SVG representation of a pattern - * @param {fabric.Object} object - */ + * Returns SVG representation of a pattern + * @param {fabric.Object} object + */ toSVG(object: IObject): string; } interface IPatternStatic { @@ -705,239 +704,216 @@ declare module fabric { x: number; y: number; /** - * Adds another point to this one and returns another one - * @param {fabric.Point} that - * @return {fabric.Point} new Point instance with added values - */ + * 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 - * @return {fabric.Point} thisArg - */ + * 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 - * @return {fabric.Point} new Point with added value - */ + * 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 - * @return {fabric.Point} thisArg - */ + * 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 - * @return {fabric.Point} new Point object with subtracted values - */ - subtract(that: IPoint): 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 - * @return {fabric.Point} thisArg - */ - subtractEquals(that): 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 - * @return {fabric.Point} - */ + * 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 - * @return {fabric.Point} thisArg - */ + * 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 - * @return {fabric.Point} - */ + * 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 - * @return {fabric.Point} thisArg - */ - multiplyEquals(scalar): 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 - * @return {fabric.Point} - */ - divide(scalar): 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 - * @return {fabric.Point} thisArg - */ + * 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 - * @return {Boolean} - */ + * 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 - * @return {Boolean} - */ + * 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 - * @return {Boolean} - */ + * 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 - * @return {Boolean} - */ + * 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 - * @return {Boolean} - */ + * 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 - * @return {fabric.Point} - */ - lerp(that, t: number): 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 - * @return {Number} - */ + * 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 - * @return {fabric.Point} - */ + * 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 - * @return {fabric.Point} - */ + * 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 - * @return {fabric.Point} - */ + * 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 - * @return {String} - */ + * Returns string representation of this point + */ toString(): string; /** - * Sets x/y of this point - * @param {Number} x - * @param {Number} y - */ - setXY(x, y: IPoint): IPoint; + * 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 - */ + * 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 - */ + * Swaps x/y of this point and another point + * @param {fabric.Point} that + */ swap(that: IPoint): IPoint; } interface IPointStatic { - new (x, y): IPoint; + new (x: number, y: number): IPoint; prototype: any; } interface IShadowOptions { /** - * Whether the shadow should affect stroke operations - */ + * Whether the shadow should affect stroke operations + */ affectStrike: boolean; /** - * Shadow blur - */ + * Shadow blur + */ blur: number; /** - * Shadow color - */ + * Shadow color + */ color: string; /** - * Indicates whether toObject should include default values - */ + * Indicates whether toObject should include default values + */ includeDefaultValues: boolean; /** - * Shadow horizontal offset - */ + * Shadow horizontal offset + */ offsetX: number; /** - * Shadow vertical offset - */ + * Shadow vertical offset + */ offsetY: number; } interface IShadow extends IShadowOptions { initialize(options?: IShadowOptions|string): IShadow; /** - * Returns object representation of a shadow - */ + * Returns object representation of a shadow + */ toObject(): IObject; /** - * Returns a string representation of an instance, CSS3 text-shadow declaration - */ + * Returns a string representation of an instance, CSS3 text-shadow declaration + */ toString(): string; /** - * Returns SVG representation of a shadow - * @param {fabric.Object} object - */ + * Returns SVG representation of a shadow + * @param {fabric.Object} object + */ toSVG(object: IObject): string; /** - * Regex matching shadow offsetX, offsetY and blur, Static - */ + * Regex matching shadow offsetX, offsetY and blur, Static + */ reOffsetsAndBlur: RegExp } interface IShadowStatic { - new (options?: IShadowOptions): IShadow + new (options?: IShadowOptions): IShadow; reOffsetsAndBlur: RegExp; } @@ -946,381 +922,421 @@ declare module fabric { ////////////////////////////////////////////////////////////////////////////// interface ICanvasDimensions { /** - * Width of canvas element - */ + * Width of canvas element + */ width: number; /** - * Height of canvas element - */ + * Height of canvas element + */ height: number; } interface ICanvasDimensionsOptions { /** - * Set the given dimensions only as canvas backstore dimensions - */ + * Set the given dimensions only as canvas backstore dimensions + */ backstoreOnly?: boolean; /** - * Set the given dimensions only as css dimensions - */ + * 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 - */ + * 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 - */ + * 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 - */ + * 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 - */ + * 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 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; + * 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 - */ + * 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 - */ + * Indicates whether object controls (borders/controls) are rendered above overlay image + */ controlsAboveOverlay?: boolean; /** - * Indicates whether toObject/toDatalessObject should include default values - */ + * Indicates whether toObject/toDatalessObject should include default values + */ includeDefaultValues?: boolean; /** - * Overlay color of canvas instance. - * Should be set via setOverlayColor - */ - overlayColor?: string | IPattern; + * 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. - */ + * 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) - */ + * 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 - */ + * 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 - */ + * 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#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}. - */ + * 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 - */ + * 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 - */ + * 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) - */ + * Returns canvas width (in px) + */ getWidth(): number; /** - * Returns canvas height (in px) - */ + * 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 - */ + * 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 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 - */ + * 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 - */ + * Returns canvas zoom level + */ getZoom(): number; /** - * Sets viewport transform of this canvas instance - * @param {Array} vpt the transform in the form of context.transform - */ + * 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 - */ + * 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 - */ + * 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 - */ + * 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 - */ + * Pans viewpoint relatively + * @param {fabric.Point} point (position vector) to move by + */ relativePan(point: IPoint): IStaticCanvas; /** - * Returns element corresponding to this instance - */ + * Returns element corresponding to this instance + */ getElement(): HTMLCanvasElement; /** - * Returns currently selected object, if any - */ + * Returns currently selected object, if any + */ getActiveObject(): IObject; /** - * Returns currently selected group of object, if any - */ + * Returns currently selected group of object, if any + */ getActiveGroup(): IGroup; /** - * Clears specified context of canvas element - * @param {CanvasRenderingContext2D} ctx Context to clear - * @chainable - */ + * Clears specified context of canvas element + * @param {CanvasRenderingContext2D} ctx Context to clear + * @chainable + */ clearContext(ctx: CanvasRenderingContext2D): IStaticCanvas; /** - * Returns context of canvas where objects are drawn - */ + * Returns context of canvas where objects are drawn + */ getContext(): CanvasRenderingContext2D; /** - * Clears all contexts (background, main, top) of an instance - */ + * Clears all contexts (background, main, top) of an instance + */ clear(): IStaticCanvas; /** - * Renders both the top canvas and the secondary container canvas. - * @param {Boolean} [allOnTop] Whether we want to force all images to be rendered on the top canvas - * @chainable - */ + * Renders both the top canvas and the secondary container canvas. + * @param {Boolean} [allOnTop] Whether we want to force all images to be rendered on the top canvas + * @chainable + */ renderAll(allOnTop?: boolean): IStaticCanvas; /** - * Method to render only the top canvas. - * Also used to render the group selection box. - * @chainable - */ + * Method to render only the top canvas. + * Also used to render the group selection box. + * @chainable + */ renderTop(): IStaticCanvas; /** - * Returns coordinates of a center of canvas. - * Returned value is an object with top and left properties - */ - getCenter(): { top: number; left: number; } - + * Returns coordinates of a center of canvas. + * Returned value is an object with top and left properties + */ + getCenter(): { top: number; left: number; }; /** - * Centers object horizontally. - * You might need to call `setCoords` on an object after centering, to update controls area. - * @param {fabric.Object} object Object to center horizontally - */ + * Centers object horizontally. + * You might need to call `setCoords` on an object after centering, to update controls area. + * @param {fabric.Object} object Object to center horizontally + */ centerObjectH(object: IObject): IStaticCanvas; /** - * Centers object vertically. - * You might need to call `setCoords` on an object after centering, to update controls area. - * @param {fabric.Object} object Object to center vertically - */ + * Centers object vertically. + * You might need to call `setCoords` on an object after centering, to update controls area. + * @param {fabric.Object} object Object to center vertically + */ centerObjectV(object: IObject): IStaticCanvas; /** - * Centers object vertically and horizontally. - * You might need to call `setCoords` on an object after centering, to update controls area. - * @param {fabric.Object} object Object to center vertically and horizontally - */ + * Centers object vertically and horizontally. + * You might need to call `setCoords` on an object after centering, to update controls area. + * @param {fabric.Object} object Object to center vertically and horizontally + */ centerObject(object: IObject): IStaticCanvas; /** - * Returs dataless JSON representation of canvas - * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output - */ + * Returs dataless JSON representation of canvas + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + */ toDatalessJSON(propertiesToInclude?: any[]): string; /** - * Returns object representation of canvas - * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output - */ - toObject(propertiesToInclude?: any[]): any; + * Returns object representation of canvas + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + */ + toObject(propertiesToInclude?: any[]): any; /** - * Returns dataless object representation of canvas - * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output - */ + * Returns dataless object representation of canvas + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + */ toDatalessObject(propertiesToInclude?: any[]): any; /** - * When true, getSvgTransform() will apply the StaticCanvas.viewportTransform to the SVG transformation. When true, - * a zoomed canvas will then produce zoomed SVG output. - */ + * When true, getSvgTransform() will apply the StaticCanvas.viewportTransform to the SVG transformation. When true, + * a zoomed canvas will then produce zoomed SVG output. + */ svgViewportTransformation: boolean; /** - * Returns SVG representation of canvas - * @param {Object} [options] Options object for SVG output - * @param {Function} [reviver] Method for further parsing of svg elements, called after each fabric object converted into svg representation. - */ + * Returns SVG representation of canvas + * @param {Object} [options] Options object for SVG output + * @param {Function} [reviver] Method for further parsing of svg elements, called after each fabric object converted into svg representation. + */ toSVG(options: IToSVGOptions, reviver?: Function): string; /** - * Moves an object to the bottom of the stack of drawn objects - * @param {fabric.Object} object Object to send to back - * @chainable - */ + * Moves an object to the bottom of the stack of drawn objects + * @param {fabric.Object} object Object to send to back + * @chainable + */ sendToBack(object: IObject): IStaticCanvas; /** - * Moves an object to the top of the stack of drawn objects - * @param {fabric.Object} object Object to send - * @chainable - */ + * Moves an object to the top of the stack of drawn objects + * @param {fabric.Object} object Object to send + * @chainable + */ bringToFront(object: IObject): IStaticCanvas; /** - * Moves an object down in stack of drawn objects - * @param {fabric.Object} object Object to send - * @param {Boolean} [intersecting] If `true`, send object behind next lower intersecting object - * @chainable - */ + * Moves an object down in stack of drawn objects + * @param {fabric.Object} object Object to send + * @param {Boolean} [intersecting] If `true`, send object behind next lower intersecting object + * @chainable + */ sendBackwards(object: IObject): IStaticCanvas; /** - * Moves an object up in stack of drawn objects - * @param {fabric.Object} object Object to send - * @param {Boolean} [intersecting] If `true`, send object in front of next upper intersecting object - * @chainable - */ + * Moves an object up in stack of drawn objects + * @param {fabric.Object} object Object to send + * @param {Boolean} [intersecting] If `true`, send object in front of next upper intersecting object + * @chainable + */ bringForward(object: IObject): IStaticCanvas; /** - * Moves an object to specified level in stack of drawn objects - * @param {fabric.Object} object Object to send - * @param {Number} index Position to move to - * @chainable - */ + * Moves an object to specified level in stack of drawn objects + * @param {fabric.Object} object Object to send + * @param {Number} index Position to move to + * @chainable + */ moveTo(object: IObject, index: number): IStaticCanvas; /** - * Clears a canvas element and removes all event listeners - */ + * Clears a canvas element and removes all event listeners + */ dispose(): IStaticCanvas; /** - * Returns a string representation of an instance - */ + * Returns a string representation of an instance + */ toString(): string; /** - * Provides a way to check support of some of the canvas methods - * (either those of HTMLCanvasElement itself, or rendering context) - * - * @param {String} methodName Method to check support for; - * Could be one of "getImageData", "toDataURL", "toDataURLWithQuality" or "setLineDash" - * @return {Boolean | null} `true` if method is supported (or at least exists), - * `null` if canvas element or context can not be initialized - */ - supports(methodName: string): boolean; - EMPTY_JSON: string; + * Exports canvas element to a dataurl image. Note that when multiplier is used, cropping is scaled appropriately + * @param {Object} [options] Options object + */ + toDataURL(options?: IDataURLOptions): string; - // methods + /** + * Provides a way to check support of some of the canvas methods + * (either those of HTMLCanvasElement itself, or rendering context) + * @param {String} methodName Method to check support for; Could be one of "getImageData", "toDataURL", "toDataURLWithQuality" or "setLineDash" + * @return {Boolean | null} `true` if method is supported (or at least exists), null` if canvas element or context can not be initialized + */ + supports(methodName: string): boolean; + + /** + * Populates canvas with data from the specified JSON. + * JSON format must conform to the one of toJSON formats + * @param {String|Object} json JSON string or object + * @param {Function} callback Callback, invoked when json is parsed + * and corresponding objects (e.g: {@link fabric.Image}) + * are initialized + * @param {Function} [reviver] Method for further parsing of JSON elements, called after each fabric object created. + */ + loadFromJSON(json: string|any, callback: Function, reviver?: Function): ICanvas; + /** + * Clones canvas instance + * @param {Object} [callback] Receives cloned instance as a first argument + * @param {Array} [properties] Array of properties to include in the cloned canvas and children + */ + clone(callback: (canvas: IStaticCanvas) => any, properties?: any[]): void; + + /** + * Clones canvas instance without cloning existing data. + * This essentially copies canvas dimensions, clipping properties, etc. + * but leaves data empty (so that you can populate it with your own) + * @param {Object} [callback] Receives cloned instance as a first argument + */ + cloneWithoutData(callback: (canvas: IStaticCanvas) => any): void; + + /** + * Callback; invoked right before object is about to be scaled/rotated + */ onBeforeScaleRotate(target: IObject); - toGrayscale(propertiesToInclude: any[]): string; + + // Functions from object straighten mixin + // -------------------------------------------------------------------------------------------------------------------------------- + + /** + * Straightens object, then rerenders canvas + * @param {fabric.Object} object Object to straighten + */ + straightenObject(object: IObject): IStaticCanvas + + /** + * Same as straightenObject, but animated + * @param {fabric.Object} object Object to straighten + */ + fxStraightenObject(object: IObject): IStaticCanvas } interface IStaticCanvasStatic { /** - * Constructor - * @param {HTMLElement|String} element element to initialize instance on - * @param {Object} [options] Options object - */ - new (element: HTMLCanvasElement | string, options?: ICanvasOptions): IStaticCanvas; + * Constructor + * @param {HTMLElement|String} element element to initialize instance on + * @param {Object} [options] Options object + */ + new (element: HTMLCanvasElement|string, options?: ICanvasOptions): IStaticCanvas; EMPTY_JSON: string; /** @@ -1339,219 +1355,212 @@ declare module fabric { interface ICanvasOptions extends IStaticCanvasOptions { /** - * When true, objects can be transformed by one side (unproportionally) - */ + * When true, objects can be transformed by one side (unproportionally) + */ uniScaleTransform?: boolean; /** - * When true, objects use center point as the origin of scale transformation. - * Backwards incompatibility note: This property replaces "centerTransform" (Boolean). - */ + * When true, objects use center point as the origin of scale transformation. + * Backwards incompatibility note: This property replaces "centerTransform" (Boolean). + */ centeredScaling?: boolean; /** - * When true, objects use center point as the origin of rotate transformation. - * Backwards incompatibility note: This property replaces "centerTransform" (Boolean). - */ + * When true, objects use center point as the origin of rotate transformation. + * Backwards incompatibility note: This property replaces "centerTransform" (Boolean). + */ centeredRotation?: boolean; /** - * Indicates that canvas is interactive. This property should not be changed. - */ + * Indicates that canvas is interactive. This property should not be changed. + */ interactive?: boolean; /** - * Indicates whether group selection should be enabled - */ + * Indicates whether group selection should be enabled + */ selection?: boolean; /** - * Color of selection - */ + * Color of selection + */ selectionColor?: string; /** - * Default dash array pattern - * If not empty the selection border is dashed - */ + * Default dash array pattern + * If not empty the selection border is dashed + */ selectionDashArray?: any[]; /** - * Color of the border of selection (usually slightly darker than color of selection itself) - */ + * Color of the border of selection (usually slightly darker than color of selection itself) + */ selectionBorderColor?: string; /** - * Width of a line used in object/group selection - */ + * Width of a line used in object/group selection + */ selectionLineWidth?: number; /** - * Default cursor value used when hovering over an object on canvas - */ + * Default cursor value used when hovering over an object on canvas + */ hoverCursor?: string; /** - * Default cursor value used when moving an object on canvas - */ + * Default cursor value used when moving an object on canvas + */ moveCursor?: string; /** - * Default cursor value used for the entire canvas - */ + * Default cursor value used for the entire canvas + */ defaultCursor?: string; /** - * Cursor value used during free drawing - */ + * Cursor value used during free drawing + */ freeDrawingCursor?: string; /** - * Cursor value used for rotation point - */ + * Cursor value used for rotation point + */ rotationCursor?: string; /** - * Default element class that's given to wrapper (div) element of canvas - */ + * Default element class that's given to wrapper (div) element of canvas + */ containerClass?: string; /** - * When true, object detection happens on per-pixel basis rather than on per-bounding-box - */ + * When true, object detection happens on per-pixel basis rather than on per-bounding-box + */ perPixelTargetFind?: boolean; /** - * Number of pixels around target pixel to tolerate (consider active) during object detection - */ + * Number of pixels around target pixel to tolerate (consider active) during object detection + */ targetFindTolerance?: number; /** - * When true, target detection is skipped when hovering over canvas. This can be used to improve performance. - */ + * When true, target detection is skipped when hovering over canvas. This can be used to improve performance. + */ skipTargetFind?: boolean; /** - * When true, mouse events on canvas (mousedown/mousemove/mouseup) result in free drawing. - * After mousedown, mousemove creates a shape, - * and then mouseup finalizes it and adds an instance of `fabric.Path` onto canvas. - */ + * When true, mouse events on canvas (mousedown/mousemove/mouseup) result in free drawing. + * After mousedown, mousemove creates a shape, + * and then mouseup finalizes it and adds an instance of `fabric.Path` onto canvas. + */ isDrawingMode?: boolean; } interface ICanvas extends IStaticCanvas, ICanvasOptions { - // constructors - new (element: HTMLCanvasElement|string, options: ICanvasOptions): ICanvas; - _objects: IObject[]; - // fields - freeDrawingColor: string; - freeDrawingLineWidth: number; - /** - * Checks if point is contained within an area of given object - * @param {Event} e Event object - * @param {fabric.Object} target Object to test against - */ + * Checks if point is contained within an area of given object + * @param {Event} e Event object + * @param {fabric.Object} target Object to test against + */ containsPoint(e: Event, target: IObject): boolean; /** - * Deactivates all objects on canvas, removing any active group or object - * @return {fabric.Canvas} thisArg - */ + * Deactivates all objects on canvas, removing any active group or object + * @return {fabric.Canvas} thisArg + */ deactivateAll(): ICanvas; /** - * Deactivates all objects and dispatches appropriate events - * @param {Event} [e] Event (passed along when firing) - * @return {fabric.Canvas} thisArg - */ + * Deactivates all objects and dispatches appropriate events + * @param {Event} [e] Event (passed along when firing) + * @return {fabric.Canvas} thisArg + */ deactivateAllWithDispatch(e?: Event): ICanvas; /** - * Discards currently active group - * @param {Event} [e] Event (passed along when firing) - * @return {fabric.Canvas} thisArg - */ + * Discards currently active group + * @param {Event} [e] Event (passed along when firing) + * @return {fabric.Canvas} thisArg + */ discardActiveGroup(e?: Event): ICanvas; /** - * Discards currently active object - * @param {Event} [e] Event (passed along when firing) - * @return {fabric.Canvas} thisArg - * @chainable - */ + * Discards currently active object + * @param {Event} [e] Event (passed along when firing) + * @return {fabric.Canvas} thisArg + * @chainable + */ discardActiveObject(e?: Event): ICanvas; /** - * Draws objects' controls (borders/controls) - * @param {CanvasRenderingContext2D} ctx Context to render controls on - */ + * Draws objects' controls (borders/controls) + * @param {CanvasRenderingContext2D} ctx Context to render controls on + */ drawControls(ctx: CanvasRenderingContext2D): void; - drawDashedLine(ctx: CanvasRenderingContext2D, x: number, y: number, x2: number, y2: number, dashArray: number[]): ICanvas; /** - * Method that determines what object we are clicking on - * @param {Event} e mouse event - * @param {Boolean} skipGroup when true, group is skipped and only objects are traversed through - */ + * Method that determines what object we are clicking on + * @param {Event} e mouse event + * @param {Boolean} skipGroup when true, group is skipped and only objects are traversed through + */ findTarget(e: MouseEvent, skipGroup: boolean): ICanvas; /** - * Returns currently active group - * @return {fabric.Group} Current group - */ + * Returns currently active group + * @return {fabric.Group} Current group + */ getActiveGroup(): IGroup; /** - * Returns currently active object - * @return {fabric.Object} active object - */ + * Returns currently active object + * @return {fabric.Object} active object + */ getActiveObject(): IObject; /** - * Returns pointer coordinates relative to canvas. - * @param {Event} e - * @return {Object} object with "x" and "y" number values - */ + * Returns pointer coordinates relative to canvas. + * @param {Event} e + * @return {Object} object with "x" and "y" number values + */ getPointer(e: Event, ignoreZoom?: boolean, upperCanvasEl?: CanvasRenderingContext2D): { x: number; y: number; }; /** - * Returns context of canvas where object selection is drawn - * @return {CanvasRenderingContext2D} - */ + * Returns context of canvas where object selection is drawn + * @return {CanvasRenderingContext2D} + */ getSelectionContext(): CanvasRenderingContext2D; /** - * Returns element on which object selection is drawn - * @return {HTMLCanvasElement} - */ + * Returns element on which object selection is drawn + * @return {HTMLCanvasElement} + */ getSelectionElement(): HTMLCanvasElement; /** - * Returns true if object is transparent at a certain location - * @param {fabric.Object} target Object to check - * @param {Number} x Left coordinate - * @param {Number} y Top coordinate - */ + * Returns true if object is transparent at a certain location + * @param {fabric.Object} target Object to check + * @param {Number} x Left coordinate + * @param {Number} y Top coordinate + */ isTargetTransparent(target: IObject, x: number, y: number): boolean; /** - * Sets active group to a speicified one - * @param {fabric.Group} group Group to set as a current one - * @param {Event} [e] Event (passed along when firing) - */ + * Sets active group to a speicified one + * @param {fabric.Group} group Group to set as a current one + * @param {Event} [e] Event (passed along when firing) + */ setActiveGroup(group: IGroup, e?: Event): ICanvas; /** - * Sets given object as the only active object on canvas - * @param {fabric.Object} object Object to set as an active one - * @param {Event} [e] Event (passed along when firing "object:selected") - */ + * Sets given object as the only active object on canvas + * @param {fabric.Object} object Object to set as an active one + * @param {Event} [e] Event (passed along when firing "object:selected") + */ setActiveObject(object: IObject, e?: Event): ICanvas; /** - * Set the cursor type of the canvas element - * @param {String} value Cursor type of the canvas element. - * @see http://www.w3.org/TR/css3-ui/#cursor - */ + * Set the cursor type of the canvas element + * @param {String} value Cursor type of the canvas element. + * @see http://www.w3.org/TR/css3-ui/#cursor + */ setCursor(value: string): void; - - loadFromJSON(json, callback: () => void): void; - loadFromDatalessJSON(json, callback: () => void): void; + /** + * Removes all event listeners + */ + removeListeners(): void } interface ICanvasStatic { /** - * Constructor - * @param {HTMLElement|String} element element to initialize instance on - * @param {Object} [options] Options object - */ + * Constructor + * @param {HTMLElement|String} element element to initialize instance on + * @param {Object} [options] Options object + */ new (element: HTMLCanvasElement | string, options?: ICanvasOptions): ICanvas; EMPTY_JSON: string; @@ -1569,8 +1578,6 @@ declare module fabric { toJSON(propertiesToInclude?: any[]): string; } - - /////////////////////////////////////////////////////////////////////////////// // Shape Interfaces ////////////////////////////////////////////////////////////////////////////// @@ -1591,17 +1598,15 @@ declare module fabric { endAngle?: number; } interface ICircle extends IObject, ICircleOptions { - initialize(options?: ICircleOptions): ICircle; - /** * Returns complexity of an instance * @return {Number} complexity of this instance */ complexity(): number; /** - * Returns horizontal radius of an object (according to how an object is scaled) - * @return {Number} - */ + * Returns horizontal radius of an object (according to how an object is scaled) + * @return {Number} + */ getRadiusX(): number; /** * Returns vertical radius of an object (according to how an object is scaled) @@ -1629,14 +1634,14 @@ declare module fabric { } interface ICircleStatic { /** - * List of attribute names to account for when parsing SVG element (used by {@link fabric.Circle.fromElement}) - */ + * List of attribute names to account for when parsing SVG element (used by {@link fabric.Circle.fromElement}) + */ ATTRIBUTE_NAMES: string[]; /** - * Returns Circle instance from an SVG element - * @param {SVGElement} element Element to parse - * @param {Object} [options] Options object - */ + * Returns Circle instance from an SVG element + * @param {SVGElement} element Element to parse + * @param {Object} [options] Options object + */ fromElement(element: SVGElement, options: ICircleOptions): ICircle; /** * Returns Circle instance from an object representation @@ -1652,8 +1657,8 @@ declare module fabric { interface IEllipseOptions extends IObjectOptions { /** - * Horizontal radius - */ + * Horizontal radius + */ rx?: number; /** * Vertical radius @@ -1661,7 +1666,6 @@ declare module fabric { ry?: number; } interface IEllipse extends IObject, IEllipseOptions { - initialize(options?: IEllipseOptions): IEllipse; /** * Returns horizontal radius of an object (according to how an object is scaled) * @return {Number} @@ -1694,8 +1698,8 @@ declare module fabric { interface IEllipseStatic { new (options?: IEllipseOptions): IEllipse; /** - * List of attribute names to account for when parsing SVG element (used by {@link fabric.Ellipse.fromElement}) - */ + * List of attribute names to account for when parsing SVG element (used by {@link fabric.Ellipse.fromElement}) + */ ATTRIBUTE_NAMES: string[]; /** @@ -1703,7 +1707,7 @@ declare module fabric { * @param {SVGElement} element Element to parse * @param {Object} [options] Options object */ - fromElement(element: SVGElement, options?: IEllipseOptions): IEllipse + fromElement(element: SVGElement, options?: IEllipseOptions): IEllipse; /** * Returns Ellipse instance from an object representation @@ -1713,9 +1717,6 @@ declare module fabric { } interface IGroup extends IObject, ICollection { - initialize(objects?: IObject[], options?: IObjectOptions): any; - type: string; - activateAllObjects(): IGroup; /** * Adds an object to a group; Then recalculates group's dimension, position. @@ -1724,23 +1725,23 @@ declare module fabric { * @chainable */ addWithUpdate(object: IObject): IGroup; - containsPoint(point): boolean; + containsPoint(point: IPoint): boolean; /** - * Destroys a group (restoring state of its objects) - * @return {fabric.Group} thisArg - * @chainable - */ + * Destroys a group (restoring state of its objects) + * @return {fabric.Group} thisArg + * @chainable + */ destroy(): IGroup; /** - * Returns requested property - * @param {String} prop Property to get - * @return {Any} - */ + * Returns requested property + * @param {String} prop Property to get + * @return {Any} + */ get(prop: string): any; /** - * Checks whether this group was moved (since `saveCoords` was called last) - * @return {Boolean} true if an object was moved (since fabric.Group#saveCoords was called) - */ + * Checks whether this group was moved (since `saveCoords` was called last) + * @return {Boolean} true if an object was moved (since fabric.Group#saveCoords was called) + */ hasMoved(): boolean; /** * Removes an object from a group; Then recalculates group's dimension, position. @@ -1755,11 +1756,11 @@ declare module fabric { */ render(ctx: CanvasRenderingContext2D): void; /** - * 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 - */ + * 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[]): IGroup; /** * Saves coordinates of this instance (to be used together with `hasMoved`) @@ -1774,7 +1775,6 @@ declare module fabric { * @chainable */ setObjectsCoords(): IGroup; - toGrayscale(): IGroup; /** * Returns object representation of an instance * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output @@ -1836,14 +1836,14 @@ declare module fabric { /** * Image filter array */ - filters: IFilter[]; + filters: IBaseFilter[]; } interface IImage extends IObject, IImageOptions { initialize(element?: string|HTMLImageElement, options?: IImageOptions); /** - * Applies filters assigned to this image (from "filters" array) - * @param {Function} callback Callback is invoked when all filters have been applied and new image is generated - */ + * Applies filters assigned to this image (from "filters" array) + * @param {Function} callback Callback is invoked when all filters have been applied and new image is generated + */ applyFilters(callback: Function); /** * Returns a clone of an instance @@ -1874,18 +1874,18 @@ declare module fabric { render(ctx: CanvasRenderingContext2D, noTransform: boolean); /** - * Sets image element for this instance to a specified one. - * If filters defined they are applied to new image. - * You might need to call `canvas.renderAll` and `object.setCoords` after replacing, to render new image and update controls area. - * @param {HTMLImageElement} element - * @param {Function} [callback] Callback is invoked when all filters have been applied and new image is generated - * @param {Object} [options] Options object - */ + * Sets image element for this instance to a specified one. + * If filters defined they are applied to new image. + * You might need to call `canvas.renderAll` and `object.setCoords` after replacing, to render new image and update controls area. + * @param {HTMLImageElement} element + * @param {Function} [callback] Callback is invoked when all filters have been applied and new image is generated + * @param {Object} [options] Options object + */ setElement(element: HTMLImageElement, callback: Function, options: IImageOptions): IImage; /** * Sets crossOrigin value (on an instance and corresponding image element) */ - setCrossOrigin(value): IImage; + setCrossOrigin(value: string): IImage; /** * Returns object representation of an instance * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output @@ -1919,30 +1919,30 @@ declare module fabric { */ new (element: HTMLImageElement, objObjects: IObjectOptions): IImage; /** - * Creates an instance of fabric.Image from an URL string - * @param {String} url URL to create an image from - * @param {Function} [callback] Callback to invoke when image is created (newly created image is passed as a first argument) - * @param {Object} [imgOptions] Options object - */ + * Creates an instance of fabric.Image from an URL string + * @param {String} url URL to create an image from + * @param {Function} [callback] Callback to invoke when image is created (newly created image is passed as a first argument) + * @param {Object} [imgOptions] Options object + */ fromURL(url: string, callback?: (image: IImage) => any, objObjects?: IObjectOptions): IImage; /** - * Creates an instance of fabric.Image from its object representation - * @static - * @param {Object} object Object to create an instance from - * @param {Function} [callback] Callback to invoke when an image instance is created - */ + * Creates an instance of fabric.Image from its object representation + * @static + * @param {Object} object Object to create an instance from + * @param {Function} [callback] Callback to invoke when an image instance is created + */ fromObject(object: any, callback: (image: IImage) => {}): void; /** - * Returns Image instance from an SVG element - * @param {SVGElement} element Element to parse - * @param {Function} callback Callback to execute when fabric.Image object is created - * @param {Object} [options] Options object - */ + * Returns Image instance from an SVG element + * @param {SVGElement} element Element to parse + * @param {Function} callback Callback to execute when fabric.Image object is created + * @param {Object} [options] Options object + */ fromElement(element: SVGElement, callback: Function, options?: IImageOptions): void; prototype: any; /** - * Default CSS class name for canvas - */ + * Default CSS class name for canvas + */ CSS_CANVAS: string; filters: IAllFilters @@ -1990,16 +1990,16 @@ declare module fabric { interface ILineStatic { ATTRIBUTE_NAMES: string[]; /** - * Returns fabric.Line instance from an SVG element - * @param {SVGElement} element Element to parse - * @param {Object} [options] Options object - */ + * Returns fabric.Line instance from an SVG element + * @param {SVGElement} element Element to parse + * @param {Object} [options] Options object + */ fromElement(element: SVGElement, options?: ILineOptions): ILine; /** - * Returns fabric.Line instance from an object representation - * @param {Object} object Object to create an instance from - */ - fromObject(object): ILine; + * Returns fabric.Line instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): ILine; prototype: any; /** * Constructor @@ -2011,294 +2011,292 @@ declare module fabric { interface IObjectOptions { /** - * Type of an object (rect, circle, path, etc.). - * Note that this property is meant to be read-only and not meant to be modified. - * If you modify, certain parts of Fabric (such as JSON loading) won't work correctly. - */ + * Type of an object (rect, circle, path, etc.). + * Note that this property is meant to be read-only and not meant to be modified. + * If you modify, certain parts of Fabric (such as JSON loading) won't work correctly. + */ type?: string; /** - * Horizontal origin of transformation of an object (one of "left", "right", "center") - */ + * Horizontal origin of transformation of an object (one of "left", "right", "center") + */ originX?: string; /** - * Vertical origin of transformation of an object (one of "top", "bottom", "center") - */ + * Vertical origin of transformation of an object (one of "top", "bottom", "center") + */ originY?: string; /** - * Top position of an object. Note that by default it's relative to object center. You can change this by setting originY={top/center/bottom} - */ + * Top position of an object. Note that by default it's relative to object center. You can change this by setting originY={top/center/bottom} + */ top?: number; /** - * Left position of an object. Note that by default it's relative to object center. You can change this by setting originX={left/center/right} - */ + * Left position of an object. Note that by default it's relative to object center. You can change this by setting originX={left/center/right} + */ left?: number; /** - * Object width - */ + * Object width + */ width?: number; /** - * Object height - */ + * Object height + */ height?: number; /** - * Object scale factor (horizontal) - */ + * Object scale factor (horizontal) + */ scaleX?: number; /** - * Object scale factor (vertical) - */ + * Object scale factor (vertical) + */ scaleY?: number; /** - * When true, an object is rendered as flipped horizontally - */ + * When true, an object is rendered as flipped horizontally + */ flipX?: boolean; /** - * When true, an object is rendered as flipped vertically - */ + * When true, an object is rendered as flipped vertically + */ flipY?: boolean; /** - * Opacity of an object - */ + * Opacity of an object + */ opacity?: number; /** - * Angle of rotation of an object (in degrees) - */ + * Angle of rotation of an object (in degrees) + */ angle?: number; /** - * Size of object's controlling corners (in pixels) - */ + * Size of object's controlling corners (in pixels) + */ cornerSize?: number; /** - * When true, object's controlling corners are rendered as transparent inside (i.e. stroke instead of fill) - */ + * When true, object's controlling corners are rendered as transparent inside (i.e. stroke instead of fill) + */ transparentCorners?: boolean; /** - * Default cursor value used when hovering over this object on canvas - */ + * Default cursor value used when hovering over this object on canvas + */ hoverCursor?: string; /** - * Padding between object and its controlling borders (in pixels) - */ + * Padding between object and its controlling borders (in pixels) + */ padding?: number; /** - * Color of controlling borders of an object (when it's active) - */ + * Color of controlling borders of an object (when it's active) + */ borderColor?: string; /** - * Color of controlling corners of an object (when it's active) - */ + * Color of controlling corners of an object (when it's active) + */ cornerColor?: string; /** - * When true, this object will use center point as the origin of transformation - * when being scaled via the controls. - * Backwards incompatibility note: This property replaces "centerTransform" (Boolean). - */ + * When true, this object will use center point as the origin of transformation + * when being scaled via the controls. + * Backwards incompatibility note: This property replaces "centerTransform" (Boolean). + */ centeredScaling?: boolean; /** - * When true, this object will use center point as the origin of transformation - * when being rotated via the controls. - * Backwards incompatibility note: This property replaces "centerTransform" (Boolean). - */ + * When true, this object will use center point as the origin of transformation + * when being rotated via the controls. + * Backwards incompatibility note: This property replaces "centerTransform" (Boolean). + */ centeredRotation?: boolean; /** - * Color of object's fill - */ + * Color of object's fill + */ fill?: string; /** - * Fill rule used to fill an object - * accepted values are nonzero, evenodd - * Backwards incompatibility note: This property was used for setting globalCompositeOperation until v1.4.12 (use `fabric.Object#globalCompositeOperation` instead) - */ + * Fill rule used to fill an object + * accepted values are nonzero, evenodd + * Backwards incompatibility note: This property was used for setting globalCompositeOperation until v1.4.12, use `globalCompositeOperation` instead + */ fillRule?: string; /** - * Composite rule used for canvas globalCompositeOperation - */ + * Composite rule used for canvas globalCompositeOperation + */ globalCompositeOperation?: string; /** - * Background color of an object. Only works with text objects at the moment. - */ + * Background color of an object. Only works with text objects at the moment. + */ backgroundColor?: string; /** - * When defined, an object is rendered via stroke and this property specifies its color - */ + * When defined, an object is rendered via stroke and this property specifies its color + */ stroke?: string; /** - * Width of a stroke used to render this object - */ + * Width of a stroke used to render this object + */ strokeWidth?: number; /** - * Array specifying dash pattern of an object's stroke (stroke must be defined) - */ + * Array specifying dash pattern of an object's stroke (stroke must be defined) + */ strokeDashArray?: any[]; /** - * Line endings style of an object's stroke (one of "butt", "round", "square") - */ + * Line endings style of an object's stroke (one of "butt", "round", "square") + */ strokeLineCap?: string; /** - * Corner style of an object's stroke (one of "bevil", "round", "miter") - */ + * Corner style of an object's stroke (one of "bevil", "round", "miter") + */ strokeLineJoin?: string; /** - * Maximum miter length (used for strokeLineJoin = "miter") of an object's stroke - */ + * Maximum miter length (used for strokeLineJoin = "miter") of an object's stroke + */ strokeMiterLimit?: number; /** - * Shadow object representing shadow of this shape - */ + * Shadow object representing shadow of this shape + */ shadow?: IShadow|string; /** - * Opacity of object's controlling borders when object is active and moving - */ + * Opacity of object's controlling borders when object is active and moving + */ borderOpacityWhenMoving?: number; /** - * Scale factor of object's controlling borders - */ + * Scale factor of object's controlling borders + */ borderScaleFactor?: number; /** - * Transform matrix (similar to SVG's transform matrix) - */ + * Transform matrix (similar to SVG's transform matrix) + */ transformMatrix?: any[]; /** - * Minimum allowed scale value of an object - */ + * Minimum allowed scale value of an object + */ minScaleLimit?: number; /** - * When set to `false`, an object can not be selected for modification (using either point-click-based or group-based selection). - * But events still fire on it. - */ + * When set to `false`, an object can not be selected for modification (using either point-click-based or group-based selection). + * But events still fire on it. + */ selectable?: boolean; /** - * When set to `false`, an object can not be a target of events. All events propagate through it. Introduced in v1.3.4 - */ + * When set to `false`, an object can not be a target of events. All events propagate through it. Introduced in v1.3.4 + */ evented?: boolean; /** - * When set to `false`, an object is not rendered on canvas - */ + * When set to `false`, an object is not rendered on canvas + */ visible?: boolean; /** - * When set to `false`, object's controls are not displayed and can not be used to manipulate object - */ + * When set to `false`, object's controls are not displayed and can not be used to manipulate object + */ hasControls?: boolean; /** - * When set to `false`, object's controlling borders are not rendered - */ + * When set to `false`, object's controlling borders are not rendered + */ hasBorders?: boolean; /** - * When set to `false`, object's controlling rotating point will not be visible or selectable - */ + * When set to `false`, object's controlling rotating point will not be visible or selectable + */ hasRotatingPoint?: boolean; /** - * Offset for object's controlling rotating point (when enabled via `hasRotatingPoint`) - */ + * Offset for object's controlling rotating point (when enabled via `hasRotatingPoint`) + */ rotatingPointOffset?: number; /** - * When set to `true`, objects are "found" on canvas on per-pixel basis rather than according to bounding box - */ + * When set to `true`, objects are "found" on canvas on per-pixel basis rather than according to bounding box + */ perPixelTargetFind?: boolean; /** - * When `false`, default object's values are not included in its serialization - */ + * When `false`, default object's values are not included in its serialization + */ includeDefaultValues?: boolean; /** - * Function that determines clipping of an object (context is passed as a first argument) - * Note that context origin is at the object's center point (not left/top corner) - * @type Function - */ + * Function that determines clipping of an object (context is passed as a first argument) + * Note that context origin is at the object's center point (not left/top corner) + * @type Function + */ clipTo?: Function; /** - * When `true`, object horizontal movement is locked - */ + * When `true`, object horizontal movement is locked + */ lockMovementX?: boolean; /** - * When `true`, object vertical movement is locked - */ + * When `true`, object vertical movement is locked + */ lockMovementY?: boolean; /** - * When `true`, object rotation is locked - */ + * When `true`, object rotation is locked + */ lockRotation?: boolean; /** - * When `true`, object horizontal scaling is locked - */ + * When `true`, object horizontal scaling is locked + */ lockScalingX?: boolean; /** - * When `true`, object vertical scaling is locked - */ + * When `true`, object vertical scaling is locked + */ lockScalingY?: boolean; /** - * When `true`, object non-uniform scaling is locked - */ + * When `true`, object non-uniform scaling is locked + */ lockUniScaling?: boolean; /** - * When `true`, object cannot be flipped by scaling into negative values - */ + * When `true`, object cannot be flipped by scaling into negative values + */ lockScalingFlip?: boolean; /** - * Not used by fabric, just for convenience - */ + * Not used by fabric, just for convenience + */ name?: string; /** - * Not used by fabric, just for convenience - */ + * Not used by fabric, just for convenience + */ data?: any; } interface IObject extends IObservable, IObjectOptions, IObjectAnimation { - - getCurrentWidth(): number; getCurrentHeight(): number; @@ -2310,7 +2308,6 @@ declare module fabric { getBorderScaleFactor(): number; - getCornersize(): number; setCornersize(value: number): IObject; @@ -2356,216 +2353,420 @@ declare module fabric { setWidth(value: number): IObject; /* * Sets object's properties from options - * @param {Object} [options] Options object - */ + * @param {Object} [options] Options object + */ setOptions(options: any): void; /** - * Transforms context when rendering an object - * @param {CanvasRenderingContext2D} ctx Context - * @param {Boolean} fromLeft When true, context is transformed to object's top/left corner. This is used when rendering text on Node - */ + * Transforms context when rendering an object + * @param {CanvasRenderingContext2D} ctx Context + * @param {Boolean} fromLeft When true, context is transformed to object's top/left corner. This is used when rendering text on Node + */ transform(ctx: CanvasRenderingContext2D, fromLeft: boolean): void; /** - * Returns an object representation of an instance - * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output - */ - toObject(propertiesToInclude?: any[]): any; + * Returns an object representation of an instance + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + */ + toObject(propertiesToInclude?: any[]): any; /** - * Returns (dataless) object representation of an instance - * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output - */ + * Returns (dataless) object representation of an instance + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + */ toDatalessObject(propertiesToInclude?: any[]): any; /** - * Returns a string representation of an instance - */ + * Returns a string representation of an instance + */ toString(): string; /** - * Basic getter - * @param {String} property Property name - */ + * Basic getter + * @param {String} property Property name + */ get(property: string): any; /** - * Sets property to a given value. When changing position/dimension -related properties (left, top, scale, angle, etc.) `set` does not update position of object's borders/controls. - * If you need to update those, call `setCoords()`. - * @param {String|Object} key Property name or object (if object, iterate over the object properties) - * @param {Object|Function} value Property value (if function, the value is passed into it and its return value is used as a new one) - */ - set(key: string|any, value: any|Function): IObject; + * Sets property to a given value. + * When changing position/dimension -related properties (left, top, scale, angle, etc.) `set` does not update position of object's borders/controls. + * If you need to update those, call `setCoords()`. + * @param {String} key Property name + * @param {Object|Function} value Property value (if function, the value is passed into it and its return value is used as a new one) + */ + set(key: string, value: any|Function): IObject; + /** + * Sets property to a given value. + * When changing position/dimension -related properties (left, top, scale, angle, etc.) `set` does not update position of object's borders/controls. + * If you need to update those, call `setCoords()`. + * @param Object key Property object, iterate over the object properties + */ + set(key: any): IObject; /** - * Toggles specified property from `true` to `false` or from `false` to `true` - * @param {String} property Property to toggle - */ + * Toggles specified property from `true` to `false` or from `false` to `true` + * @param {String} property Property to toggle + */ toggle(property: string): IObject; /** - * Sets sourcePath of an object - * @param {String} value Value to set sourcePath to - */ - setSourcePath(value): IObject + * Sets sourcePath of an object + * @param {String} value Value to set sourcePath to + */ + setSourcePath(value: string): IObject; /** - * Retrieves viewportTransform from Object's canvas if possible - * @method getViewportTransform - * @memberOf fabric.Object.prototype - */ + * Retrieves viewportTransform from Object's canvas if possible + */ getViewportTransform(): boolean; - /** - * Renders an object on a specified context - * @param {CanvasRenderingContext2D} ctx Context to render on - * @param {Boolean} [noTransform] When true, context is not transformed - */ + * Renders an object on a specified context + * @param {CanvasRenderingContext2D} ctx Context to render on + * @param {Boolean} [noTransform] When true, context is not transformed + */ render(ctx: CanvasRenderingContext2D, noTransform?: boolean): void; /** - * Clones an instance - * @param {Function} callback Callback is invoked with a clone as a first argument - * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output - */ + * Clones an instance + * @param {Function} callback Callback is invoked with a clone as a first argument + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + */ clone(callback: Function, propertiesToInclude?: any[]): IObject; /** - * Creates an instance of fabric.Image out of an object - * @param {Function} callback callback, invoked with an instance as a first argument - */ + * Creates an instance of fabric.Image out of an object + * @param {Function} callback callback, invoked with an instance as a first argument + */ cloneAsImage(callback: (image: IImage) => any): IObject; - /** - * Converts an object into a data-url-like string - * @param options Options object - */ + * Converts an object into a data-url-like string + * @param options Options object + */ toDataURL(options: IDataURLOptions): string; /** - * Returns true if specified type is identical to the type of an instance - * @param {String} type Type to check against - */ + * Returns true if specified type is identical to the type of an instance + * @param {String} type Type to check against + */ isType(type: string): boolean; /** - * Returns complexity of an instance - */ + * Returns complexity of an instance + */ complexity(): number; /** - * Returns a JSON representation of an instance - * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output - */ + * Returns a JSON representation of an instance + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + */ toJSON(propertiesToInclude?: any[]): any; - - /** - * Sets gradient (fill or stroke) of an object - * Backwards incompatibility note: This method was named "setGradientFill" until v1.1.0 - * @param {String} property Property name 'stroke' or 'fill' - * @param {Object} [options] Options object - */ - setGradient(property: string, options: IGradientOptions): IObject; - + * Sets gradient (fill or stroke) of an object + * Backwards incompatibility note: This method was named "setGradientFill" until v1.1.0 + * @param {String} property Property name 'stroke' or 'fill' + * @param {Object} [options] Options object + */ + setGradient(property: string, options: IGradientOptions): IObject; /** - * Sets pattern fill of an object - * @param {Object} options Options object - */ + * Sets pattern fill of an object + * @param {Object} options Options object + */ setPatternFill(options: IFillOptions): IObject; /** - * Sets shadow of an object - * @param {String} [options] Options object or string (e.g. "2px 2px 10px rgba(0,0,0,0.2)") - */ + * Sets shadow of an object + * @param {String} [options] Options object or string (e.g. "2px 2px 10px rgba(0,0,0,0.2)") + */ setShadow(options?: string): IObject; /** - * Sets shadow of an object - * @param [options] Options object - */ + * Sets shadow of an object + * @param [options] Options object + */ setShadow(options: IShadow): IObject; /** - * Sets "color" of an instance (alias of `set('fill', …)`) - * @param {String} color Color value - */ + * Sets "color" of an instance (alias of `set('fill', …)`) + * @param {String} color Color value + */ setColor(color: string): IObject; /** - * Sets "angle" of an instance - * @param {Number} angle Angle value - */ - setAngle(angle: number): IObject + * Sets "angle" of an instance + * @param {Number} angle Angle value + */ + setAngle(angle: number): IObject; /** - * Sets "angle" of an instance - * @param {Number} angle Angle value - */ - rotate(angle: number): IObject + * Sets "angle" of an instance + * @param {Number} angle Angle value + */ + rotate(angle: number): IObject; /** - * Centers object horizontally on canvas to which it was added last. - * You might need to call `setCoords` on an object after centering, to update controls area. - */ + * Centers object horizontally on canvas to which it was added last. + * You might need to call `setCoords` on an object after centering, to update controls area. + */ centerH(): void; /** - * Centers object vertically on canvas to which it was added last. - * You might need to call `setCoords` on an object after centering, to update controls area. - */ + * Centers object vertically on canvas to which it was added last. + * You might need to call `setCoords` on an object after centering, to update controls area. + */ centerV(): void; /** - * Centers object vertically and horizontally on canvas to which is was added last - * You might need to call `setCoords` on an object after centering, to update controls area. - */ + * Centers object vertically and horizontally on canvas to which is was added last + * You might need to call `setCoords` on an object after centering, to update controls area. + */ center(): void; /** - * Removes object from canvas to which it was added last - */ + * Removes object from canvas to which it was added last + */ remove(): IObject; /** - * Returns coordinates of a pointer relative to an object - * @param {Event} e Event to operate upon - * @param {Object} [pointer] Pointer to operate upon (instead of event) - */ + * Returns coordinates of a pointer relative to an object + * @param {Event} e Event to operate upon + * @param {Object} [pointer] Pointer to operate upon (instead of event) + */ getLocalPointer(e: Event, pointer: any): any; - // methods - bringForward(intersecting?: boolean): IObject; - bringToFront(): IObject; - drawBorders(context: CanvasRenderingContext2D): IObject; - drawCorners(context: CanvasRenderingContext2D): IObject; - 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; - saveState(): IObject; - scale(value: number): IObject; - scaleToHeight(value: number): IObject; - scaleToWidth(value: number): IObject; - sendBackwards(intersecting?: boolean): IObject; - sendToBack(): IObject; - - setActive(active: boolean): IObject; - setCoords(); + /** + * Sets object's properties from options + * @param {Object} [options] Options object + */ setOptions(options: any); + /** + * Sets sourcePath of an object + * @param {String} value Value to set sourcePath to + */ setSourcePath(value: string): IObject; - toGrayscale(): IObject; + // functions from object svg export mixin + // ----------------------------------------------------------------------------------------------------------------------------------- + /** + * Returns styles-string for svg-export + */ + getSvgStyles(): string; + /** + * Returns transform-string for svg-export + */ + getSvgTransform(): string; + /** + * Returns transform-string for svg-export from the transform matrix of single elements + */ + getSvgTransformMatrix(): string; + + // functions from stateful mixin + // ----------------------------------------------------------------------------------------------------------------------------------- + /** + * Returns true if object state (one of its state properties) was changed + */ + hasStateChanged(): boolean; + /** + * Saves state of an object + * @param {Object} [options] Object with additional `stateProperties` array to include when saving state + * @return {fabric.Object} thisArg + */ + saveState(options?: { stateProperties: any[] }): IObject; + /** + * Setups state of an object + */ + setupState(): IObject; + // functions from object straightening mixin + // ----------------------------------------------------------------------------------------------------------------------------------- + /** + * Straightens an object (rotating it from current angle to one of 0, 90, 180, 270, etc. depending on which is closer) + */ + straighten(): IObject; + /** + * Same as straighten but with animation + * @param {Object} callbacks Object with callback functions + * @param {Function} [callbacks.onComplete] Invoked on completion + * @param {Function} [callbacks.onChange] Invoked on every step of animation + */ + fxStraighten(callbacks: { onComplete?: Function; onChange: Function }): IObject; + + // functions from object stacking mixin + // ----------------------------------------------------------------------------------------------------------------------------------- + /** + * Moves an object up in stack of drawn objects + * @param {Boolean} [intersecting] If `true`, send object in front of next upper intersecting object + */ + bringForward(intersecting?: boolean): IObject; + /** + * Moves an object to the top of the stack of drawn objects + */ + bringToFront(): IObject; + /** + * Moves an object down in stack of drawn objects + * @param {Boolean} [intersecting] If `true`, send object behind next lower intersecting object + */ + sendBackwards(intersecting?: boolean): IObject; + /** + * Moves an object to the bottom of the stack of drawn objects + */ + sendToBack(): IObject; + /** + * Moves an object to specified level in stack of drawn objects + * @param {Number} index New position of object + */ + moveTo(index: number): IObject; + + // functions from object origin mixin + // ----------------------------------------------------------------------------------------------------------------------------------- + /** + * Translates the coordinates from origin to center coordinates (based on the object's dimensions) + * @param {fabric.Point} point The point which corresponds to the originX and originY params + * @param {String} originX Horizontal origin: 'left', 'center' or 'right' + * @param {String} originY Vertical origin: 'top', 'center' or 'bottom' + */ + translateToCenterPoint(point: IPoint, originX: string, originY: string): IPoint; + + /** + * Translates the coordinates from center to origin coordinates (based on the object's dimensions) + * @param {fabric.Point} center The point which corresponds to center of the object + * @param {String} originX Horizontal origin: 'left', 'center' or 'right' + * @param {String} originY Vertical origin: 'top', 'center' or 'bottom' + */ + translateToOriginPoint(center: IPoint, originX: string, originY: string): IPoint; + /** + * Returns the real center coordinates of the object + */ + getCenterPoint(): IPoint; + + /** + * Returns the coordinates of the object as if it has a different origin + * @param {String} originX Horizontal origin: 'left', 'center' or 'right' + * @param {String} originY Vertical origin: 'top', 'center' or 'bottom' + */ + getPointByOrigin(): IPoint; + + /** + * Returns the point in local coordinates + * @param {fabric.Point} point The point relative to the global coordinate system + * @param {String} originX Horizontal origin: 'left', 'center' or 'right' + * @param {String} originY Vertical origin: 'top', 'center' or 'bottom' + */ + toLocalPoint(point: IPoint, originX: string, originY: string): IPoint; + + /** + * Sets the position of the object taking into consideration the object's origin + * @param {fabric.Point} pos The new position of the object + * @param {String} originX Horizontal origin: 'left', 'center' or 'right' + * @param {String} originY Vertical origin: 'top', 'center' or 'bottom' + * @return {void} + */ + setPositionByOrigin(pos: IPoint, originX: string, originY: string): void; + + /** + * @param {String} to One of 'left', 'center', 'right' + */ + adjustPosition(to: string): void; + + // functions from interactivity mixin + // ----------------------------------------------------------------------------------------------------------------------------------- + /**- + * Draws borders of an object's bounding box. + * Requires public properties: width, height + * Requires public options: padding, borderColor + * @param {CanvasRenderingContext2D} ctx Context to draw on + */ + drawBorders(context: CanvasRenderingContext2D): IObject; + + /** + * Draws corners of an object's bounding box. + * Requires public properties: width, height + * Requires public options: cornerSize, padding + * @param {CanvasRenderingContext2D} ctx Context to draw on + */ + drawCorners(context: CanvasRenderingContext2D): IObject; + + /** + * Returns true if the specified control is visible, false otherwise. + * @param {String} controlName The name of the control. Possible values are 'tl', 'tr', 'br', 'bl', 'ml', 'mt', 'mr', 'mb', 'mtr'. + */ + isControlVisible(controlName: string): boolean; + /** + * Sets the visibility of the specified control. + * @param {String} controlName The name of the control. Possible values are 'tl', 'tr', 'br', 'bl', 'ml', 'mt', 'mr', 'mb', 'mtr'. + * @param {Boolean} visible true to set the specified control visible, false otherwise + */ + setControlVisible(controlName: string, visible: boolean): IObject; + + /** + * Sets the visibility state of object controls. + * @param {Object} [options] Options object + */ + setControlsVisibility(options?: { + bl?: boolean; + br?: boolean; + mb?: boolean; + ml?: boolean; + mr?: boolean; + mt?: boolean; + tl?: boolean; + tr?: boolean; + mtr?: boolean; }): IObject; + + // functions from geometry mixin + // ------------------------------------------------------------------------------------------------------------------------------- + /** + * Sets corner position coordinates based on current angle, width and height + * See https://github.com/kangax/fabric.js/wiki/When-to-call-setCoords + */ + setCoords(): IObject; + /** + * Returns coordinates of object's bounding rectangle (left, top, width, height) + * @return {Object} Object with left, top, width, height properties + */ + getBoundingRect(): { left: number; top: number; width: number; height: number }; + /** + * Checks if object is fully contained within area of another object + * @param {Object} other Object to test + */ + isContainedWithinObject(other: IObject): boolean; + /** + * Checks if object is fully contained within area formed by 2 points + * @param {Object} pointTL top-left point of area + * @param {Object} pointBR bottom-right point of area + */ + isContainedWithinRect(pointTL: any, pointBR: any): boolean; + /** + * Checks if point is inside the object + * @param {fabric.Point} point Point to check against + */ + containsPoint(point: IPoint): boolean; + /** + * Scales an object (equally by x and y) + * @param {Number} value Scale factor + * @return {fabric.Object} thisArg + */ + scale(value: number): IObject; + /** + * Scales an object to a given height, with respect to bounding box (scaling by x/y equally) + * @param {Number} value New height value + */ + scaleToHeight(value: number): IObject; + /** + * Scales an object to a given width, with respect to bounding box (scaling by x/y equally) + * @param {Number} value New width value + */ + scaleToWidth(value: number): IObject; + /** + * Checks if object intersects with another object + * @param {Object} other Object to test + */ + intersectsWithObject(other: IObject): boolean; + /** + * Checks if object intersects with an area formed by 2 points + * @param {Object} pointTL top-left point of area + * @param {Object} pointBR bottom-right point of area + */ + intersectsWithRect(pointTL: any, pointBR: any): boolean; } interface IObjectStatic { prototype: any; @@ -2661,9 +2862,9 @@ declare module fabric { */ isSameColor(): boolean; /** - * Renders this group on a specified context - * @param {CanvasRenderingContext2D} ctx Context to render this instance on - */ + * Renders this group on a specified context + * @param {CanvasRenderingContext2D} ctx Context to render this instance on + */ render(ctx: CanvasRenderingContext2D); /** * Returns dataless object representation of this path group @@ -2671,12 +2872,11 @@ declare module fabric { * @return {Object} dataless object representation of an instance */ toDatalessObject(propertiesToInclude?: any[]): any; - toGrayscale(): IPathGroup; /** - * Returns object representation of this path group - * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output - * @return {Object} object representation of an instance - */ + * Returns object representation of this path group + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + * @return {Object} object representation of an instance + */ toObject(propertiesToInclude?: any[]): any; /** * Returns a string representation of this path group @@ -2696,7 +2896,7 @@ declare module fabric { getObjects(): IPath[]; } interface IPathGroupStatic { - fromObject(object): IPathGroup; + fromObject(object: any): IPathGroup; /** * Constructor * @param {Array} paths @@ -2704,12 +2904,12 @@ declare module fabric { */ new (paths: IPath[], options?: IObjectOptions): IPathGroup; /** - * Creates fabric.PathGroup instance from an object representation - * @static - * @memberOf fabric.PathGroup - * @param {Object} object Object to create an instance from - * @param {Function} callback Callback to invoke when an fabric.PathGroup instance is created - */ + * Creates fabric.PathGroup instance from an object representation + * @static + * @memberOf fabric.PathGroup + * @param {Object} object Object to create an instance from + * @param {Function} callback Callback to invoke when an fabric.PathGroup instance is created + */ fromObject(object: any, callback: (group: IPathGroup) => any): void; prototype: any; } @@ -2718,7 +2918,7 @@ declare module fabric { /** * Points array */ - points?: IPoint[] + points?: IPoint[]; /** * Minimum X from points values, necessary to offset points @@ -2752,8 +2952,8 @@ declare module fabric { } interface IPolygonStatic { /** - * List of attribute names to account for when parsing SVG element (used by `fabric.Polygon.fromElement`) - */ + * List of attribute names to account for when parsing SVG element (used by `fabric.Polygon.fromElement`) + */ ATTRIBUTE_NAMES: string[]; /** @@ -2763,9 +2963,9 @@ declare module fabric { */ fromElement(element: SVGElement, options?: IPolygonOptions): IPolygon; /** - * Returns fabric.Polygon instance from an object representation - * @param {Object} object Object to create an instance from - */ + * Returns fabric.Polygon instance from an object representation + * @param {Object} object Object to create an instance from + */ fromObject(object: any): IPolygon; /** * Constructor @@ -2780,7 +2980,7 @@ declare module fabric { /** * Points array */ - points?: IPoint[] + points?: IPoint[]; /** * Minimum X from points values, necessary to offset points @@ -2814,8 +3014,8 @@ declare module fabric { } interface IPolylineStatic { /** - * List of attribute names to account for when parsing SVG element (used by `fabric.Polygon.fromElement`) - */ + * List of attribute names to account for when parsing SVG element (used by `fabric.Polygon.fromElement`) + */ ATTRIBUTE_NAMES: string[]; /** @@ -2825,9 +3025,9 @@ declare module fabric { */ fromElement(element: SVGElement, options?: IPolylineOptions): IPolyline; /** - * Returns fabric.Polyline instance from an object representation - * @param {Object} object Object to create an instance from - */ + * Returns fabric.Polyline instance from an object representation + * @param {Object} object Object to create an instance from + */ fromObject(object: any): IPolyline; /** * Constructor @@ -2875,19 +3075,19 @@ declare module fabric { } interface IRectStatic { /** - * List of attribute names to account for when parsing SVG element (used by `fabric.Rect.fromElement`) - */ + * List of attribute names to account for when parsing SVG element (used by `fabric.Rect.fromElement`) + */ ATTRIBUTE_NAMES: string[]; /** - * Returns Rect instance from an SVG element - * @param {SVGElement} element Element to parse - * @param {Object} [options] Options object - */ + * Returns Rect instance from an SVG element + * @param {SVGElement} element Element to parse + * @param {Object} [options] Options object + */ fromElement(element: SVGElement, options?: IRectOptions): IRect; /** - * Returns Rect instance from an object representation - * @param {Object} object Object to create an instance from - */ + * Returns Rect instance from an object representation + * @param {Object} object Object to create an instance from + */ fromObject(object: any): IRect; /** * Constructor @@ -2907,8 +3107,8 @@ declare module fabric { */ fontWeight?: number|string; /** - * Font family - */ + * Font family + */ fontFamily?: string; /** * Text decoration Possible values?: "", "underline", "overline" or "line-through". @@ -2927,9 +3127,9 @@ declare module fabric { */ lineHeight?: number; /** - * When defined, an object is rendered via stroke and this property specifies its color. - * Backwards incompatibility note?: This property was named "strokeStyle" until v1.1.6 - */ + * When defined, an object is rendered via stroke and this property specifies its color. + * Backwards incompatibility note?: This property was named "strokeStyle" until v1.1.6 + */ stroke?: string; /** * Shadow object representing shadow of this shape. @@ -2938,8 +3138,6 @@ declare module fabric { shadow?: IShadow|string; /** * Background color of text lines - * @type String - * @default */ textBackgroundColor?: string; @@ -2948,18 +3146,13 @@ declare module fabric { text?: string; } interface IText extends IObject, ITextOptions { - - - initialize(text: string, options?: IITextOptions): IText; /** * Returns complexity of an instance - * @return {Number} complexity */ complexity(): number; /** - * Returns string representation of an instance - * @return {String} String representation of text object - */ + * Returns string representation of an instance + */ toString(): string; /** * Renders text instance on a specified context @@ -2968,15 +3161,12 @@ declare module fabric { render(ctx: CanvasRenderingContext2D, noTransform: boolean); /** * Returns object representation of an instance - * @method toObject * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output - * @return {Object} object representation of an instance */ toObject(propertiesToInclude?: any[]): IObject; /** * Returns SVG representation of an instance * @param {Function} [reviver] Method for further parsing of svg representation. - * @return {String} svg representation of an instance */ toSVG(reviver?: Function): string; /** @@ -2987,14 +3177,13 @@ declare module fabric { * Sets object's fontSize * @param {Number} fontSize Font size (in pixels) */ - setFontSize(fontSize): IText; + setFontSize(fontSize: number): IText; /** * Retrieves object's fontWeight */ getFontWeight(): number|string; /** * Sets object's fontWeight - * @method setFontWeight * @param {(Number|String)} fontWeight Font weight */ setFontWeight(fontWeight: string|number): IText; @@ -3061,12 +3250,11 @@ declare module fabric { * @param {String} textBackgroundColor Text background color */ setTextBackgroundColor(textBackgroundColor: string): IText; - } interface ITextStatic { /** - * List of attribute names to account for when parsing SVG element (used by `fabric.Text.fromElement`) - */ + * List of attribute names to account for when parsing SVG element (used by `fabric.Text.fromElement`) + */ ATTRIBUTE_NAMES: string[]; /** * Default SVG font size @@ -3084,8 +3272,7 @@ declare module fabric { * @param {SVGElement} element Element to parse * @param {Object} [options] Options object */ - fromElement(element: SVGElement, options?: ITextOptions): IText - + fromElement(element: SVGElement, options?: ITextOptions): IText; /** * Returns fabric.Text instance from an object representation * @param {Object} object Object to create an instance from @@ -3156,11 +3343,9 @@ declare module fabric { caching?: boolean; } interface IIText extends IObject, IText, IITextOptions { - initialize(text?: string, options?: IITextOptions): IText; - /** - * Returns true if object has no styling - */ + * Returns true if object has no styling + */ isEmptyStyles(): boolean; render(ctx: CanvasRenderingContext2D, noTransform: boolean); /** @@ -3183,11 +3368,11 @@ declare module fabric { */ setSelectionEnd(index: number): void; /** - * Gets style of a current selection/cursor (at the start position) - * @param {Number} [startIndex] Start index to get styles at - * @param {Number} [endIndex] End index to get styles at - * @return {Object} styles Style object at a specified (or current) index - */ + * Gets style of a current selection/cursor (at the start position) + * @param {Number} [startIndex] Start index to get styles at + * @param {Number} [endIndex] End index to get styles at + * @return {Object} styles Style object at a specified (or current) index + */ getSelectionStyles(startIndex: number, endIndex: number): any; /** * Sets style of a current selection @@ -3198,8 +3383,8 @@ declare module fabric { setSelectionStyles(styles: any): IText; /** - * Renders cursor or selection (depending on what exists) - */ + * Renders cursor or selection (depending on what exists) + */ renderCursorOrSelection(): void; /** @@ -3211,7 +3396,7 @@ declare module fabric { * Returns complete style of char at the current cursor * @param {Number} lineIndex Line index * @param {Number} charIndex Char index - * @return {Object} Character style + * @return {Object} Character style */ getCurrentCharStyle(lineIndex: number, charIndex: number): any; @@ -3234,15 +3419,166 @@ declare module fabric { * Renders cursor * @param {Object} boundaries */ - renderCursor(boundaries): void; + renderCursor(boundaries: any): void; /** - * Renders text selection - * @param {Array} chars Array of characters - * @param {Object} boundaries Object with left/top/leftOffset/topOffset - */ + * Renders text selection + * @param {Array} chars Array of characters + * @param {Object} boundaries Object with left/top/leftOffset/topOffset + */ renderSelection(chars: string[], boundaries: any): void; + // functions from itext behavior mixin + // ------------------------------------------------------------------------------------------------------------------------ + /** + * Initializes all the interactive behavior of IText + */ + initBehavior(): void; + + /** + * Initializes "selected" event handler + */ + initSelectedHandler(): void; + + /** + * Initializes "added" event handler + */ + initAddedHandler(): void; + + initRemovedHandler(): void; + + /** + * Initializes delayed cursor + */ + initDelayedCursor(restart: boolean): void; + + /** + * Aborts cursor animation and clears all timeouts + */ + abortCursorAnimation(): void; + + /** + * Selects entire text + */ + selectAll(): void; + + /** + * Returns selected text + */ + getSelectedText(): string; + + /** + * Find new selection index representing start of current word according to current selection index + * @param {Number} startFrom Surrent selection index + * @return {Number} New selection index + */ + findWordBoundaryLeft(startFrom: number): number; + + /** + * Find new selection index representing end of current word according to current selection index + * @param {Number} startFrom Current selection index + * @return {Number} New selection index + */ + findWordBoundaryRight(startFrom: number): number; + + /** + * Find new selection index representing start of current line according to current selection index + * @param {Number} startFrom Current selection index + */ + findLineBoundaryLeft(startFrom: number): number; + + /** + * Find new selection index representing end of current line according to current selection index + * @param {Number} startFrom Current selection index + */ + findLineBoundaryRight(startFrom: number): number; + + /** + * Returns number of newlines in selected text + */ + getNumNewLinesInSelectedText(): number; + + /** + * Finds index corresponding to beginning or end of a word + * @param {Number} selectionStart Index of a character + * @param {Number} direction: 1 or -1 + */ + searchWordBoundary(selectionStart: number, direction: number): number; + + /** + * Selects a word based on the index + * @param {Number} selectionStart Index of a character + */ + selectWord(selectionStart: number): void; + /** + * Selects a line based on the index + * @param {Number} selectionStart Index of a character + */ + selectLine(selectionStart: number): void; + + /** + * Enters editing state + */ + enterEditing(): IIText; + + /** + * Initializes "mousemove" event handler + */ + initMouseMoveHandler(): void; + /** + * Exits from editing state + * @return {fabric.IText} thisArg + * @chainable + */ + exitEditing(): IIText; + + /** + * Inserts a character where cursor is (replacing selection if one exists) + * @param {String} _chars Characters to insert + */ + insertChars(_chars: string, useCopiedStyle?: boolean): void; + /** + * Inserts new style object + * @param {Number} lineIndex Index of a line + * @param {Number} charIndex Index of a char + * @param {Boolean} isEndOfLine True if it's end of line + */ + insertNewlineStyleObject(lineIndex: number, charIndex: number, isEndOfLine: boolean): void; + + /** + * Inserts style object for a given line/char index + * @param {Number} lineIndex Index of a line + * @param {Number} charIndex Index of a char + * @param {Object} [style] Style object to insert, if given + */ + insertCharStyleObject(lineIndex: number, charIndex: number, isEndOfLine: boolean): void; + + /** + * Inserts style object(s) + * @param {String} _chars Characters at the location where style is inserted + * @param {Boolean} isEndOfLine True if it's end of line + * @param {Boolean} [useCopiedStyle] Style to insert + */ + insertStyleObjects(_chars: string, isEndOfLine: boolean, useCopiedStyle?: boolean): void; + + /** + * Shifts line styles up or down + * @param {Number} lineIndex Index of a line + * @param {Number} offset Can be -1 or +1 + */ + shiftLineStyles(lineIndex: number, offset: number): void; + + /** + * Removes style object + * @param {Boolean} isBeginningOfLine True if cursor is at the beginning of line + * @param {Number} [index] Optional index. When not given, current selectionStart is used. + */ + removeStyleObject(isBeginningOfLine: boolean, index?: number): void; + /** + * Inserts new line + */ + insertNewline(): void; + } interface IITextStatic extends ITextStatic { /** @@ -3252,16 +3588,14 @@ declare module fabric { */ new (text: string, options?: IITextOptions): IIText; /** - * Returns fabric.IText instance from an object representation - * @param {Object} object Object to create an instance from - */ + * Returns fabric.IText instance from an object representation + * @param {Object} object Object to create an instance from + */ fromObject(object: any): IIText; } interface ITriangleOptions extends IObjectOptions { } interface ITriangle extends IObject { - initialize(options: IObjectOptions): ITriangle; - /** * Returns complexity of an instance * @return {Number} complexity of this instance @@ -3282,9 +3616,9 @@ declare module fabric { */ new (options?: ITriangleOptions): ITriangle; /** - * Returns Triangle instance from an object representation - * @param {Object} object Object to create an instance from - */ + * Returns Triangle instance from an object representation + * @param {Object} object Object to create an instance from + */ fromObject(object: any): ITriangle; } @@ -3298,7 +3632,200 @@ declare module fabric { * @param {Object} [options] Options object */ new (options?: any): IBaseFilter; - } + }; + Blend: { + /** + * Constructor + * @param {Object} [options] Options object + */ + new (options?: { color?: string; mode?: string; alpha?: number; image?: IImage }): IBlendFilter; + /** + * Returns filter instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): IBlendFilter + }; + Brightness: { + /** + * Constructor + * @param {Object} [options] Options object + * @param {Number} [options.brightness=0] Value to brighten the image up (0..255) + */ + new (options?: { brightness: number }): IBrightnessFilter; + /** + * Returns filter instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): IBrightnessFilter + }; + Convolute: { + /** + * Constructor + * @param {Object} [options] Options object + * @param {Boolean} [options.opaque=false] Opaque value (true/false) + * @param {Array} [options.matrix] Filter matrix + */ + new (options?: { opaque?: boolean; matrix?: number[] }): IConvoluteFilter; + /** + * Returns filter instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): IConvoluteFilter + }; + GradientTransparency: { + /** + * Constructor + * @param {Object} [options] Options object + * @param {Number} [options.threshold=100] Threshold value + */ + new (options?: { threshold?: number; }): IGradientTransparencyFilter; + /** + * Returns filter instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): IGradientTransparencyFilter + }; + Grayscale: { + /** + * Constructor + * @param {Object} [options] Options object + */ + new (options?: any): IGrayscaleFilter; + /** + * Returns filter instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): IGrayscaleFilter + }; + Invert: { + /** + * Constructor + * @param {Object} [options] Options object + */ + new (options?: any): IInvertFilter; + /** + * Returns filter instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): IInvertFilter + }; + Mask: { + /** + * Constructor + * @param {Object} [options] Options object + * @param {fabric.Image} [options.mask] Mask image object + * @param {Number} [options.channel=0] Rgb channel (0, 1, 2 or 3) + */ + new (options?: { mask?: IImage; channel: number; }): IMaskFilter; + /** + * Returns filter instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): IMaskFilter + }; + Multiply: { + /** + * Constructor + * @param {Object} [options] Options object + * @param {Number} [options.color=#000000] Color to multiply the image pixels with + */ + new (options?: { color: string; }): IMultiplyFilter; + /** + * Returns filter instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): IMultiplyFilter + }; + Noise: { + /** + * Constructor + * @param {Object} [options] Options object + * @param {Number} [options.noise=0] Noise value + */ + new (options?: { noise: number; }): INoiseFilter; + /** + * Returns filter instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): INoiseFilter + }; + Pixelate: { + /** + * Constructor + * @param {Object} [options] Options object + * @param {Number} [options.blocksize=4] Blocksize for pixelate + */ + new (options?: { blocksize?: number; }): IPixelateFilter; + /** + * Returns filter instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): IPixelateFilter + }; + RemoveWhite: { + /** + * Constructor + * @param {Object} [options] Options object + * @param {Number} [options.threshold=30] Threshold value + * @param {Number} [options.distance=20] Distance value + */ + new (options?: { threshold?: number; distance?: number; }): IRemoveWhiteFilter; + /** + * Returns filter instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): IRemoveWhiteFilter + }; + Resize: { + /** + * Constructor + * @param {Object} [options] Options object + */ + new (options?: any): IResizeFilter; + /** + * Returns filter instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): IResizeFilter + }; + Sepia2: { + /** + * Constructor + * @param {Object} [options] Options object + */ + new (options?: any): ISepia2Filter; + /** + * Returns filter instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): ISepia2Filter + }; + Sepia: { + /** + * Constructor + * @param {Object} [options] Options object + */ + new (options?: any): ISepiaFilter; + /** + * Returns filter instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): ISepiaFilter + }; + Tint: { + /** + * Constructor + * @param {Object} [options] Options object + * @param {String} [options.color=#000000] Color to tint the image with + * @param {Number} [options.opacity] Opacity value that controls the tint effect's transparency (0..1) + */ + new (options?: { color?: string; opacity?: number; }): ITintFilter; + /** + * Returns filter instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): ITintFilter + }; } interface IBaseFilter { /** @@ -3309,528 +3836,761 @@ declare module fabric { /** * Returns object representation of an instance */ - toObject(): any; - + toObject(): any; /** * Returns a JSON representation of an instance */ toJSON(): string; } -} -interface IBrightnessFilter { -} -interface IInvertFilter { -} -interface IRemoveWhiteFilter { -} -interface IGrayscaleFilter { -} -interface ISepiaFilter { -} -interface ISepia2Filter { -} -interface INoiseFilter { -} -interface IGradientTransparencyFilter { -} -interface IPixelateFilter { -} -interface IConvoluteFilter { -} - - -/////////////////////////////////////////////////////////////////////////////// -// Fabric util Interface -////////////////////////////////////////////////////////////////////////////// -interface IUtilAnimationOptions { - /** - * Starting value - */ - startValue?: number; - /** - * Ending value - */ - endValue?: number; - /** - * Value to modify the property by - */ - byValue: number; - /** - * Duration of change (in ms) - */ - duration?: number; - /** - * Callback; invoked on every value change - */ - onChange?: Function; - /** - * Callback; invoked when value change is completed - */ - onComplete?: Function - /** - * Easing function - */ - easing?: Function; -} -interface IUtilAnimation { - /** - * Changes value from one to another within certain period of time, invoking callbacks as value is being changed. - * @param {Object} [options] Animation options - */ - animate(options?: IUtilAnimationOptions): void; - /** - * requestAnimationFrame polyfill based on http://paulirish.com/2011/requestanimationframe-for-smart-animating/ - * In order to get a precise start time, `requestAnimFrame` should be called as an entry into the method - * @param {Function} callback Callback to invoke - */ - requestAnimFrame(callback: Function): void; -} - -interface IUtilAnimEase { - easeInBack(): Function; - easeInBounce(): Function; - easeInCirc(): Function; - easeInCubic(): Function; - easeInElastic(): Function; - easeInExpo(): Function; - easeInOutBack(): Function; - easeInOutBounce(): Function; - easeInOutCirc(): Function; - easeInOutCubic(): Function; - easeInOutElastic(): Function; - easeInOutExpo(): Function; - easeInOutQuad(): Function; - easeInOutQuart(): Function; - easeInOutQuint(): Function; - easeInOutSine(): Function; - easeInQuad(): Function; - easeInQuart(): Function; - easeInQuint(): Function; - easeInSine(): Function; - easeOutBack(): Function; - easeOutBounce(): Function; - easeOutCirc(): Function; - easeOutCubic(): Function; - easeOutElastic(): Function; - easeOutExpo(): Function; - easeOutQuad(): Function; - easeOutQuart(): Function; - easeOutQuint(): Function; - easeOutSine(): Function; -} - -interface IUtilArc { - /** - * Draws arc - * @param {CanvasRenderingContext2D} ctx - * @param {Number} fx - * @param {Number} fy - * @param {Array} coords - */ - drawArc(ctx: CanvasRenderingContext2D, fx: number, fy: number, coords: number[]): void; - /** - * Calculate bounding box of a elliptic-arc - * @param {Number} fx start point of arc - * @param {Number} fy - * @param {Number} rx horizontal radius - * @param {Number} ry vertical radius - * @param {Number} rot angle of horizontal axe - * @param {Number} large 1 or 0, whatever the arc is the big or the small on the 2 points - * @param {Number} sweep 1 or 0, 1 clockwise or counterclockwise direction - * @param {Number} tx end point of arc - * @param {Number} ty - */ - getBoundsOfArc(fx: number, fy: number, rx: number, ry: number, rot: number, large: number, sweep: number, tx: number, ty: number): IPoint[]; - /** - * Calculate bounding box of a beziercurve - * @param {Number} x0 starting point - * @param {Number} y0 - * @param {Number} x1 first control point - * @param {Number} y1 - * @param {Number} x2 secondo control point - * @param {Number} y2 - * @param {Number} x3 end of beizer - * @param {Number} y3 - */ - getBoundsOfCurve(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, x3: number, y3: number): IPoint[]; - -} - -interface IUtilDomEvent { - /** - * Cross-browser wrapper for getting event's coordinates - * @param {Event} event Event object - * @param {HTMLCanvasElement} upperCanvasEl <canvas> element on which object selection is drawn - */ - getPointer(event: Event, upperCanvasEl: HTMLCanvasElement): IPoint; - - /** - * Adds an event listener to an element - * @param {HTMLElement} element - * @param {String} eventName - * @param {Function} handler - */ - addListener(element: HTMLElement, eventName: string, handler: Function): void; - - /** - * Removes an event listener from an element - * @param {HTMLElement} element - * @param {String} eventName - * @param {Function} handler - */ - removeListener(element: HTMLElement, eventName: string, handler: Function): void; -} - -interface IUtilDomMisc { - /** - * Takes id and returns an element with that id (if one exists in a document) - * @param {String|HTMLElement} id - */ - getById(id: string|HTMLElement): HTMLElement; - /** - * Converts an array-like object (e.g. arguments or NodeList) to an array - * @param {Object} arrayLike - */ - toArray(arrayLike: any): any[]; - /** - * Creates specified element with specified attributes - * @memberOf fabric.util - * @param {String} tagName Type of an element to create - * @param {Object} [attributes] Attributes to set on an element - * @return {HTMLElement} Newly created element - */ - makeElement(tagName: string, attributes?: any): HTMLElement; - /** - * Adds class to an element - * @param {HTMLElement} element Element to add class to - * @param {String} className Class to add to an element - */ - addClass(element: HTMLElement, classname: string): void; - /** - * Wraps element with another element - * @param {HTMLElement} element Element to wrap - * @param {HTMLElement|String} wrapper Element to wrap with - * @param {Object} [attributes] Attributes to set on a wrapper - */ - wrapElement(element: HTMLElement, wrapper: HTMLElement|string, attributes?: any): HTMLElement; - /** - * Returns element scroll offsets - * @param {HTMLElement} element Element to operate on - * @param {HTMLElement} upperCanvasEl Upper canvas element - */ - getScrollLeftTop(element: HTMLElement, upperCanvasEl: HTMLElement): { left: number; right: number; } - /** - * Returns offset for a given element - * @param {HTMLElement} element Element to get offset for - */ - getElementOffset(element: HTMLElement): { left: number; right: number; } - /** - * Returns style attribute value of a given element - * @param {HTMLElement} element Element to get style attribute for - * @param {String} attr Style attribute to get for element - */ - getElementStyle(elment: HTMLElement, attr: string): string; - /** - * Inserts a script element with a given url into a document; invokes callback, when that script is finished loading - * @memberOf fabric.util - * @param {String} url URL of a script to load - * @param {Function} callback Callback to execute when script is finished loading - */ - getScript(url: string, callback: Function): void; - /** - * Makes element unselectable - * @param {HTMLElement} element Element to make unselectable - */ - makeElementUnselectable(element: HTMLElement): HTMLElement; - /** - * Makes element selectable - * @param {HTMLElement} element Element to make selectable - */ - makeElementSelectable(element: HTMLElement): HTMLElement; -} - -interface IUtilDomRequest { - /** - * Cross-browser abstraction for sending XMLHttpRequest - * @param {String} url URL to send XMLHttpRequest to - * @param {Object} [options] Options object - * @param {String} [options.method="GET"] - * @param {Function} options.onComplete Callback to invoke when request is completed - */ - request(url: string, options?: { method?: string; onComplete: Function }): XMLHttpRequest; -} - -interface IUtilDomStyle { - /** - * Cross-browser wrapper for setting element's style - * @param {HTMLElement} element - * @param {Object} styles - */ - setStyle(element: HTMLElement, styles: any): HTMLElement; -} - -interface IUtilArray { - /** - * Invokes method on all items in a given array - * @param {Array} array Array to iterate over - * @param {String} method Name of a method to invoke - */ - invoke(array: any[], method: string): any[]; - /** - * Finds minimum value in array (not necessarily "first" one) - * @param {Array} array Array to iterate over - * @param {String} byProperty - */ - min(array: any[], byProperty: string): any; - /** - * Finds maximum value in array (not necessarily "first" one) - * @param {Array} array Array to iterate over - * @param {String} byProperty - */ - max(array: any[], byProperty: string): any; -} - -interface IUtilClass { - /** - * Helper for creation of "classes". - * @param {Function} [parent] optional "Class" to inherit from - * @param {Object} [properties] Properties shared by all instances of this class - * (be careful modifying objects defined here as this would affect all instances) - */ - createClass(parent: Function, properties?: any); - /** - * Helper for creation of "classes". - * @param {Object} [properties] Properties shared by all instances of this class - * (be careful modifying objects defined here as this would affect all instances) - */ - createClass(properties?: any); - -} - -interface IUtilObject { - /** - * Copies all enumerable properties of one object to another - * @param {Object} destination Where to copy to - * @param {Object} source Where to copy from - */ - extend(destination: any, source: any): any; - - /** - * Creates an empty object and copies all enumerable properties of another object to it - * @memberOf fabric.util.object - * @param {Object} object Object to clone - * @return {Object} - */ - clone(object: any): any -} - -interface IUtilString { - /** - * Camelizes a string - * @param {String} string String to camelize - */ - camelize(string: string): string; - - /** - * Capitalizes a string - * @param {String} string String to capitalize - * @param {Boolean} [firstLetterOnly] If true only first letter is capitalized - * and other letters stay untouched, if false first letter is capitalized - * and other letters are converted to lowercase. - */ - capitalize(string: string, firstLetterOnly: boolean): string; - - /** - * Escapes XML in a string - * @param {String} string String to escape - */ - escapeXml(string: string): string; -} - -interface IUtilMisc { - /** - * Removes value from an array. - * Presence of value (and its position in an array) is determined via `Array.prototype.indexOf` - * @param {Array} array - * @param {Any} value - */ - removeFromArray(array: any[], value: any): any[]; - - /** - * Returns random number between 2 specified ones. - * @param {Number} min lower limit - * @param {Number} max upper limit - */ - getRandomInt(min: number, max: number): number; - - /** - * Transforms degrees to radians. - * @param {Number} degrees value in degrees - */ - degreesToRadians(degrees: number): number; - - /** - * Transforms radians to degrees. - * @memberOf fabric.util - * @param {Number} radians value in radians - */ - radiansToDegrees(radians: number): number; - - /** - * Rotates `point` around `origin` with `radians` - * @param {fabric.Point} point The point to rotate - * @param {fabric.Point} origin The origin of the rotation - * @param {Number} radians The radians of the angle for the rotation - */ - rotatePoint(point: IPoint, origin: IPoint, radians: number): IPoint; - - /** - * Apply transform t to point p - * @param {fabric.Point} p The point to transform - * @param {Array} t The transform - * @param {Boolean} [ignoreOffset] Indicates that the offset should not be applied - */ - transformPoint(p: IPoint, t: any[], ignoreOffset?: boolean): IPoint - - /** - * Invert transformation t - * @param {Array} t The transform - */ - invertTransform(t: any[]): any[]; - - /** - * A wrapper around Number#toFixed, which contrary to native method returns number, not string. - * @param {Number|String} number number to operate on - * @param {Number} fractionDigits number of fraction digits to "leave" - */ - toFixed(number: number, fractionDigits: number): number; - - /** - * Converts from attribute value to pixel value if applicable. - * Returns converted pixels or original value not converted. - * @param {Number|String} value number to operate on - */ - parseUnit(value: number|string, fontSize?: number): number|string; - - /** - * Function which always returns `false`. - */ - falseFunction(): boolean - - /** - * Returns klass "Class" object of given namespace - * @param {String} type Type of object (eg. 'circle') - * @param {String} namespace Namespace to get klass "Class" object from - */ - getKlass(type: string, namespace: string): any; - - /** - * Returns object of given namespace - * @param {String} namespace Namespace string e.g. 'fabric.Image.filter' or 'fabric' - */ - resolveNamespace(namespace: string): any; - - /** - * Loads image element from given url and passes it to a callback - * @param {String} url URL representing an image - * @param {Function} callback Callback; invoked with loaded image - * @param {Any} [context] Context to invoke callback in - * @param {Object} [crossOrigin] crossOrigin value to set image element to - */ - loadImage(url: string, callback: (image: HTMLImageElement) => {}, context?: any, crossOrigin?: boolean): void; - - /** - * Creates corresponding fabric instances from their object representations - * @param {Array} objects Objects to enliven - * @param {Function} callback Callback to invoke when all objects are created - * @param {String} namespace Namespace to get klass "Class" object from - * @param {Function} reviver Method for further parsing of object elements, called after each fabric object created. - */ - enlivenObjects(objects: any[], callback: Function, namespace: string, reviver?: Function): void; - - /** - * Groups SVG elements (usually those retrieved from SVG document) - * @param {Array} elements SVG elements to group - * @param {Object} [options] Options object - */ - groupSVGElements(elements: any[], options?: any, path?: any): IPathGroup - - /** - * Populates an object with properties of another object - * @param {Object} source Source object - * @param {Object} destination Destination object - * @param {Array} properties Propertie names to include - */ - populateWithProperties(source: any, destination: any, properties: any): void; - - /** - * Draws a dashed line between two points - * - * This method is used to draw dashed line around selection area. - * - * @param {CanvasRenderingContext2D} ctx context - * @param {Number} x start x coordinate - * @param {Number} y start y coordinate - * @param {Number} x2 end x coordinate - * @param {Number} y2 end y coordinate - * @param {Array} da dash array pattern - */ - drawDashedLine(ctx: CanvasRenderingContext2D, x: number, y: number, x2: number, y2: number, da: any[]): void; - - /** - * Creates canvas element and initializes it via excanvas if necessary - * @param {CanvasElement} [canvasEl] optional canvas element to initialize; - * when not given, element is created implicitly - */ - createCanvasElement(canvasEl?: HTMLCanvasElement): HTMLCanvasElement; - - /** - * Creates image element (works on client and node) - */ - createImage(): HTMLImageElement; - - /** - * Creates accessors (getXXX, setXXX) for a "class", based on "stateProperties" array - * @param {Object} klass "Class" to create accessors for - */ - createAccessors(klass: any): any; - - /** - * @param {fabric.Object} receiver Object implementing `clipTo` method - * @param {CanvasRenderingContext2D} ctx Context to clip - */ - clipContext(receiver: IObject, ctx: CanvasRenderingContext2D): void; - - /** - * Multiply matrix A by matrix B to nest transformations - * @param {Array} a First transformMatrix - * @param {Array} b Second transformMatrix - */ - multiplyTransformMatrices(a: any[], b: any[]): any[] - - /** - * Returns string representation of function body - * @param {Function} fn Function to get body of - */ - getFunctionBody(fn: Function): string; - - /** - * Returns true if context has transparent pixel - * at specified location (taking tolerance into account) - * @param {CanvasRenderingContext2D} ctx context - * @param {Number} x x coordinate - * @param {Number} y y coordinate - * @param {Number} tolerance Tolerance - */ - isTransparent(ctx: CanvasRenderingContext2D, x: number, y: number, tolerance: number): boolean; -} - - -interface Util extends IUtilAnimation, IUtilArc, IObservable, IUtilDomEvent, IUtilDomMisc, - IUtilDomRequest, IUtilDomStyle, IUtilClass, IUtilMisc { - ease: IUtilAnimEase; - array: IUtilArray; - object: IUtilObject; - string: IUtilString; -} + interface IBlendFilter extends IBaseFilter { + /** + * Applies filter to canvas element + * @param {Object} canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; + } + interface IBrightnessFilter extends IBaseFilter { + /** + * Applies filter to canvas element + * @param {Object} canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; + } + interface IConvoluteFilter extends IBaseFilter { + /** + * Applies filter to canvas element + * @param {Object} canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; + } + interface IGradientTransparencyFilter { + /** + * Applies filter to canvas element + * @param {Object} canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; + } + interface IGrayscaleFilter { + /** + * Applies filter to canvas element + * @param {Object} canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; + } + interface IInvertFilter { + /** + * Applies filter to canvas element + * @param {Object} canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; + } + interface IMaskFilter { + /** + * Applies filter to canvas element + * @param {Object} canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; + } + interface IMultiplyFilter { + /** + * Applies filter to canvas element + * @param {Object} canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; + } + interface INoiseFilter { + /** + * Applies filter to canvas element + * @param {Object} canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; + } + interface IPixelateFilter { + /** + * Applies filter to canvas element + * @param {Object} canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; + } + interface IRemoveWhiteFilter { + /** + * Applies filter to canvas element + * @param {Object} canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; + } + interface IResizeFilter { + /** + * Resize type + */ + resizeType: string; + + /** + * Scale factor for resizing, x axis + */ + scaleX: number; + + /** + * Scale factor for resizing, y axis + */ + scaleY: number; + + /** + * LanczosLobes parameter for lanczos filter + */ + lanczosLobes: number; + /** + * Applies filter to canvas element + * @param {Object} canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; + } + interface ISepiaFilter { + /** + * Applies filter to canvas element + * @param {Object} canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; + } + interface ISepia2Filter { + /** + * Applies filter to canvas element + * @param {Object} canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; + } + interface ITintFilter { + /** + * Applies filter to canvas element + * @param {Object} canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; + } + + //////////////////////////////////////////////////////////// + // Brushes + //////////////////////////////////////////////////////////// + interface IBaseBrush { + /** + * Color of a brush + */ + color: string; + + /** + * Width of a brush + */ + width: number; + + /** + * Shadow object representing shadow of this shape. + * Backwards incompatibility note: This property replaces "shadowColor" (String), "shadowOffsetX" (Number), + * "shadowOffsetY" (Number) and "shadowBlur" (Number) since v1.2.12 + */ + shadow: IShadow|string; + /** + * Line endings style of a brush (one of "butt", "round", "square") + */ + strokeLineCap: string; + + /** + * Corner style of a brush (one of "bevil", "round", "miter") + */ + strokeLineJoin: string; + + /** + * Stroke Dash Array. + */ + strokeDashArray: any[]; + + /** + * Sets shadow of an object + * @param {Object|String} [options] Options object or string (e.g. "2px 2px 10px rgba(0,0,0,0.2)") + */ + setShadow(options: string|any): IBaseBrush; + + } + interface ICircleBrush extends IBaseBrush { + /** + * Width of a brush + */ + width: number; + /** + * Invoked inside on mouse down and mouse move + * @param {Object} pointer + */ + drawDot(pointer: any): void; + + /** + * @param {Object} pointer + * @return {fabric.Point} Just added pointer point + */ + addPoint(pointer: any): IPoint + } + interface ISprayBrush extends IBaseBrush { + /** + * Width of a brush + */ + width: number; + /** + * Density of a spray (number of dots per chunk) + */ + density: number; + + /** + * Width of spray dots + */ + dotWidth: number; + /** + * Width variance of spray dots + */ + dotWidthVariance: number; + + /** + * Whether opacity of a dot should be random + */ + randomOpacity: boolean; + /** + * Whether overlapping dots (rectangles) should be removed (for performance reasons) + */ + optimizeOverlapping: boolean; + /** + * @param {Object} pointer + */ + addSprayChunk(pointer: any): void + } + interface IPatternBrush extends IPencilBrush { + getPatternSrc(): HTMLCanvasElement; + + getPatternSrcFunction(): string; + + /** + * Creates "pattern" instance property + */ + getPattern(): any; + /** + * Creates path + */ + createPath(pathData: string): IPath; + } + interface IPencilBrush extends IBaseBrush { + /** + * Converts points to SVG path + * @param {Array} points Array of points + * @param {Number} minX + * @param {Number} minY + */ + convertPointsToSVGPath(points: { x: number; y: number }[], minX?: number, minY?: number): string[]; + + /** + * Creates fabric.Path object to add on canvas + * @param {String} pathData Path data + */ + createPath(pathData: string): IPath; + } + var BaseBrush: { + new (): IBaseBrush + }; + var CircleBrush: { + new (canvas: fabric.ICanvas): ICircle + }; + var SprayBrush: { + new (canvas: fabric.ICanvas): ISprayBrush + }; + var PencilBrush: { + new (canvas: fabric.ICanvas): IPencilBrush + }; + var PatternBrush: { + new (canvas: fabric.ICanvas): IPatternBrush + }; + /////////////////////////////////////////////////////////////////////////////// + // Fabric util Interface + ////////////////////////////////////////////////////////////////////////////// + interface IUtilAnimationOptions { + /** + * Starting value + */ + startValue?: number; + /** + * Ending value + */ + endValue?: number; + /** + * Value to modify the property by + */ + byValue: number; + /** + * Duration of change (in ms) + */ + duration?: number; + /** + * Callback; invoked on every value change + */ + onChange?: Function; + /** + * Callback; invoked when value change is completed + */ + onComplete?: Function; + /** + * Easing function + */ + easing?: Function; + } + interface IUtilAnimation { + /** + * Changes value from one to another within certain period of time, invoking callbacks as value is being changed. + * @param {Object} [options] Animation options + */ + animate(options?: IUtilAnimationOptions): void; + /** + * requestAnimationFrame polyfill based on http://paulirish.com/2011/requestanimationframe-for-smart-animating/ + * In order to get a precise start time, `requestAnimFrame` should be called as an entry into the method + * @param {Function} callback Callback to invoke + */ + requestAnimFrame(callback: Function): void; + } + + interface IUtilAnimEase { + easeInBack(): Function; + easeInBounce(): Function; + easeInCirc(): Function; + easeInCubic(): Function; + easeInElastic(): Function; + easeInExpo(): Function; + easeInOutBack(): Function; + easeInOutBounce(): Function; + easeInOutCirc(): Function; + easeInOutCubic(): Function; + easeInOutElastic(): Function; + easeInOutExpo(): Function; + easeInOutQuad(): Function; + easeInOutQuart(): Function; + easeInOutQuint(): Function; + easeInOutSine(): Function; + easeInQuad(): Function; + easeInQuart(): Function; + easeInQuint(): Function; + easeInSine(): Function; + easeOutBack(): Function; + easeOutBounce(): Function; + easeOutCirc(): Function; + easeOutCubic(): Function; + easeOutElastic(): Function; + easeOutExpo(): Function; + easeOutQuad(): Function; + easeOutQuart(): Function; + easeOutQuint(): Function; + easeOutSine(): Function; + } + + interface IUtilArc { + /** + * Draws arc + * @param {CanvasRenderingContext2D} ctx + * @param {Number} fx + * @param {Number} fy + * @param {Array} coords + */ + drawArc(ctx: CanvasRenderingContext2D, fx: number, fy: number, coords: number[]): void; + /** + * Calculate bounding box of a elliptic-arc + * @param {Number} fx start point of arc + * @param {Number} fy + * @param {Number} rx horizontal radius + * @param {Number} ry vertical radius + * @param {Number} rot angle of horizontal axe + * @param {Number} large 1 or 0, whatever the arc is the big or the small on the 2 points + * @param {Number} sweep 1 or 0, 1 clockwise or counterclockwise direction + * @param {Number} tx end point of arc + * @param {Number} ty + */ + getBoundsOfArc(fx: number, fy: number, rx: number, ry: number, rot: number, large: number, sweep: number, tx: number, ty: number): IPoint[]; + /** + * Calculate bounding box of a beziercurve + * @param {Number} x0 starting point + * @param {Number} y0 + * @param {Number} x1 first control point + * @param {Number} y1 + * @param {Number} x2 secondo control point + * @param {Number} y2 + * @param {Number} x3 end of beizer + * @param {Number} y3 + */ + getBoundsOfCurve(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, x3: number, y3: number): IPoint[]; + + } + + interface IUtilDomEvent { + /** + * Cross-browser wrapper for getting event's coordinates + * @param {Event} event Event object + * @param {HTMLCanvasElement} upperCanvasEl <canvas> element on which object selection is drawn + */ + getPointer(event: Event, upperCanvasEl: HTMLCanvasElement): IPoint; + + /** + * Adds an event listener to an element + * @param {HTMLElement} element + * @param {String} eventName + * @param {Function} handler + */ + addListener(element: HTMLElement, eventName: string, handler: Function): void; + + /** + * Removes an event listener from an element + * @param {HTMLElement} element + * @param {String} eventName + * @param {Function} handler + */ + removeListener(element: HTMLElement, eventName: string, handler: Function): void; + } + + interface IUtilDomMisc { + /** + * Takes id and returns an element with that id (if one exists in a document) + * @param {String|HTMLElement} id + */ + getById(id: string|HTMLElement): HTMLElement; + /** + * Converts an array-like object (e.g. arguments or NodeList) to an array + * @param {Object} arrayLike + */ + toArray(arrayLike: any): any[]; + /** + * Creates specified element with specified attributes + * @memberOf fabric.util + * @param {String} tagName Type of an element to create + * @param {Object} [attributes] Attributes to set on an element + * @return {HTMLElement} Newly created element + */ + makeElement(tagName: string, attributes?: any): HTMLElement; + /** + * Adds class to an element + * @param {HTMLElement} element Element to add class to + * @param {String} className Class to add to an element + */ + addClass(element: HTMLElement, classname: string): void; + /** + * Wraps element with another element + * @param {HTMLElement} element Element to wrap + * @param {HTMLElement|String} wrapper Element to wrap with + * @param {Object} [attributes] Attributes to set on a wrapper + */ + wrapElement(element: HTMLElement, wrapper: HTMLElement|string, attributes?: any): HTMLElement; + /** + * Returns element scroll offsets + * @param {HTMLElement} element Element to operate on + * @param {HTMLElement} upperCanvasEl Upper canvas element + */ + getScrollLeftTop(element: HTMLElement, upperCanvasEl: HTMLElement): { left: number; right: number; }; + /** + * Returns offset for a given element + * @param {HTMLElement} element Element to get offset for + */ + getElementOffset(element: HTMLElement): { left: number; right: number; }; + /** + * Returns style attribute value of a given element + * @param {HTMLElement} element Element to get style attribute for + * @param {String} attr Style attribute to get for element + */ + getElementStyle(elment: HTMLElement, attr: string): string; + /** + * Inserts a script element with a given url into a document; invokes callback, when that script is finished loading + * @memberOf fabric.util + * @param {String} url URL of a script to load + * @param {Function} callback Callback to execute when script is finished loading + */ + getScript(url: string, callback: Function): void; + /** + * Makes element unselectable + * @param {HTMLElement} element Element to make unselectable + */ + makeElementUnselectable(element: HTMLElement): HTMLElement; + /** + * Makes element selectable + * @param {HTMLElement} element Element to make selectable + */ + makeElementSelectable(element: HTMLElement): HTMLElement; + } + + interface IUtilDomRequest { + /** + * Cross-browser abstraction for sending XMLHttpRequest + * @param {String} url URL to send XMLHttpRequest to + * @param {Object} [options] Options object + * @param {String} [options.method="GET"] + * @param {Function} options.onComplete Callback to invoke when request is completed + */ + request(url: string, options?: { method?: string; onComplete: Function }): XMLHttpRequest; + } + + interface IUtilDomStyle { + /** + * Cross-browser wrapper for setting element's style + * @param {HTMLElement} element + * @param {Object} styles + */ + setStyle(element: HTMLElement, styles: any): HTMLElement; + } + + interface IUtilArray { + /** + * Invokes method on all items in a given array + * @param {Array} array Array to iterate over + * @param {String} method Name of a method to invoke + */ + invoke(array: any[], method: string): any[]; + /** + * Finds minimum value in array (not necessarily "first" one) + * @param {Array} array Array to iterate over + * @param {String} byProperty + */ + min(array: any[], byProperty: string): any; + /** + * Finds maximum value in array (not necessarily "first" one) + * @param {Array} array Array to iterate over + * @param {String} byProperty + */ + max(array: any[], byProperty: string): any; + } + + interface IUtilClass { + /** + * Helper for creation of "classes". + * @param {Function} [parent] optional "Class" to inherit from + * @param {Object} [properties] Properties shared by all instances of this class + * (be careful modifying objects defined here as this would affect all instances) + */ + createClass(parent: Function, properties?: any); + /** + * Helper for creation of "classes". + * @param {Object} [properties] Properties shared by all instances of this class + * (be careful modifying objects defined here as this would affect all instances) + */ + createClass(properties?: any); + + } + + interface IUtilObject { + /** + * Copies all enumerable properties of one object to another + * @param {Object} destination Where to copy to + * @param {Object} source Where to copy from + */ + extend(destination: any, source: any): any; + + /** + * Creates an empty object and copies all enumerable properties of another object to it + * @memberOf fabric.util.object + * @param {Object} object Object to clone + * @return {Object} + */ + clone(object: any): any + } + + interface IUtilString { + /** + * Camelizes a string + * @param {String} string String to camelize + */ + camelize(string: string): string; + + /** + * Capitalizes a string + * @param {String} string String to capitalize + * @param {Boolean} [firstLetterOnly] If true only first letter is capitalized + * and other letters stay untouched, if false first letter is capitalized + * and other letters are converted to lowercase. + */ + capitalize(string: string, firstLetterOnly: boolean): string; + + /** + * Escapes XML in a string + * @param {String} string String to escape + */ + escapeXml(string: string): string; + } + + interface IUtilMisc { + /** + * Removes value from an array. + * Presence of value (and its position in an array) is determined via `Array.prototype.indexOf` + * @param {Array} array + * @param {Any} value + */ + removeFromArray(array: any[], value: any): any[]; + + /** + * Returns random number between 2 specified ones. + * @param {Number} min lower limit + * @param {Number} max upper limit + */ + getRandomInt(min: number, max: number): number; + + /** + * Transforms degrees to radians. + * @param {Number} degrees value in degrees + */ + degreesToRadians(degrees: number): number; + + /** + * Transforms radians to degrees. + * @memberOf fabric.util + * @param {Number} radians value in radians + */ + radiansToDegrees(radians: number): number; + + /** + * Rotates `point` around `origin` with `radians` + * @param {fabric.Point} point The point to rotate + * @param {fabric.Point} origin The origin of the rotation + * @param {Number} radians The radians of the angle for the rotation + */ + rotatePoint(point: IPoint, origin: IPoint, radians: number): IPoint; + + /** + * Apply transform t to point p + * @param {fabric.Point} p The point to transform + * @param {Array} t The transform + * @param {Boolean} [ignoreOffset] Indicates that the offset should not be applied + */ + transformPoint(p: IPoint, t: any[], ignoreOffset?: boolean): IPoint; + + /** + * Invert transformation t + * @param {Array} t The transform + */ + invertTransform(t: any[]): any[]; + + /** + * A wrapper around Number#toFixed, which contrary to native method returns number, not string. + * @param {Number|String} number number to operate on + * @param {Number} fractionDigits number of fraction digits to "leave" + */ + toFixed(number: number, fractionDigits: number): number; + + /** + * Converts from attribute value to pixel value if applicable. + * Returns converted pixels or original value not converted. + * @param {Number|String} value number to operate on + */ + parseUnit(value: number|string, fontSize?: number): number|string; + + /** + * Function which always returns `false`. + */ + falseFunction(): boolean; + + /** + * Returns klass "Class" object of given namespace + * @param {String} type Type of object (eg. 'circle') + * @param {String} namespace Namespace to get klass "Class" object from + */ + getKlass(type: string, namespace: string): any; + + /** + * Returns object of given namespace + * @param {String} namespace Namespace string e.g. 'fabric.Image.filter' or 'fabric' + */ + resolveNamespace(namespace: string): any; + + /** + * Loads image element from given url and passes it to a callback + * @param {String} url URL representing an image + * @param {Function} callback Callback; invoked with loaded image + * @param {Any} [context] Context to invoke callback in + * @param {Object} [crossOrigin] crossOrigin value to set image element to + */ + loadImage(url: string, callback: (image: HTMLImageElement) => {}, context?: any, crossOrigin?: boolean): void; + + /** + * Creates corresponding fabric instances from their object representations + * @param {Array} objects Objects to enliven + * @param {Function} callback Callback to invoke when all objects are created + * @param {String} namespace Namespace to get klass "Class" object from + * @param {Function} reviver Method for further parsing of object elements, called after each fabric object created. + */ + enlivenObjects(objects: any[], callback: Function, namespace: string, reviver?: Function): void; + + /** + * Groups SVG elements (usually those retrieved from SVG document) + * @param {Array} elements SVG elements to group + * @param {Object} [options] Options object + */ + groupSVGElements(elements: any[], options?: any, path?: any): IPathGroup; + + /** + * Populates an object with properties of another object + * @param {Object} source Source object + * @param {Object} destination Destination object + * @param {Array} properties Propertie names to include + */ + populateWithProperties(source: any, destination: any, properties: any): void; + + /** + * Draws a dashed line between two points + * This method is used to draw dashed line around selection area. + * @param {CanvasRenderingContext2D} ctx context + * @param {Number} x start x coordinate + * @param {Number} y start y coordinate + * @param {Number} x2 end x coordinate + * @param {Number} y2 end y coordinate + * @param {Array} da dash array pattern + */ + drawDashedLine(ctx: CanvasRenderingContext2D, x: number, y: number, x2: number, y2: number, da: any[]): void; + + /** + * Creates canvas element and initializes it via excanvas if necessary + * @param {CanvasElement} [canvasEl] optional canvas element to initialize; + * when not given, element is created implicitly + */ + createCanvasElement(canvasEl?: HTMLCanvasElement): HTMLCanvasElement; + + /** + * Creates image element (works on client and node) + */ + createImage(): HTMLImageElement; + + /** + * Creates accessors (getXXX, setXXX) for a "class", based on "stateProperties" array + * @param {Object} klass "Class" to create accessors for + */ + createAccessors(klass: any): any; + + /** + * @param {fabric.Object} receiver Object implementing `clipTo` method + * @param {CanvasRenderingContext2D} ctx Context to clip + */ + clipContext(receiver: IObject, ctx: CanvasRenderingContext2D): void; + + /** + * Multiply matrix A by matrix B to nest transformations + * @param {Array} a First transformMatrix + * @param {Array} b Second transformMatrix + */ + multiplyTransformMatrices(a: any[], b: any[]): any[]; + + /** + * Returns string representation of function body + * @param {Function} fn Function to get body of + */ + getFunctionBody(fn: Function): string; + + /** + * Returns true if context has transparent pixel + * at specified location (taking tolerance into account) + * @param {CanvasRenderingContext2D} ctx context + * @param {Number} x x coordinate + * @param {Number} y y coordinate + * @param {Number} tolerance Tolerance + */ + isTransparent(ctx: CanvasRenderingContext2D, x: number, y: number, tolerance: number): boolean; + } + + interface IUtil extends IUtilAnimation, IUtilArc, IObservable, IUtilDomEvent, IUtilDomMisc, + IUtilDomRequest, IUtilDomStyle, IUtilClass, IUtilMisc { + ease: IUtilAnimEase; + array: IUtilArray; + object: IUtilObject; + string: IUtilString; + } }