BBaysinger
BBaysinger

Reputation: 6857

Function that converts circle properties into a counter-clockwise (reverse) SVG circular path

I have a script that takes properties of a circle, and converts them to a clockwise SVG path. It looks like:

static circlePath(cx, cy, r) {
    return 'M ' + cx + ' ' + cy + ' m -' + r + ', 0 a ' + r + ',' + r + ' 0 1,0 ' + (r * 2) + ',0 a ' + r + ',' + r + ' 0 1,0 -' + (r * 2) + ',0';
}

I need the exact same thing, but counter-clockwise, for my text path to wrap on the other side of a circle, which is necessary for Chrome, as it does not support text wrap on circle, and does not support the side property of textPath.

I've already tried a utility that is should reverse my path after it's created, but it doesn't seem to be giving the right output, as I input:

M 0 0 m -287.5, 0 a 287.5,287.5 0 1,0 575,0 a 287.5,287.5 0 1,0 -575,0 

and it outputs:

M 0 0 M -287.5 0 

Upvotes: 0

Views: 151

Answers (1)

BBaysinger
BBaysinger

Reputation: 6857

Actually, this is super easy. Since the path draws two arcs, you just need to toggle the sweep flags, as those determine clockwise or counterclockwise (or anticlockwise). So this:

m -287.5, 0 a 287.5,287.5 0 1,0 575,0 a 287.5,287.5 0 1,0 -575,0 

Becomes:

m -287.5, 0 a 287.5,287.5 0 1,1 575,0 a 287.5,287.5 0 1,1 -575,0

And the function can take a sweep parameter:

static circlePath(cx, cy, r, sweep) {
    if (typeof sweep === 'undefined') sweep = 1;
    return 'm -' + r + ', 0 a ' + r + ',' + r + ' 0 1,' + sweep + ' ' + (r * 2) + ',0 a ' + r + ',' + r + ' 0 1,' + sweep + ' -' + (r * 2) + ',0';
}

Or in ES6:

static circlePath(cx, cy, r, sweep = 1) {
return `m -${r}, 0 a ${r},${r} 0 1,${sweep} ${r * 2},0 a ${r},${r} 0 1,${sweep} -${r * 2},0`;
}

https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/d#Path_commands

Upvotes: 1

Related Questions