xxxxxxxxxx
80
let points = [];
let drawing = false;
let drawCanvas;
let finalCanvas;
function setup() {
createCanvas(400, 400);
drawCanvas = createGraphics(width, height);
finalCanvas = createGraphics(width, height);
background(220);
}
function draw() {
drawCanvas.clear();
finalCanvas.clear();
if(drawing) {
points.push(createVector(mouseX, mouseY));
drawCanvas.noFill();
drawCanvas.beginShape();
for(let i = 0; i < points.length; i ++) {
drawCanvas.vertex(points[i].x, points[i].y);
}
drawCanvas.endShape();
}
image(drawCanvas, 0, 0);
image(finalCanvas, 0, 0);
}
function mousePressed() {
drawing = true;
points = [];
}
function mouseReleased() {
drawing = false;
points = smoothPoints(points, 0.5);
finalCanvas.noFill();
finalCanvas.beginShape();
for(let i = 0; i < points.length; i ++) {
finalCanvas.curveVertex(points[i].x, points[i].y);
}
finalCanvas.endShape();
}
function smoothPoints(inputPoints, smoothingFactor) {
if (inputPoints.length < 2) {
// Not enough points to smooth
return inputPoints;
}
const smoothedPoints = [inputPoints[0]]; // Initialize with the first point
for (let i = 1; i < inputPoints.length; i++) {
const prevPoint = smoothedPoints[smoothedPoints.length - 1];
const currentPoint = inputPoints[i];
// Calculate the difference between the current point and the previous point
const deltaX = currentPoint.x - prevPoint.x;
const deltaY = currentPoint.y - prevPoint.y;
// Apply smoothing factor to adjust the interpolation
const smoothedX = prevPoint.x + deltaX * smoothingFactor;
const smoothedY = prevPoint.y + deltaY * smoothingFactor;
// Add the smoothed point to the result
smoothedPoints.push({ x: smoothedX, y: smoothedY });
}
return smoothedPoints;
}