/* * A basic interface for the user to draw a collection of ellipses. * In this example, the user can draw an ellipse by selecting the center * and then dragging the mouse to designate a corner of the bounding box. * * Pressing 'a' aborts the currently stretched ellipse * Pressing 'c' clears the canvas. * Pressing 'u' undos most recent ellipse (if any) * * We use arrays to store the parameters of the ellipses so that we can * repaint them from within draw after clearning the background. */ int MAX_NUM = 1000; // somewhat arbitrary limit boolean active = false; // active if ellipse currently being drawn int cx, cy; // center of currently stretched ellipse (if any) int numEllipses = 0; // count of complete ellipses (i.e., not including stetching one) int x[] = new int[MAX_NUM]; // x[k] is x-coord for center of ellipse k int y[] = new int[MAX_NUM]; // y[k] is y-coord for center of ellipse k int w[] = new int[MAX_NUM]; // w[k] is width of ellipse k int h[] = new int[MAX_NUM]; // h[k] is height of ellipse k color col[] = new color[MAX_NUM]; // random color for ellipse k // This function is executed only once, at the very beginning void setup() { size(600, 400); } // This function is repeatedly call in an implicit loop. // A single call is responsible for drawing a single frame. void draw() { background(255); // first draw all existing ellipses for (int k=0; k < numEllipses; k++) { fill(col[k]); ellipse(x[k], y[k], w[k], h[k]); } // now draw a stretching ellipse, if currently active if (active) { noFill(); int tempW = 2*abs(mouseX-cx); int tempH = 2*abs(mouseY-cy); ellipse(cx, cy, tempW, tempH); } } // when mouse is first pressed, record the position as center of new ellipse void mousePressed() { cx = mouseX; cy = mouseY; active = true; } // when mouse is released, lock in parameters for newest ellipse void mouseReleased() { if (active) { active = false; int k = numEllipses; // this is coordinate for newest ellipse numEllipses++; // and now we have one more x[k] = cx; y[k] = cy; w[k] = 2*abs(mouseX-cx); h[k] = 2*abs(mouseY-cy); col[k] = color(random(127, 255), random(127, 255), random(127, 255)); // pastels } } // clear all history when space is pressed void keyPressed() { if (key == 'a') { // abort current ellipse active = false; } else if (key == 'c') { // clear all history numEllipses = 0; } else if (key == 'u' && numEllipses > 0) { numEllipses--; // remove most recent ellipse } }