From what I can see it looks like the only way to change the length of a single Path is to path.scale(x)
it. However I want to make the line's length oscillate slightly around its original length, which is difficult to do with scale
, because if you feed it random values you will in effect end up with its length taking a random walk, potentially ending up far away from its original length.
is it possible to set the length of a line path explicitly, something like path.length = 10
? According to the documentation it doesn't seem like this is possible. Why not?? And what would be the best way to achieve my desired outcome?
You can do this by noting that paths in paperjs are not geometric shapes though they may have been specified as one. They are arrays of segment points; that's why setting the length of a line directly is not possible. A line has two segment points - one for the start and one for the end of the line. By manipulating the second segment point you can adjust the length of the line. This sketch (the following code) illustrates how to do so. To adjust the length of the original line uncomment the last line of code.
line = new Path.Line([100,100], [200, 300]);
line.strokeColor = 'black';
line.strokeWidth = 5;
// paths in paper are arrays of segments, not instances of
// circle or line or rectangle. so find the vector that
// represents the delta between the first point and the
// second point.
vector = line.segments[0].point - line.segments[1].point;
// adjustment for the line - this would vary in your case
factor = 0.9;
// I'm drawing a new line here to make it easy to see
p0 = line.segments[0].point;
p1 = p0 - vector * factor;
newline = new Path.Line(p0, p1);
newline.strokeColor = 'red';
newline.strokeWidth = 2;
// but to adjust your original line just use the following
//line.segments[1].point = p1;
You can store the original vector, if you choose to do so, in the property line.data
which is an empty object that paper creates for whatever the user wishes. So line.data.vector = vector;
would allow you to keep each line's original vector. And you can set the length of a line to a specific length with the following:
var v = line.data.vector.clone();
v.length = 10; // specific length
line.segments[1].point = p0 - v;