xxxxxxxxxx
113
let lines = [];
let currentLine = [];
let canvas;
function setup() {
canvas = createCanvas(400, 200);
}
function draw() {
// console.log(lines)
// console.log(lines.reduce((accumulator, currentValue) => accumulator + currentValue.length, 0))
background(255, 255, 170);
noFill();
stroke(0);
drawingContext.setLineDash([7, 5]);
line(0, 0.85 * height, width, 0.85 * height);
drawingContext.setLineDash([]);
strokeWeight(2);
stroke(0, 0, 100);
for (let line of [currentLine, lines]) {
beginShape();
for (let p of line) {
vertex(p.x, p.y);
}
endShape();
}
if (mouseIsPressed == true) {
const pointX = Math.round(mouseX * 10) / 10;
const pointY = Math.round(mouseY * 10) / 10;
// check that last point is different from current
if (currentLine.length > 0) {
const lastPoint = currentLine[currentLine.length - 1];
if (lastPoint.x == pointX && lastPoint.y == pointY) return;
}
currentLine.push(createVector(
pointX,
pointY
));
// console.log(currentLine)
} else if (currentLine.length > 0) {
let newLine = [currentLine[0], rdp(currentLine), currentLine[currentLine.length - 1]];
console.log(newLine.length)
// remove same points after each other
newLine = newLine.filter((point, i, arr) => {
if (i == 0) return true;
return !point.equals(arr[i - 1]);
});
console.log(newLine.length)
console.log("")
lines.push(newLine);
// lines.push([currentLine[0], ...rgp(currentLine), currentLine[currentLine.length - 1]]);
currentLine = [];
}
}
function undo() {
lines.pop();
}
function exportImage() {
var dataURL = canvas.canvas.toDataURL();
console.log(dataURL);
}
function rdp(points = [], epsilon = 0.5) {
const p1 = points[0];
const p2 = points[points.length - 1];
const {
index,
dist
} = furthestPoint(p1, p2, points);
if (dist > epsilon) {
return [rdp(points.slice(0, index + 1), epsilon), rdp(points.slice(index).slice(1), epsilon)];
} else {
return p1 == p2 ? [p1] : [p1, p2];
}
}
function furthestPoint(p1, p2, points) {
let dmax = 0;
let maxI = -1;
for (let i = 0; i < points.length; i++) {
const dtemp = perpendicularDist(points[i], p1, p2);
if (dtemp > dmax) {
dmax = dtemp;
maxI = i;
}
}
return {
index: maxI,
dist: dmax
};
}
function perpendicularDist(p, p1, p2) {
if (p1 == p || p == p2) return 0;
const a = p.copy().sub(p1);
const b = p.copy().sub(p2);
const c = a.cross(b).mag();
const d = p2.copy().sub(p1).mag();
return c / d;
}