xxxxxxxxxx
86
// Create variables to keep track
// of the drawing and its title.
let drawing = {
title: "Untitled",
path: [],
};
let titleInput;
let prevX = 0;
let prevY = 0;
function setup() {
createCanvas(400, 400);
//frameRate(2)
// Create a text input for the sketch'stitle.
titleInput = createInput(drawing.title);
titleInput.position(5, 425);
titleInput.size(200);
// Create an upload button.
let button = createButton("Upload");
button.position(220, 425);
button.mouseClicked(uploadDrawing);
}
function draw() {
background(220);
// Iterate through each segment
for (let segment of drawing.path) {
for (let i = 0; i < segment.points.length - 1; i++) {
let p1 = segment.points[i];
let p2 = segment.points[i + 1];
let numPoints = int(dist(p1.x, p1.y, p2.x, p2.y));
for (let j = 0; j < numPoints; j++) {
let x = lerp(p1.x, p2.x, j / numPoints);
let y = lerp(p1.y, p2.y, j / numPoints);
fill(0);
noStroke();
circle(x, y, 5);
}
}
}
}
// Update the drawing path while the
// mouse is dragged.
function mouseDragged() {
let p = { x: mouseX, y: mouseY };
// If this is the first point in a new segment or if mouse is pressed after release, create a new segment
if (drawing.path.length === 0 || drawing.path[drawing.path.length - 1].isComplete) {
drawing.path.push({ points: [p], isComplete: false });
} else {
// Otherwise, add the point to the current segment
drawing.path[drawing.path.length - 1].points.push(p);
}
}
function mousePressed() {
prevX = mouseX;
prevY = mouseY;
}
function mouseReleased() {
if (drawing.path.length > 0) {
drawing.path[drawing.path.length - 1].isComplete = true;
}
}
// Clear the drawing path when the
// canvas is double-clicked.
function doubleClicked() {
drawing.path = [];
}
// Upload the data to the server
// using a POST request.
function uploadDrawing() {
drawing.title = titleInput.value();
httpPost("/data", "json", drawing);
}