Skip to content

Instantly share code, notes, and snippets.

@globalpolicy
Created August 22, 2019 17:49
Show Gist options
  • Save globalpolicy/12aa0e11fd737037a5e9be6e97ee474e to your computer and use it in GitHub Desktop.
Save globalpolicy/12aa0e11fd737037a5e9be6e97ee474e to your computer and use it in GitHub Desktop.
Convex hull with JavaScript and p5.js
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>
<script src="sketch.js"></script>
</head>
<body>
<div id="canvas"></div>
<input type="button" id="btnGo" value="Go" onclick="btnGoClicked()">
</body>
</html>
let width = 640,
height = 480;
let points = [];
let donePoints = [];
function setup() {
let cnv = createCanvas(width, height);
cnv.parent("canvas");
background(255, 0, 255);
}
function draw() {
}
function mouseClicked() {
if (mouseX < width && mouseY < height) {
fill(255);
ellipse(mouseX, mouseY, 5, 5);
points.push({
mouseX,
mouseY
});
}
}
function btnGoClicked() {
for (let i=0;i<points.length-1;i++) {
for (let j=i+1;j<points.length;j++) {
if (points[i] != points[j]) {
if(isSegmentConvex(points[i],points[j],points)){
line(points[i].mouseX,points[i].mouseY,points[j].mouseX,points[j].mouseY);
}
}
}
}
}
function isSegmentConvex(point1, point2, points) {
let side=null;
for (const point of points) {
if (point != point1 && point != point2) {
let d=(point.mouseX-point1.mouseX)*(point2.mouseY-point1.mouseY)-(point.mouseY-point1.mouseY)*(point2.mouseX-point1.mouseX);
if(side==null){
side=d;
}
if(d*side<0){//if 'd' and 'side' have opposite signs, there's at least one point on either side of the segment
return false;
}
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment