How to use redraw().

edited February 2016 in How To...

Hello. I want a rectangle to follow a certain path but leave no trace behind it without having to redraw background in every cycle. Is it possible? Thanks

Tagged:

Answers

  • Its not possible because you would have to erase the old rectangle before drawing it in its new position.

    The redraw() method will not help you to do this either.

  • redraw() forces a frame to be drawn when you are using noLoop() to stop the usual function of draw().

    maybe an offscreen buffer will suit your needs:
    https://processing.org/reference/createGraphics_.html

  • int sx, sy;
    
    void setup()
    {
      background(60);
      size(600,600);
      frameRate(5);
      sx = 10;
      sy = 10;
      noFill();
    }
    
    void draw()
    {
      if(sx < 50)
      {
        if(frameCount % 2 == 0)
        {
          // cancel rect
          strokeWeight(2);
          stroke(60);
          rect(sx, sy, 30, 30);
        }
        else
        {
          sx += 5;
          strokeWeight(1);
          stroke(0);
          // draw new rect      
          rect(sx, sy, 30, 30);
        }
      }  
    }
    
  • Answer ✓

    @cameyo nice try :) but that is not the way to do it because the rectangle is only drawn every other frame so it flashes.

    The code below shows one way of doing it but erasing the rectangle clears anything underneath the old position. In this example you can see it eats through the yellow ellipse :(

    Effectively it is the same as using background() but only for a part of the display.

    int sx, sy;
    
    void setup() {
      size(600, 600);
      background(128);
      sx = 10;
      sy = 100;
      fill(255,255,0);
      noStroke();
      ellipse(width/2, sy, 50, height);
      noFill();
    }
    
    void draw() {
      // clear rect
      strokeWeight(2);
      stroke(128);
      fill(128);
      rect(sx, sy, 30, 30);
      // Move rect
      sx += 1;
      sx %= width; // wrap movment
      //draw rect
      strokeWeight(1);
      stroke(255, 0, 0);
      fill(255);
      // draw new rect      
      rect(sx, sy, 30, 30);
    }
    
  • edited February 2016

    @quark the use of frameRate(5) and if (frameCount) was intentional to show the method. No more flashing without :\">
    Another bad @-) idea is to grab the canvas image(s) who "eats" the rect along the path and redraw them after.

  • Why don't you want to redraw the background every frame? It's one line of code and it doesn't bring the fps down...

Sign In or Register to comment.