Combine Multiple paths to Single path
Combine Multiple paths to single paths
Recently i was searching for a simple logic to combine multiple path data to single path, and i come up with the final solution to combine multiple paths as follows.
combinePaths(paths) {
if (!paths.length) {
return null;
}
let singlePath = paths[0];
for (let i = 1; i < paths.length; i++) {
if(paths[i][0][0] === "M") {
paths[i][0][0] = "Q";
paths[i][0][3] = paths[i][0][1];
paths[i][0][4] = paths[i][0][2];
}
singlePath = [...singlePath, ...paths[i]];
}
return singlePath;
}
In fabric js we can combine and pass multiple paths data to fabric.path class to generate single fabric js object as follows.
combinePaths(paths, strokeColor, strokeWidth) {
if (!paths.length) {
return null;
}
let singlePath = paths[0];
for (let i = 1; i < paths.length; i++) {
if(paths[i][0][0] === "M") {
paths[i][0][0] = "Q";
paths[i][0][3] = paths[i][0][1];
paths[i][0][4] = paths[i][0][2];
}
//To combine the last path with first path
// we can update the logic as below
if(i === paths.length-1) {
var len = paths[i].length;
paths[i][len] = [];
paths[i][len].push("Q");
paths[i][len].push(paths[i][len-1][1]);
paths[i][len].push(paths[i][len-1][2]);
paths[i][len].push(paths[0][0][1]);
paths[i][len].push(paths[0][0][2]);
}
singlePath = [...singlePath, ...paths[i]];
}
return new fabric.Path(singlePath, {
fill: '',
stroke: strokeColor,
strokeWidth: strokeWidth,
strokeLineCap: 'round',
strokeDashOffset: 0,
});
}
Using above simple function we can combine multiple seperate paths into single path.