using scale in to zoom in and zoom out an rectangle Object.

I have a rectangle object where I need to zoom in and zoom out i.e., scaling the object.

Here is my code for that. var y; function setup() { createCanvas(600,400); rectMode(CENTER); y = 400; } function draw(){ background(0); fill(0,0,255); translate(width/2,y); if(y%2 == 0){ scale(1.5); } rect(0,y,200,20); y--; if(y < 0){ y = height; } }

But for weird reasons,there are two rectangle objects on the screen. Am I missing any point here? Or it is suppose to work like this?

alpha.editor.p5js.org/zusamarehan/sketches/Syi5Ufvxf

Here is a link where you can check the code and the output.

Answers

  • edited November 2017

    You have one rectangle, but it is being drawn at different sizes half the time. Specifically, when it's y position is divisible by 2, it gets scaled up. This is also why they both seem to flicker.

    The easiest way to show you this is to not scale based on any condition, but to instead make how much the rectangle is scaled up depend on the position of the mouse:

    var y;
    function setup() {
      createCanvas(600,400);
      rectMode(CENTER);
        y = 400;
    }
    function draw(){
        background(0);
        fill(0,0,255);
        translate(width/2,y);
        scale(map(mouseX,0,width,0.5,3));
        rect(0,y,200,20);
        y--;
        if(y < 0){
            y = height;
        }
    }
    

    Here I am using the mouse's X position to determine how much to scale by. If the mouse is at the left side of the screen, I scale down to half the normal size. If it is at the right edge, it scales up to three times the normal size. And there is a smooth transition between these two extremes.

  • But I still don't understand why there is two rectangles. I have only one rect() in the code.

    What makes it to duplicate it?

  • edited November 2017 Answer ✓

    @UsamaRehan --

    There aren't two rectangles. There is one rectangle that is vibrating.

    Here: try dropping the frameRate from the default (60fps) to two frames per second, and see what is happening when you watch in slow-motion:

    function setup() {
      createCanvas(600, 400);
      rectMode(CENTER);
      y = 150;
      frameRate(2);
    }
    

    See? Just one rectangle, bouncing back and forth "if(y%2 == 0)"

  • @hermydouglass

    Thank you for the explanation. I understand now.

Sign In or Register to comment.