Search code examples
javascriptdrawingmouseeventprocessing

Drawing with an easing mouse in Processing 3.0


I'm trying to create a smooth drawing tool with the help of a line- like [this][1]. I got the basics done but my code has several issues.

Here's the code of the sketch I'm working on:

void setup() {
  frameRate(60);
  size(640, 360);
  fill(255, 126);

  }

void draw() {
  s1.display(mouseX, mouseY);
  s1.update(mouseX, mouseY);
  }




  void update(float targetX, float targetY) {
    x += vx;
    y += vy; 
  }

  void display(float nx, float ny) {
   if (mousePressed == true) {
    
    background(0);
      
    stroke(40, 255, 150);
    line(x, y, nx, ny);

    
    noStroke();
    fill(255, 130, 40);
    ellipse(x, y, 5, 5);
   
  } else  {
   background(0);
   }
  }
}

The problem is, when I don't set the background to a certain color (here 0; which is black) the guide string (green line and the orange dot) will draw itself onto canvas as well. However, I like to use them only as a guide, as a helper. So, what should I do to get lines drawn according to the orange dot without drawing the string line?


Solution

  • Even if you have a very high framerate, your mouse doesn't actually pass through every pixel on the screen. It moves by multiple pixels at a time, depending on how fast you're moving your mouse. So between frames, the mouse can move from one position to another without moving through every position between those two positions.

    To get around this, instead of drawing an ellipse at the current position, you could draw lines from the previous position to the current position.

    In your Spring2D class, you have to keep track of the previous position. You could just use two variables:

    float previousX;
    float previousY;
    

    You need to update these variables in your update() function.

    previousX = x;
    previousY = y;
    

    Then in your display() function, you need to use these variables to draw a line from the previous point to the current point:

    strokeWeight(radius*2);
    line(previousX, previousY, x, y);
    

    This will prevent the spaces between points you're seeing.

    If you have any other questions, please post them as separate questions in their own posts. Try to narrow your problem down to a specific question about a specific line of code, or as few lines as possible. It's hard to answer general "how do I do this" type questions. Stack Overflow is designed for more specific "I tried X, expected Y, but got Z instead" type questions. You'll have much better luck (and faster response times) if you try to be more specific. Good luck, this seems like an interesting project.