Chris Wilson
Chris Wilson

Reputation: 6719

Using SVG curves to imitate rounded corners

I have a series of backwards-'L' shapes drawn in Raphael in SVG path notation -- just a collection of datapoints each represented by a horizontal line then a vertical line, of varying lengths.

<div id="canvas"></div>​
<script>
    var data = [
        [{x: 32, y: 207}, {x: 50, y: 371}],
        [{x: 34, y: 209}, {x: 39, y: 34}],
        [{x: 32, y: 216}, {x: 58, y: 38}],
        [{x: 70, y: 221}, {x: 93, y: 40}],
        [{x: 89, y: 223}, {x: 105, y: 41}],
        [{x: 113, y: 225}, {x: 150, y: 42}],
        [{x: 132, y: 228}, {x: 173, y: 43}],
        [{x: 305, y: 230}, {x: 354, y: 45}]
    ],
        paper = Raphael("canvas", 400, 300),
        path;

    for (var c = 0; c < data.length; c += 1) {
        path = "M" + data[c][0].x + "," + data[c][0].y;
        path += "H" + data[c][1].x;
        path += "V" + data[c][2].y;
        paper.path(path).attr({"stroke": "#900", "stroke-width": 2})
    }
</script>

jsFiddle

I would like to give these shapes rounded corners of a radius of 5 or so. Do I have to manually draw the horizontal line to 5px short of its destinatation, program a curve up PI/2 radians, then draw the rest of the vertical line?

I'm hoping there's a way to do this with a single SVG curve with a small radius, such that the shape proceeds in a straight line until shortly before its end and then curves upward -- exactly the behavior of a rounded rectangle in Raphael or CSS3.

I have examined the SVG path guidelines but am having difficulty working through the details.

Thank you!

Upvotes: 2

Views: 4731

Answers (1)

Timo K&#228;hk&#246;nen
Timo K&#228;hk&#246;nen

Reputation: 12220

This should do the trick (at least in the example cases):

http://jsfiddle.net/jYGrq/3/

Change this

path += "H" + (data[c][1].x)

to this: path += "H" + (data[c][1].x-5);

And add these lines after it:

if (data[c][0].y > data[c][1].y) path += "s 5 0 5 -5";
else if (data[c][0].y < data[c][1].y) path += "s 5 0 5 5";

This covers all the cases in example, but if you want to round corners despite of the orientation, make more ifs. Hope this helps a little.

By the way, I assume that shorthand relative cubic (s) is the curve type that is most suitable in your case.

Upvotes: 3

Related Questions