Skip to content

Instantly share code, notes, and snippets.

Created October 23, 2010 21:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/642717 to your computer and use it in GitHub Desktop.
Save anonymous/642717 to your computer and use it in GitHub Desktop.
proce55ing.js draw program
class Point {
int x, y;
Point(int X, int Y) { x = X; y = Y; }
void moveTo(Point other) { x = other.x; y = other.y; }
float distanceTo(Point other) {
return dist(x, y, other.x, other.y);
}
}
class Line {
Point start, end;
Line(Point S, Point E) { start = S; end = E; }
void draw() { line(start.x, start.y, end.x, end.y); }
}
ArrayList lines = new ArrayList();
void setup() {
size(250,250);
strokeWeight(2);
stroke(0);
}
Point last;
boolean rubberbanding = false;
Point selected;
void draw() {
background(255);
for (int i = 0; i < lines.size(); i++) {
((Line)lines.get(i)).draw();
}
if (rubberbanding) line(last.x, last.y, mouseX, mouseY);
}
void makeLine(Point here) {
Line newLine = new Line(last, here);
lines.add(newLine);
newLine.draw();
last = here;
}
Point pointAt(Point mouse) {
Point nearest;
for (int i = 0; i < lines.size(); i++) {
Line line = (Line)lines.get(i);
if (nearest == null) nearest = line.start;
if (nearest.distanceTo(mouse) > line.start.distanceTo(mouse)) {
nearest = line.start;
}
if (nearest.distanceTo(mouse) > line.end.distanceTo(mouse)) {
nearest = line.end;
}
}
return nearest;
}
void mousePressed() {
Point here = new Point(mouseX, mouseY);
if (selected != null) { // if we are dragging a point, release it
selected.moveTo(here);
selected = null;
} else {
Point nearest = pointAt(here);
if (nearest != null && nearest.distanceTo(here) < 3) {
selected = nearest;
rubberbanding = false;
} else { // we didn't click on a point, so start drawing
if (rubberbanding) makeLine(here);
last = here;
rubberbanding = true;
}
}
}
void mouseDragged() {
Point here = new Point(mouseX, mouseY);
if (selected != null) {
selected.moveTo(here);
} else {
makeLine(new Point(mouseX, mouseY));
rubberbanding = false;
}
}
void mouseMoved() {
if (selected != null) {
selected.moveTo(new Point(mouseX, mouseY));
}
}
void removeLinesUsingPoint(Point p) {
for (int i = lines.size()-1; i >= 0; i--) {
Line line = (Line)lines.get(i);
if (line.start == p || line.end == p) lines.remove(i);
}
}
void dumpDrawing() {
println("drawing:");
for (int i = 0; i < lines.size(); i++) {
Line line = (Line)lines.get(i);
print(line.start.x + " " + line.start.y + " ");
println(line.end.x + " " + line.end.y + " ");
}
println("end of drawing");
}
void keyPressed() {
if (key == 46 && selected != null) {
removeLinesUsingPoint(selected);
selected = null;
} else if (key == 's') {
dumpDrawing();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment