Reputation: 1933
I have two curved paths, both roughly going from left to right, one above the . I need to join them up with straight lines into a closed path.
To do this, I am assuming I need to build the path string of the big closed path. But in order to build the path, I need to reverse the second curve.
How can I reverse a path in Raphael.js? Or is there a better way to do what I want to do?
Thanks.
Upvotes: 1
Views: 1048
Reputation: 1494
I needed this functionality recently to fill the area between to curves on a graph. I used the following implementation.
function reversePath(pathString) {
var pathPieces = pathString.match(/[MLHVCSQTA][-0-9.,]*/gi);
var reversed = '';
var skip = true;
var previousPathType;
for (var i = pathPieces.length - 1; i >= 0; i--) {
var pathType = pathPieces[i].substr(0, 1);
var pathValues = pathPieces[i].substr(1);
switch (pathType) {
case 'M':
case 'L':
reversed += (skip ? '' : pathType) + pathValues;
skip = false;
break;
case 'C':
var curvePieces = pathValues.match(/^([-0-9.]*,[-0-9.]*),([-0-9.]*,[-0-9.]*),([-0-9.]*,[-0-9.]*)$/);
reversed += curvePieces[3] + pathType + curvePieces[2] + ',' + curvePieces[1] + ',';
skip = true;
break;
default:
alert('Not implemented: ' + pathType);
break;
}
}
return reversed;
}
And I would call it like so:
var combinedPath = path1 + 'L' + reversePath(path2) + 'Z';
Upvotes: 0
Reputation: 2482
Can you try using this example?
It creates 2 independent paths running left to right. Then it merges these into a closed path.
Try in JSFiddle.
EDITED:
var paper = Raphael(0, 0, 800, 600);
// Define 2 paths running left to right
var path1 = paper.path("M10 10L200 120 300 80 400 100 450 150")
.attr({stroke: "#00FF00"}),
path2 = paper.path("M10 200L200 220 300 280 400 300 450 250")
.attr({stroke: "#00FF00"}),
closedPath = joinPaths(path1, path2)
.attr({
fill: "#FF0000",
stroke: "#0000FF"
});
// This function is a poc and assumes that
// the paths contain a "M" at the begining
// and that that "M" is replacable by "L" (absolute Line to)
function joinPaths() {
var i,
len = arguments.length,
pathArr =[],
finalPathArr =[];
for (i = 0; i < len; i++) {
pathArr[i] = arguments[i].attr("path");
if (i) {
pathArr[i][0][0] = "L";
pathArr[i].reverse();
if (i === len-1) {
pathArr[i].push("Z");
}
}
finalPathArr = finalPathArr.concat(pathArr[i]);
}
return paper.path(finalPathArr);
}
Upvotes: 1