xxxxxxxxxx
// Example of how to draw a line with variable thickness.
// Polyline code rrom Dave Pagurek @davepvm
//
// Note that line ends and tight curves may display artifacts.
// Changing curveVertex to vertex calls in drawPolyline may
// help mitigate the problem.
let numPoints = 25;
let points = [];
let widths = [];
let a = 0;
let deltaA = 0.25;
function setup() {
createCanvas(windowWidth, windowHeight);
background(255);
}
function draw() {
background(255);
createPoints();
// Draw the polyline curve from Dave
stroke(255, 0, 0);
strokeWeight(4);
fill(0);
drawPolyline(points, widths);
// // Draw the original points
// fill(255, 0, 0);
// noStroke();
// points.forEach(p => {
// ellipse(p.x, p.y, 5, 5);
// });
}
//// Dave's Code
// Polyline - line with variable thickness
function drawPolyline(points, widths) {
const tangents = []
for (let i = 1; i < points.length; i++) {
tangents.push(points[i].copy().sub(points[i - 1]).normalize())
}
tangents.push(tangents[tangents.length - 1])
const normals = tangents.map((t) => createVector(-t.y, t.x))
beginShape()
for (let i = 0; i < points.length; i++) {
const pt = normals[i].copy().mult(widths[i] / 2).add(points[i])
curveVertex(pt.x, pt.y) // might want to use just vertex here
}
for (let i = points.length - 1; i >= 0; i--) {
const pt = normals[i].copy().mult(-widths[i] / 2).add(points[i])
curveVertex(pt.x, pt.y) // might want to use just vertex here
}
endShape(CLOSE)
}
//// End of Dave's Code
function createPoints() {
points = [];
widths = [];
for (let i = 0; i < numPoints; i++) {
let x = 20 + (width - 40) / numPoints * i;
let y = map(sin(a), -1, 1, height / 2 + 200, height / 2 - 200);
let p = createVector(x, y);
points.push(p);
let w = map(cos(a), -1, 1, 50, 1);
widths.push(w);
a += deltaA;
}
}