If you have a vector line path in Raphael.js and would like to style part of it - highlighting a section of a line graph, for example - you can achieve this easily using the path.getSubPath()
interface to get part of your path, then adding a new shape on top based on that pathstring.
For example, let’s say we had a squiggly line:
The line itself is fairly easy to create with Raphael’s paper.path()
method:
1 | var paper = Raphael('paper', 640, 480); |
Now let’s say we want to highlight only part of it:
This is pretty simple:
1 | var paper = Raphael('paper', 640, 480); |
The getSubPath method gets us a path string that we can pass to paper.path()
just like any other. By default, new vector elements are drawn at the front, so it’ll appear on top of the original line. If you need to coerce this for whatever reason, there’s an element.toFront()
interface that does just that.
Now let’s say we wanted to only highlight the last 20 pixels of the line. I say pixels; pixels on SVG elements are actually arbitrary units based on the size of the viewbox rather than pixels in the browser. But let’s assume we’re not doing any scaling, so there’s a 1:1 mapping between pixels in our viewbox and pixels in our browser. We can highlight the last 20 pixels by simply subtracting twenty from the total line length, which we can obtain with element.getTotalLength()
, then passing that to element.getSubpath
.
1 | var paper = Raphael('paper', 640, 480); |
Pretty easy, isn’t it? Raphael is a firm favourite of mine.