Rascar
Rascar

Reputation: 85

Raphaël - transformPath() to return lines instead of curves

Is it possible to get Raphael.transformPath() to return a path made of lines instead of a path made of curves?

                var path = "M10,20L30,40";
                var trans = "t100,100s2,2";
                var trpath = Raphael.transformPath(path, trans);
                console.log('trpath: ' + trpath);

will output:

trpath: M100,110C100,110,140,150,140,150 

I need this path with only straight lines!

Upvotes: 4

Views: 1808

Answers (1)

Chris Wilson
Chris Wilson

Reputation: 6719

Weird, not sure why Raphael chooses to do this. But not too hard to get around:

If you consult the source for the .transformPath() method, you'll see that it is a composite of two other utility methods:

transformPath = R.transformPath = function (path, transform) {
    return mapPath(path, toMatrix(path, transform));
}

Pretty straight-forward: .toMatrix() parses that transform string into a matrix, and mapPath applies that matrix to the path string.

For some reason, mapPath includes a call to the .path2curve() method, which is why you're having trouble. So we need to grab the source for that method and modify it:

var mapPathStraight = function (path, matrix) {
    if (!matrix) {
        return path;
    }
    var x, y, i, j, ii, jj, pathi;
    //replace following line with .parsePathString(), which also parses path string into an array without adding curves
    //path = path2curve(path);
    path = Raphael.parsePathString(path);
    for (i = 0, ii = path.length; i < ii; i++) {
        pathi = path[i];
        for (j = 1, jj = pathi.length; j < jj; j += 2) {
            x = matrix.x(pathi[j], pathi[j + 1]);
            y = matrix.y(pathi[j], pathi[j + 1]);
            pathi[j] = x;
            pathi[j + 1] = y;
        }
    }
    return path;
};

Now we can achieve a straight line like so:

var trpath = mapPathStraight(path, Raphael.toMatrix(path, trans));

Which gives me an output of:

trpath: M100,110L140,150 

Here's the jsFiddle

Upvotes: 5

Related Questions