@axceta/angular-editor-fabric-js
Version:
> Drag-and-drop editor based on Fabricjs for Angular with multiple options
691 lines (684 loc) • 26.1 kB
JavaScript
import { fabric } from 'fabric';
import { __decorate } from 'tslib';
import { EventEmitter, ViewChild, Output, Component, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { ColorPickerModule } from 'ngx-color-picker';
var CanvasManager = /** @class */ (function () {
function CanvasManager() {
}
/**
* Create and return a fabric canvas item.
* @param element Name, selector or reference to a HTML canvas element (such Angular's ElementRef)
* @param options Standard options for the canvas element
*/
CanvasManager.createCanvas = function (element, options) {
return new fabric.Canvas(element, options);
};
/**
* Create and return a fabric canvas item that DOES NOT have interactivity
* @param element Name, selector or reference to a HTML canvas element (such Angular's ElementRef)
* @param options Standard options for the canvas element
*/
CanvasManager.createStaticCanvas = function (element, options) {
return new fabric.StaticCanvas(element, options);
};
return CanvasManager;
}());
var DEFAULT_CANVAS_WIDTH = 500;
var FabricjsEditorComponent = /** @class */ (function () {
function FabricjsEditorComponent() {
this.moving = new EventEmitter();
this.modified = new EventEmitter();
this.selection = new EventEmitter();
this.cleared = new EventEmitter();
this.props = {
canvasFill: '#ffffff',
canvasImage: '',
id: null,
opacity: null,
fill: null,
fontSize: null,
lineHeight: null,
charSpacing: null,
fontWeight: null,
fontStyle: null,
textAlign: null,
fontFamily: null,
TextDecoration: ''
};
this.url = '';
this.size = {
width: DEFAULT_CANVAS_WIDTH,
height: 800
};
this.textEditor = false;
this.figureEditor = false;
}
FabricjsEditorComponent.prototype.ngAfterViewInit = function () {
var _this = this;
// setup front side canvas
this.canvas = new fabric.Canvas(this.htmlCanvas.nativeElement, {
hoverCursor: 'pointer',
selection: true,
selectionBorderColor: 'blue'
});
this.canvas.on({
'object:moving': function (e) { _this.moving.emit(e); },
'object:modified': function (e) { _this.modified.emit(e); },
'object:selected': function (e) {
_this.selection.emit(e);
var selectedObject = e.target;
_this.selected = selectedObject;
selectedObject.hasRotatingPoint = true;
selectedObject.transparentCorners = false;
selectedObject.cornerColor = 'rgba(255, 87, 34, 0.7)';
_this.resetPanels();
if (selectedObject.type !== 'group' && selectedObject) {
_this.getOpacity();
switch (selectedObject.type) {
case 'rect':
case 'circle':
case 'triangle':
_this.figureEditor = true;
_this.getFill();
break;
case 'i-text':
_this.textEditor = true;
_this.getLineHeight();
_this.getCharSpacing();
_this.getBold();
_this.getFill();
_this.getTextDecoration();
_this.getTextAlign();
_this.getFontFamily();
break;
case 'image':
break;
}
}
},
'selection:cleared': function (e) {
_this.cleared.emit(e);
_this.selected = null;
_this.resetPanels();
}
});
this.canvas.setWidth(this.size.width);
this.canvas.setHeight(this.size.height);
};
/*------------------------Block elements------------------------*/
/**
* Subscribe to a FabricJS event. You can find the list of available events here: http://fabricjs.com/docs/fabric.Canvas.html
* @param eventName The event name to listen to
*/
FabricjsEditorComponent.prototype.onEvent = function (eventName, callback) {
var _a;
this.canvas.on((_a = {}, _a[eventName] = callback, _a));
};
// Block "Size"
FabricjsEditorComponent.prototype.changeSize = function () {
this.canvas.setWidth(this.size.width);
this.canvas.setHeight(this.size.height);
};
// Block "Add text"
FabricjsEditorComponent.prototype.addText = function () {
if (this.textString) {
var text = new fabric.IText(this.textString, {
left: 10,
top: 10,
fontFamily: 'helvetica',
angle: 0,
fill: '#000000',
scaleX: 0.5,
scaleY: 0.5,
fontWeight: '',
hasRotatingPoint: true
});
this.extend(text, this.randomId());
this.canvas.add(text);
this.selectItemAfterAdded(text);
this.textString = '';
}
};
// Block "Add images"
FabricjsEditorComponent.prototype.getImgPolaroid = function (event) {
var _this = this;
var el = event.target;
fabric.loadSVGFromURL(el.src, function (objects, options) {
var image = fabric.util.groupSVGElements(objects, options);
image.set({
left: 10,
top: 10,
angle: 0,
padding: 10,
cornerSize: 10,
hasRotatingPoint: true,
});
_this.extend(image, _this.randomId());
_this.canvas.add(image);
_this.selectItemAfterAdded(image);
});
};
// Block "Upload Image"
FabricjsEditorComponent.prototype.addImageOnCanvas = function (url) {
var _this = this;
if (url) {
fabric.Image.fromURL(url, function (image) {
image.set({
left: 10,
top: 10,
angle: 0,
padding: 10,
cornerSize: 10,
hasRotatingPoint: true
});
image.scaleToWidth(200);
image.scaleToHeight(200);
_this.extend(image, _this.randomId());
_this.canvas.add(image);
_this.selectItemAfterAdded(image);
});
}
};
FabricjsEditorComponent.prototype.readUrl = function (event) {
var _this = this;
if (event.target.files && event.target.files[0]) {
var reader = new FileReader();
reader.onload = function (readerEvent) {
_this.url = readerEvent.target.result;
};
reader.readAsDataURL(event.target.files[0]);
}
};
FabricjsEditorComponent.prototype.removeWhite = function (url) {
this.url = '';
};
// Block "Add figure"
/**
* Add a figure to the canvas following the definition you provide.
* If you passed a string to this function, please rename your implementation for addPredefinedFigure().
* @param figure Your custom figure definition
* @param id (Optional) The unique id you want to give to the figure. If no ID is specified a random one will be picked.
* @returns The ID of the created figure
*/
FabricjsEditorComponent.prototype.addFigure = function (figure, id) {
var figureId = id || this.randomId();
this.extend(figure, figureId);
this.canvas.add(figure);
this.selectItemAfterAdded(figure);
return figureId;
};
/**
* Add a predefined figure to the canvas. If you want to create a custom figure, please use addFigure().
* @param figure The name of the predefined figure. Can be one of the following: 'rectangle', 'square', 'triangle', 'circle'.
* @param id (Optional) The unique id you want to give to the figure. If no ID is specified a random one will be picked.
* @returns The ID of the created figure
* TODO: Move to app.component
*/
FabricjsEditorComponent.prototype.addPredefinedFigure = function (figure, id) {
var add;
var figureId = id || this.randomId();
switch (figure) {
case 'rectangle':
add = new fabric.Rect({
width: 200, height: 100, left: 10, top: 10, angle: 0,
fill: '#3f51b5'
});
break;
case 'square':
add = new fabric.Rect({
width: 100, height: 100, left: 10, top: 10, angle: 0,
fill: '#4caf50'
});
break;
case 'triangle':
add = new fabric.Triangle({
width: 100, height: 100, left: 10, top: 10, fill: '#2196f3'
});
break;
case 'circle':
add = new fabric.Circle({
radius: 50, left: 10, top: 10, fill: '#ff5722'
});
break;
}
return this.addFigure(add, figureId);
};
// TODO: Add copies of this for triangle and circle
// TODO: Add JSdoc
FabricjsEditorComponent.prototype.addRect = function (options, id) {
var figure = new fabric.Rect(options);
if (id) {
figure = Object.assign(figure, { data: { id: id } });
}
return this.addFigure(figure, id);
};
/*Canvas*/
FabricjsEditorComponent.prototype.cleanSelect = function () {
this.canvas.discardActiveObject();
};
FabricjsEditorComponent.prototype.selectItemAfterAdded = function (obj) {
this.canvas.discardActiveObject();
this.canvas.setActiveObject(obj);
};
FabricjsEditorComponent.prototype.setCanvasFill = function () {
if (!this.props.canvasImage) {
this.canvas.backgroundColor = this.props.canvasFill;
this.canvas.renderAll();
}
};
FabricjsEditorComponent.prototype.extend = function (obj, id) {
obj.toObject = (function (toObject) {
return function () {
return fabric.util.object.extend(toObject.call(this), {
id: id
});
};
})(obj.toObject);
};
FabricjsEditorComponent.prototype.setCanvasImage = function () {
var self = this;
if (this.props.canvasImage) {
this.canvas.setBackgroundColor(new fabric.Pattern({ source: this.props.canvasImage, repeat: 'repeat' }), function () {
self.props.canvasFill = '';
self.canvas.renderAll();
});
}
};
FabricjsEditorComponent.prototype.randomId = function () {
return Math.floor(Math.random() * 999999) + 1;
};
/*------------------------Global actions for element------------------------*/
FabricjsEditorComponent.prototype.getActiveStyle = function (styleName, object) {
object = object || this.canvas.getActiveObject();
if (!object) {
return '';
}
if (object.getSelectionStyles && object.isEditing) {
return (object.getSelectionStyles()[styleName] || '');
}
else {
return (object[styleName] || '');
}
};
FabricjsEditorComponent.prototype.setActiveStyle = function (styleName, value, object) {
object = object || this.canvas.getActiveObject();
if (!object) {
return;
}
if (object.setSelectionStyles && object.isEditing) {
var style = {};
style[styleName] = value;
if (typeof value === 'string') {
if (value.includes('underline')) {
object.setSelectionStyles({ underline: true });
}
else {
object.setSelectionStyles({ underline: false });
}
if (value.includes('overline')) {
object.setSelectionStyles({ overline: true });
}
else {
object.setSelectionStyles({ overline: false });
}
if (value.includes('line-through')) {
object.setSelectionStyles({ linethrough: true });
}
else {
object.setSelectionStyles({ linethrough: false });
}
}
object.setSelectionStyles(style);
object.setCoords();
}
else {
if (typeof value === 'string') {
if (value.includes('underline')) {
object.set('underline', true);
}
else {
object.set('underline', false);
}
if (value.includes('overline')) {
object.set('overline', true);
}
else {
object.set('overline', false);
}
if (value.includes('line-through')) {
object.set('linethrough', true);
}
else {
object.set('linethrough', false);
}
}
object.set(styleName, value);
}
object.setCoords();
this.canvas.renderAll();
};
FabricjsEditorComponent.prototype.getActiveProp = function (name) {
var object = this.canvas.getActiveObject();
if (!object) {
return '';
}
return object[name] || '';
};
FabricjsEditorComponent.prototype.setActiveProp = function (name, value) {
var object = this.canvas.getActiveObject();
if (!object) {
return;
}
object.set(name, value).setCoords();
this.canvas.renderAll();
};
FabricjsEditorComponent.prototype.clone = function () {
var activeObject = this.canvas.getActiveObject();
var activeGroup = this.canvas.getActiveObjects();
if (activeObject) {
var clone = void 0;
switch (activeObject.type) {
case 'rect':
clone = new fabric.Rect(activeObject.toObject());
break;
case 'circle':
clone = new fabric.Circle(activeObject.toObject());
break;
case 'triangle':
clone = new fabric.Triangle(activeObject.toObject());
break;
case 'i-text':
clone = new fabric.IText('', activeObject.toObject());
break;
case 'image':
clone = fabric.util.object.clone(activeObject);
break;
}
if (clone) {
clone.set({ left: 10, top: 10 });
this.canvas.add(clone);
this.selectItemAfterAdded(clone);
}
}
};
/**
* @deprecated Was renamed for getidOfSelectedObject
*/
FabricjsEditorComponent.prototype.getId = function () {
return this.getIdOfSelectedObject();
};
/**
* Returns the id of the currently selected object
* @return Object ID
*/
FabricjsEditorComponent.prototype.getIdOfSelectedObject = function () {
this.props.id = this.canvas.getActiveObject().toObject().id;
return this.props.id;
};
/**
* @deprecated Was renamed for setIdOfSelectedObject
*/
FabricjsEditorComponent.prototype.setId = function () {
this.setIdOfSelectedObject();
};
FabricjsEditorComponent.prototype.setIdOfSelectedObject = function () {
var val = this.props.id;
var complete = this.canvas.getActiveObject().toObject();
// FIXME: This is bad, it overrides the toObject() method. If something else modifies the object it wont be picked up.
this.canvas.getActiveObject().toObject = function () {
complete.id = val;
return complete;
};
};
/**
* Loops through all canvas objects and find one matching the supplied ID.
* @param id The ID to look for
*/
FabricjsEditorComponent.prototype.getObjectWithID = function (id) {
var foundObject;
this.canvas.getObjects().forEach(function (item) {
if (item.id === id) {
foundObject = item;
}
});
return foundObject;
};
FabricjsEditorComponent.prototype.getOpacity = function () {
this.props.opacity = this.getActiveStyle('opacity', null) * 100;
};
FabricjsEditorComponent.prototype.setOpacity = function () {
this.setActiveStyle('opacity', parseInt(this.props.opacity, 10) / 100, null);
};
FabricjsEditorComponent.prototype.getFill = function () {
this.props.fill = this.getActiveStyle('fill', null);
};
FabricjsEditorComponent.prototype.setFill = function () {
this.setActiveStyle('fill', this.props.fill, null);
};
FabricjsEditorComponent.prototype.getLineHeight = function () {
this.props.lineHeight = this.getActiveStyle('lineHeight', null);
};
FabricjsEditorComponent.prototype.setLineHeight = function () {
this.setActiveStyle('lineHeight', parseFloat(this.props.lineHeight), null);
};
FabricjsEditorComponent.prototype.getCharSpacing = function () {
this.props.charSpacing = this.getActiveStyle('charSpacing', null);
};
FabricjsEditorComponent.prototype.setCharSpacing = function () {
this.setActiveStyle('charSpacing', this.props.charSpacing, null);
};
FabricjsEditorComponent.prototype.getFontSize = function () {
this.props.fontSize = this.getActiveStyle('fontSize', null);
};
FabricjsEditorComponent.prototype.setFontSize = function () {
this.setActiveStyle('fontSize', parseInt(this.props.fontSize, 10), null);
};
FabricjsEditorComponent.prototype.getBold = function () {
this.props.fontWeight = this.getActiveStyle('fontWeight', null);
};
FabricjsEditorComponent.prototype.setBold = function () {
this.props.fontWeight = !this.props.fontWeight;
this.setActiveStyle('fontWeight', this.props.fontWeight ? 'bold' : '', null);
};
FabricjsEditorComponent.prototype.setFontStyle = function () {
this.props.fontStyle = !this.props.fontStyle;
if (this.props.fontStyle) {
this.setActiveStyle('fontStyle', 'italic', null);
}
else {
this.setActiveStyle('fontStyle', 'normal', null);
}
};
FabricjsEditorComponent.prototype.getTextDecoration = function () {
this.props.TextDecoration = this.getActiveStyle('textDecoration', null);
};
FabricjsEditorComponent.prototype.setTextDecoration = function (value) {
var iclass = this.props.TextDecoration;
if (iclass.includes(value)) {
iclass = iclass.replace(RegExp(value, 'g'), '');
}
else {
iclass += " " + value;
}
this.props.TextDecoration = iclass;
this.setActiveStyle('textDecoration', this.props.TextDecoration, null);
};
FabricjsEditorComponent.prototype.hasTextDecoration = function (value) {
return this.props.TextDecoration.includes(value);
};
FabricjsEditorComponent.prototype.getTextAlign = function () {
this.props.textAlign = this.getActiveProp('textAlign');
};
FabricjsEditorComponent.prototype.setTextAlign = function (value) {
this.props.textAlign = value;
this.setActiveProp('textAlign', this.props.textAlign);
};
FabricjsEditorComponent.prototype.getFontFamily = function () {
this.props.fontFamily = this.getActiveProp('fontFamily');
};
FabricjsEditorComponent.prototype.setFontFamily = function () {
this.setActiveProp('fontFamily', this.props.fontFamily);
};
/*System*/
FabricjsEditorComponent.prototype.removeSelected = function () {
var activeObject = this.canvas.getActiveObject();
var activeGroup = this.canvas.getActiveObjects();
if (activeObject) {
this.canvas.remove(activeObject);
// this.textString = '';
}
else if (activeGroup) {
this.canvas.discardActiveObject();
var self_1 = this;
activeGroup.forEach(function (object) {
self_1.canvas.remove(object);
});
}
};
FabricjsEditorComponent.prototype.bringToFront = function () {
var activeObject = this.canvas.getActiveObject();
var activeGroup = this.canvas.getActiveObjects();
if (activeObject) {
activeObject.bringToFront();
activeObject.opacity = 1;
}
else if (activeGroup) {
this.canvas.discardActiveObject();
activeGroup.forEach(function (object) {
object.bringToFront();
});
}
};
FabricjsEditorComponent.prototype.sendToBack = function () {
var activeObject = this.canvas.getActiveObject();
var activeGroup = this.canvas.getActiveObjects();
if (activeObject) {
this.canvas.sendToBack(activeObject);
activeObject.sendToBack();
activeObject.opacity = 1;
}
else if (activeGroup) {
this.canvas.discardActiveObject();
activeGroup.forEach(function (object) {
object.sendToBack();
});
}
};
/**
* Show a confirmation to tu user before clearing the canvas.
*/
FabricjsEditorComponent.prototype.confirmClear = function () {
if (confirm('Are you sure?')) {
this.clear();
}
};
/**
* Clear the canvas.
*/
FabricjsEditorComponent.prototype.clear = function () {
this.canvas.clear();
};
/**
* @
*/
FabricjsEditorComponent.prototype.rasterize = function () {
var image = new Image();
image.src = this.canvas.toDataURL({ format: 'png' });
var w = window.open('');
w.document.write(image.outerHTML);
};
FabricjsEditorComponent.prototype.rasterizeSVG = function () {
var w = window.open('');
w.document.write(this.canvas.toSVG());
return 'data:image/svg+xml;utf8,' + encodeURIComponent(this.canvas.toSVG());
};
FabricjsEditorComponent.prototype.saveCanvasToJSON = function () {
var json = JSON.stringify(this.canvas);
localStorage.setItem('Kanvas', json);
console.log('json');
console.log(json);
};
FabricjsEditorComponent.prototype.importCanvasFromLocalStorage = function () {
this.loadCanvas(localStorage.getItem('Kanvas'));
};
FabricjsEditorComponent.prototype.importCanvasFromJson = function (json) {
this.loadCanvas(json);
};
FabricjsEditorComponent.prototype.importFromObject = function (object) {
this.loadCanvas(object);
};
FabricjsEditorComponent.prototype.loadCanvas = function (canvasData) {
var _this = this;
this.canvas.loadFromJSON(canvasData, function () {
_this.canvas.renderAll();
});
};
/**
* @deprecated Use importCanvasFromLocalStorage() instead.
*/
FabricjsEditorComponent.prototype.loadCanvasFromJSON = function () {
this.importCanvasFromLocalStorage();
};
/**
* Get the full canvas data as a Javascript object
*/
FabricjsEditorComponent.prototype.getCanvasData = function (propertiesToInclude) {
return this.canvas.toObject(propertiesToInclude);
};
FabricjsEditorComponent.prototype.rasterizeJSON = function () {
this.json = JSON.stringify(this.canvas, null, 2);
};
FabricjsEditorComponent.prototype.resetPanels = function () {
this.textEditor = false;
this.figureEditor = false;
};
__decorate([
ViewChild('htmlCanvas')
], FabricjsEditorComponent.prototype, "htmlCanvas", void 0);
__decorate([
Output()
], FabricjsEditorComponent.prototype, "moving", void 0);
__decorate([
Output()
], FabricjsEditorComponent.prototype, "modified", void 0);
__decorate([
Output()
], FabricjsEditorComponent.prototype, "selection", void 0);
__decorate([
Output()
], FabricjsEditorComponent.prototype, "cleared", void 0);
FabricjsEditorComponent = __decorate([
Component({
selector: 'angular-editor-fabric-js',
template: "<canvas id=\"canvas\" #htmlCanvas></canvas>\n",
styles: ["#canvas{border:2px dashed #ccc}"]
})
], FabricjsEditorComponent);
return FabricjsEditorComponent;
}());
var FabricjsEditorModule = /** @class */ (function () {
function FabricjsEditorModule() {
}
FabricjsEditorModule = __decorate([
NgModule({
declarations: [FabricjsEditorComponent],
imports: [
BrowserModule,
FormsModule,
ColorPickerModule
],
exports: [FabricjsEditorComponent]
})
], FabricjsEditorModule);
return FabricjsEditorModule;
}());
/*
* Public API Surface of angular-editor-fabric-js
*/
/**
* Generated bundle index. Do not edit.
*/
export { CanvasManager, DEFAULT_CANVAS_WIDTH, FabricjsEditorComponent, FabricjsEditorModule };
//# sourceMappingURL=axceta-angular-editor-fabric-js.js.map