Gaterde
Gaterde

Reputation: 819

Processing - Move circle with cursor position

I made a simple drawing program to draw lines and increase/decrase the thickness of the line:

float strokeWeight = 2;

void setup() {
  size(640, 360);
  noSmooth();
  fill(126);
  background(255);
  strokeWeight(strokeWeight);
}

void draw() {
  background(0);
  ellipse(mouseX, mouseY, strokeWeight/2, strokeWeight/2);
  background(255);

  if (mousePressed) {
    stroke(0);
    line(mouseX, mouseY, pmouseX, pmouseY);
  }

  if (keyPressed) {
    if (key == '+') {
      strokeWeight = strokeWeight + 0.5;
      }
    if  (key == '-') {
      strokeWeight = strokeWeight - 0.5;
      }
     if (strokeWeight >= 0.5) {
      strokeWeight(strokeWeight);
     }
    }
}

Now I want to move a circle with my cursor that indicates the current thickness of the line. I tried something like this:

ellipse(mouseX, mouseY, strokeWeight/2, strokeWeight/2)

But this way it draws ellipses over and over again. Is there a way to "erase" the circle made before?

Upvotes: 0

Views: 1009

Answers (1)

Alberto89
Alberto89

Reputation: 356

I am not 100% sure that I've understood your question, but you probably want to use PGrahics, on one you keep the lines, on the other you draw the circle.

float strokeWeight = 2;

PGraphics canvas;
PGraphics thickness_circle;

void setup() {
  size(640, 360);

  canvas = createGraphics(width, height);

  thickness_circle = createGraphics(width, height);

  thickness_circle.beginDraw();
  thickness_circle.noFill();
  thickness_circle.strokeWeight(1);
  thickness_circle.stroke(255, 0, 0);
  thickness_circle.endDraw();
}

void draw() {
  background(255);

  if (keyPressed) {
    if (key == '+') {
      strokeWeight += 0.5;
    }
    if  (key == '-') {
      strokeWeight -= 0.5;
    }
    strokeWeight = strokeWeight >= 0.5 ? strokeWeight : 0.5;
  }

  if (mousePressed) {    
    canvas.beginDraw();
    canvas.strokeWeight(strokeWeight);
    canvas.line(mouseX, mouseY, pmouseX, pmouseY);
    canvas.endDraw();
  }

  image(canvas, 0, 0);

  thickness_circle.beginDraw();
  thickness_circle.clear();
  thickness_circle.ellipse(mouseX, mouseY, strokeWeight, strokeWeight);
  thickness_circle.endDraw();

  image(thickness_circle, 0, 0);
}

Upvotes: 1

Related Questions