Yeah something like that.
To make your sketch interactive, you will need a draw() loop. Then you can determine what you pre-calculate in setup() and what you need in the draw() loop. Since a piechart is a pretty simple shape you can just solve the mouseOver algorithmically. Depending on the selected slice you can change it's color and draw the relevant data on top of everything.
Adapted Code
- int numFake = 50;
- String[] stateNames;
- float[] numRape, theta;
- float diameter, totalRapes;
-
- void setup() {
- size(750, 750);
- noStroke();
- smooth();
- diameter = min(width, height)/1.2;
- stateNames = new String [numFake];
- numRape = new float [numFake];
- theta = new float [numFake];
- for (int i=0; i<numFake; i++) {
- stateNames[i] = "state_" + nf(i, 2);
- numRape[i] = random(1,20);
- totalRapes += numRape[i];
- }
- float angle = 0;
- for (int i=0; i<numFake; i++) {
- theta[i] = angle;
- angle += numRape[i]/totalRapes*TWO_PI;
- }
- }
-
- void draw() {
- background(149, 163, 180);
-
- fill(255);
- textSize(26);
- text("Reported Forcible Rapes per State in 2011", width/8, height/15);
- textSize(12);
- text("data from FBI.gov - sketch by -----", width/2.2, height/29);
-
- float mouseTheta = atan2(mouseY-height/2, mouseX-width/2);
- float piTheta = mouseTheta>=0?mouseTheta:mouseTheta+TWO_PI;
-
- int selected = -1;
- for (int i=0; i<stateNames.length; i++) {
- float start = theta[i];
- float end = i==stateNames.length-1?TWO_PI:theta[i+1];
- if (piTheta>= start && piTheta <= end) {
- fill(255, 0, 0);
- selected = i;
- } else {
- fill(0, 0, noise(i)*((i%2==0)?255:50));
- }
- arc(width/2, height/2, diameter, diameter, start, end);
- }
-
- if (selected>-1) {
- fill(255);
- textSize(36);
- String msg = stateNames[selected] + ": " + nfc(numRape[selected], 2) + " reported";
- text(msg,(width-textWidth(msg))/2, 100);
- }
- }