I'm drawing a curve in P5JS using the beginShape() and endShape() functions. When adding points to my shape (a line) I'm doing so via the curveVertex() function. However, the final curve does not create a segment between points[0] and points[1] for some reason. If I add the points to the curve via the vertex() function instead, the first segment is drawn. Relevant code:
function draw() {
// Loop through creating line segments
beginShape()
noFill()
// Add the first point
stroke('black')
strokeWeight(5)
curveVertex(x, y)
// Save points, draw last
let points = []
points.push({x: x, y: y})
// Draw line
for (let i = 0; i < segments; i++){
// Get random y
yRand = random(-(height * 0.125), height * 0.125);
// Add point to curve
curveVertex(x += length / segments, y += yRand);
// Save point
points.push({x: x, y: y})
}
// Draw Last Point
curveVertex(x, y)
endShape()
// Draw the last point & segment
stroke('#ff9900')
strokeWeight(10)
points.push({x: x, y: y})
points.forEach(function(p){
point(p.x, p.y)
})
// Draw the line once and stop
noLoop();
}
This produces the following image:
You can see a missing segment between points[0] and points1. Now, if I replace curveVertex() with vertex() in the three places in my code, I get the following image:
As you can see, the first segment is drawn here. If I use endShape(CLOSE) I get the first segment using the curveVertex mode—but also get a line drawn between points[0] and points[-1] (which is unwanted behavior)
My question: what's the difference between vertex() and curveVertex() that would omit the first segment?
From the documentation:
The first and last points in a series of curveVertex() lines will be used to guide the beginning and end of a the curve. A minimum of four points is required to draw a tiny curve between the second and third points. Adding a fifth point with curveVertex() will draw the curve between the second, third, and fourth points.
Essentially, the workaround seems to be to add a duplicate point for both the start and end of a curve unless one should choose to add the CLOSE argument to the endShape() function.
This produces the following image:
All that is required is to duplicate the curveVertex(x, y) call for the start and endpoints. So a collection of points {1, 2, 3, 4, 5} would essentially become {1, 1, 2, 3, 4, 5, 5} . Strange, but predictable.