I want to create an erase feature for a drawing app. Before I start writing code, I want to explain my methodology for solving this problem and ask you if there is a simpler way to do this.
Perquisite The following p5.js app is what I am referencing for this question: https://editor.p5js.org/crhallberg/sketches/SJrrLGiYM
Objective To create a tool that lets the user erase or undo the last drawing step they made.
Question
In the app referenced, you (as the user) draw lines on a grid. I (as developer) want to create a way for the user to erase or undo their last line draw. I have never used p5.js and I am exploring the thought process needed to solve this problem. The solution I have come up with is as follows:
On each mousedown/mouse up event store the line coordinates in an array. When the user decides to erase a line, find the last coordinates stored in the array and remove it. Redraw the entire app and iterate over all stored "line draw coordinates" and redrawing them.
p5.js is its own environment and I figure there might be an easier/different/built-in way to do this. I'd rather ask first before coding. Thank you.
var grid = 100;
var gridOffset = grid / 2;
function setup() {
createCanvas(500, 500);
background(255);
// Draw grid
var l = 0;
strokeWeight(1);
stroke(151);
while (l < width || l < height) {
line(0, l, width, l);
line(l, 0, l, height);
l += grid;
}
}
function draw() {
strokeWeight(gridOffset);
stroke(0, 0, 255);
if (mouseIsPressed) {
var x = snap(mouseX);
var y = snap(mouseY);
var px = snap(pmouseX);
var py = snap(pmouseY);
line(px, py, x, y);
}
}
function snap(op) {
// subtract offset (to center lines)
// divide by grid to get row/column
// round to snap to the closest one
var cell = Math.round((op - gridOffset) / grid);
// multiply back to grid scale
// add offset to center
return cell * grid + gridOffset;
}