xxxxxxxxxx
90
let curvePoints,
resolution,
pointsRadius,
draggedIndex,
draggedOffset;
function setup() {
createCanvas(960, 540);
curvePoints = [];
resolution = createSlider(1, 256, 32, 1);
pointsRadius = 8;
draggedIndex = null;
draggedOffset = createVector(0, 0);
}
function draw() {
background("#111");
if (draggedIndex !== null)
curvePoints[draggedIndex] = p5.Vector.add(getMousePosition(), draggedOffset);
noFill();
strokeWeight(2);
stroke("#EEE");
drawCurve(curvePoints);
show(curvePoints);
}
function mousePressed() {
let offset = createVector(0, 0),
i = 0;
for (i = 0; i < curvePoints.length; i++) {
offset = p5.Vector.sub(curvePoints[i], getMousePosition());
if (offset.mag() <= pointsRadius) {
draggedIndex = i;
draggedOffset = offset;
}
}
}
function mouseClicked() {
if (draggedIndex === null) {
if (0 <= mouseX && mouseX < width && 0 <= mouseY && mouseY < height)
curvePoints.push(getMousePosition());
return;
}
draggedIndex = null;
}
function show(points) {
let i = 0;
if (points.length === 0)
return;
noFill();
stroke("#888")
strokeWeight(2 * pointsRadius);
point(points[0]);
point(points[points.length - 1]);
colorMode(HSB);
for (i = 1; i < points.length - 1; i++) {
stroke(256 / points.length * i, 80, 80);
point(points[i]);
}
colorMode(RGB);
}
function drawCurve(points) {
const x = points.map(current => current.x),
y = points.map(current => current.y);
let t = 0;
if (points.length === 0)
return;
beginShape();
for (t = 0; t <= resolution.value(); t++)
vertex(lerpception(x, t / resolution.value()), lerpception(y, t / resolution.value()));
endShape();
}
function lerpception(sequence, t) {
if (sequence.length > 2)
return lerp(lerpception(sequence.slice(0, -1), t), lerpception(sequence.slice(1), t), t);
if (sequence.length > 1)
return lerp(sequence[0], sequence[1], t);
if (sequence.length > 0)
return sequence[0];
return NaN;
}
function getMousePosition() {
return createVector(mouseX, mouseY);
}