import 'fabric';
declare const fabric: any;
export class EditorComponentSvg {
private constructor() { /* noop */ }
public static fixSVGText(str) {
const svg = new DOMParser().parseFromString(str, 'image/svg+xml').documentElement;
const tspans = svg.querySelectorAll('tspan');
for (let i = 0; i < tspans.length; i++) {
const ts = tspans[i];
const parent = ts.parentNode;
const gParent = parent.parentNode;
let j = 0;
const replace = document.createElementNS('http://www.w3.org/2000/svg', 'text');
const tsAttr = ts.attributes;
const tAttr = (<SVGElement> parent).attributes;
for (j = 0; j < tsAttr.length; j++) {
replace.setAttributeNS(null, tsAttr[j].name, tsAttr[j].value);
}
const childNodes = ts.childNodes;
for (j = 0; j < childNodes.length; j++) {
replace.appendChild(ts.childNodes[j]);
}
for (j = 0; j < tAttr.length; j++) {
replace.setAttributeNS(null, tAttr[j].name, tAttr[j].value);
}
gParent.appendChild(replace);
if (ts === parent.lastElementChild) {
gParent.removeChild(parent);
}
}
return new XMLSerializer().serializeToString(svg);
}
public static splitSvg(objects, fonts){
const textObjects = [];
const nonTextObjects = [];
const nonTextObjectParentGroup = new fabric.Group();
const groupLimit = 200;
let fabricGroup = new fabric.Group();
let previousType = '';
const tempCanvas = new fabric.Canvas(document.createElement('canvas')); // to fix too large width & height of groups
for (let c = 0; c < objects.length; c++) {
if (objects[c].type === 'text') {
objects[c].fontSize = Math.round(objects[c].fontSize * objects[c].scaleX);
objects[c].scaleX = 1;
objects[c].scaleY = 1;
objects[c].fontFamily = objects[c].fontFamily.replaceAll('\'', '');
if (fonts.indexOf(objects[c].fontFamily) === -1) {objects[c].fontFamily = fonts[0]; }
objects[c].setCoords();
textObjects.push(objects[c]);
} else {
if (objects[c].clipPath === undefined) {
nonTextObjects.push(objects[c]);
tempCanvas.add(objects[c]); // to fix too large width & height of groups
}
}
}
for (let c = 0; c < nonTextObjects.length; c++) {
if (fabricGroup.size() === groupLimit || c === nonTextObjects.length - 1) {
nonTextObjectParentGroup.addWithUpdate(fabricGroup);
fabricGroup = new fabric.Group();
} else if (c > 0 && previousType !== nonTextObjects[c].type) {
nonTextObjectParentGroup.addWithUpdate(fabricGroup);
fabricGroup = new fabric.Group();
}
fabricGroup.addWithUpdate(nonTextObjects[c]);
previousType = nonTextObjects[c].type;
}
if (nonTextObjects.length === 1) {
nonTextObjectParentGroup.addWithUpdate(nonTextObjects[0]);
}
return ({nonTextObjectParentGroup, textObjects});
}
}
|