xxxxxxxxxx
178
class DragPoint {
constructor(x, y) {
this.x = x;
this.y = y;
this.h = 8;
this.w = this.h;
}
isHit(x, y) {
let w = this.w * 2.0;
return (
(x > this.x - w && x < this.x + w) &&
(y > this.y - w && y < this.y + w)
)
}
updatePos(x, y) {
this.x = x;
this.y = y;
}
render() {
fill(220);
noStroke();
rectMode(CENTER);
let factor = this.isHit(mouseX, mouseY) ? 1.0 : 0.5;
rect(this.x,this.y, this.w * factor, this.h * factor);
};
}
let points = [];
let shape = [];
let activePoint_index = -1;
const cosineInterpolate = (y1, y2, mu) =>
{
let mu2;
mu2 = (1.0 - cos(mu*PI) ) / 2.0;
return (y1 * (1.0 - mu2) + y2 * mu2);
}
const linearInterpolate = (y1, y2, mu) => {
return(y1*(1.0-mu)+y2*mu);
}
let interpolation = cosineInterpolate;
function setup() {
createCanvas(400, 400);
points.push(new DragPoint(10, 230));
points.push(new DragPoint(210, 23));
points.push(new DragPoint(340, 145));
shape = buildShape(points, interpolation);
}
const getPointsforSegment = (interpolationType, p1, p2) => {
let start = p1.x;
let end = p2.x;
let points = [];
for(let x = start; x < end; x++)
{
let mu = map(x, start, end, 0, 1);
let point = {x:0, y:0};
point.x = x;
point.y = interpolationType(p1.y, p2.y, mu) ;
points.push(point);
}
return points;
}
const buildShape = (points, interpolationType) => {
let shape = [];
points.map((point, i) => {
if ( typeof points[i+1] !== 'undefined') {
let arr = getPointsforSegment(interpolationType, point, points[i+1]) ;
shape = shape.concat(arr);
}
});
return shape;
}
function mousePressed() {
if (mouseButton == LEFT) {
if (activePoint_index = -1) {
points.map((point, i) => {
if (point.isHit(mouseX, mouseY) ) {
activePoint_index = i;
}
});
}
}
if(mouseButton === CENTER) {
points.push(new DragPoint(mouseX,mouseY));
// shape = buildShape(points, interpolation);
}
}
function keyReleased() {
if (keyCode == 80) {
if (interpolation === cosineInterpolate) {
interpolation = linearInterpolate;
} else {
interpolation = cosineInterpolate;
}
shape = buildShape(points, interpolation);
}
}
function mouseReleased() {
activePoint_index = -1;
const sortingFunc = (a,b) => {
//console.log(a.x);
return a.x - b.x;
}
points.sort(sortingFunc);
shape = buildShape(points, interpolation);
}
function update() {
if (activePoint_index >= 0) {
points[activePoint_index].updatePos(mouseX, mouseY);
shape = buildShape(points, interpolation);
}
}
function draw() {
background(121);
update();
noFill();
stroke(0);
beginShape();
shape.map((point) => {
vertex(point.x, point.y);
});
endShape();
//line(0, 0, 0, height);
//line(0, height / 2, width, height / 2);
points.map((point) => {
//point.update();
point.render();
});
}