xxxxxxxxxx
/******************
Code by Vamoss
Original code link:
https://openprocessing.org/sketch/2256135
Author links:
http://vamoss.com.br
http://twitter.com/vamoss
http://github.com/vamoss
******************/
function setup() {
const SIZE = min(windowWidth, windowHeight) / 2;
createCanvas(windowWidth, windowHeight);
initDrag((width/2 - SIZE)/2, (height - SIZE)/2, SIZE, SIZE);
}
function draw() {
background(0);
//curve hack
//as suggested by Bernardo Fontes
fill(255);
beginShape();
for (let i=0; i < dragabble.length + 3; i++)
curveVertex(dragabble[i%dragabble.length].x, dragabble[i%dragabble.length].y);
endShape();
//hobby curve
//as suggested by @mariuswatz https://twitter.com/mariuswatz/status/1784924541556302031
//createHobbyBezier by @arnoson https://github.com/arnoson/hobby-curve
push();
translate(width/2, 0);
var hobbyPoints = createHobbyBezier(dragabble, { tension: 1, cyclic: true });
beginShape();
vertex(dragabble[0].x, dragabble[0].y);
hobbyPoints.forEach(({ startControl, endControl, point }) => {
bezierVertex(startControl.x, startControl.y, endControl.x, endControl.y, point.x, point.y);
});
endShape();
pop();
drawDrag();
}
function initDrag(x, y, w, h){
const border = 40;
addDrag(createVector(x + border, y + border));//TOP LEFT
addDrag(createVector(x + w - border, y + border));//TOP RIGHT
addDrag(createVector(x + w - border, y + h - border));//BOTTOM LEFT
addDrag(createVector(x + border, y + h - border));//BOTTOM RIGHT
}
function mousePressed() {
if(!dragMousePressed()){
// simple solution
// just create a point at the end of polygon
//addDrag(createVector(mouseX, mouseY));
// complex solution
// look for the closest avarage point between two points
let closest = 99999;
let closestIndex = -1;
for (let i=0; i < dragabble.length; i++) {
let nextIndex = (i+1)%dragabble.length;
let avarageX = dragabble[i].x + (dragabble[nextIndex].x - dragabble[i].x) / 2;
let avarageY = dragabble[i].y + (dragabble[nextIndex].y - dragabble[i].y) / 2;
let distX = avarageX - mouseX;
let distY = avarageY - mouseY;
let distance = distX * distX + distY * distY;
if(distance < closest){
closest = distance;
closestIndex = i;
}
}
if(closestIndex>=0){
addDrag(createVector(mouseX, mouseY), closestIndex+1);
}
}
}
function mouseReleased() {
dragMouseReleased();
}
function mouseDragged() {
dragMouseDragged();
}