I want to write a function that, when called, returns an SVG of the fabric canvas where all text elements are replaced by paths.
This is what I came up with so far
const toPath = async () => {
const myCanvas = new fabric.Canvas("render-canvas"); //create a canvas for converting
myCanvas.loadFromJSON(canvas.toJSON()); //copy the orignal canvas into it
const objects = myCanvas.getObjects();
objects.forEach((object, index) => { //iterate over all objects
if(object.type === "i-text") { //if i-text, get font and use opentype.js to generate path
if(object.fontFamily !== "") { //opentype.load is async returning a promise
opentype.load(process.env.PUBLIC_URL+"/fonts/ttf/"+getFontByName(object.fontFamily)["url"])
.then(font => {
const path = font.getPath(object.text, 0, 0, object.fontSize);
const fabricPath = new fabric.Path(path.toPathData(20), {
//some options, size, pos, color ect copied from original
});
console.log(index);
myCanvas.insertAt(fabricPath, index);
myCanvas.remove(object);
console.log(myCanvas.getObjects()); //contains correct paths
})
.catch(err => console.log("Error fetching font:", err));
}
}
});
//somewhere above I need to return a promise that is resolved when the loop is finished
return myCanvas; //wrong here, returns unconverted copy always because of promises
}
I want to call the function somehow like this:
const pathCanvas = toPath();
// when all promises resolved
svg = pathCanvas.then(canvas => canvas.toSVG());
Now how can I use a promise here, to resolve it using fabric.toSVG() once the whole loop ran successfully?