The basic SVG rect shape provides functionality for rounded corners. Unfortunately, you can only change it for all four corners. I needed a rectangle which supports something like the CSS3 top- and bottom-border-radius instructions.
I needed this because of my GSoC project. In this project, there are different node types which have to be visualized. You can see the two node types (which are the reason for this blog post) in the following figure.
Sticking to the Don’t-Repeat-Yourself paradigm, I abstracted the drawing of rectangular shapes into a base class RectangularNode from which the classes Macromolecule and NucleicAcidFeature inherit. Since the two node types are the same (with regard to implementation), except for the border radius, I put all the funtionality into the base class RectangularNode. Now the Macromolecule and NucleicAcidFeature classes are merely subclasses which set the border radius on the RectangularNode class.
Now to the drawing of rectangles with different border-radii, there is no basic SVG shape which supports such behavior. As a result, you need the SVG path element. The path element enables you to draw such things as curves and arcs and can be used to draw every possible shape. For this specific issue, the arc is needed. Please refer to the specification for an explanation of the various commands and the path element in general. In this post I’ll only cover the generation of rectangles with different border radii and the arc command. The arc command is defined the following way (expressed as a regular expression in JavaScript with an example parsing).
console.log(evaluatedCommand);</pre>
A very good description of the parameters can be found in the specification. Now to the actual generation, I’m uing the following two helper functions for this. Please refer to the comments in the source code for a description of the functionality.
With this utility function we can now generate rectangles in the following way (use this jsfiddle to try it right away) .
That's me, Ben.
Hey, I am Ben Ripkens (bripkens)
and this is my blog.
I live in
Düsseldorf
(Germany)
and I am employed by the
codecentric AG as a Software Engineer.
Web application frontends are my main area of expertise, but you may also
find some other interesting articles on this blog.