How do I zoom in using p5?

I think I can use mouseWheel() but need help getting started.

Also, first time here. I was wondering if topics here is mostly processing/java or p5js.

Tagged:

Answers

  • There is more java posts than p5.js but you can certainly ask any question about either of them.

    Did you check the reference: https://p5js.org/reference/#/p5/mouseWheel

    Kf

  • edited May 2017 Answer ✓

    @banana --

    Depending on what you are trying to do, you might approach zooming by:

    1. centering on the sketch / canvas using translate(width/2, height/2)
    2. use scale(zoom) to set the zoom level, with 1.0 being normal.
    3. draw things based on 0,0 at the middle of the screen.

    This approach works the same in both p5.js and Processing(Java). Here is a simple example of a zooming sketch in p5.js -- it is almost identical to the Processing(Java) equivalent. There is no user input -- it just keeps zooming every time the screen redraws:

    var zoom = 1.00;
    
    function setup() {
      createCanvas(500,500);
      rectMode(CENTER);
    }
    function draw() {
      background(237, 34, 93);
      translate(width/2,height/2);
      fill(0);
      scale(zoom);
      rect(0, 0, 50, 50);
      zoom += 0.01
    }
    

    ...and here is a slightly more complex setup in which mouseWheel() controls the zoom variable:

    var zoom = 1.00;
    var zMin = 0.05;
    var zMax = 9.00;
    var sensativity = 0.005;
    
    function setup() {
      createCanvas(500,500);
      rectMode(CENTER);
    }
    function draw() {
      background(237, 34, 93);
      translate(width/2,height/2);
      fill(0);
      scale(zoom);
      rect(0, 0, 50, 50);
    }
    
    function mouseWheel(event) {
      zoom += sensativity * event.delta;
      zoom = constrain(zoom, zMin, zMax);
      //uncomment to block page scrolling
      return false;
    }
    

    For more, see:

    If you are trying to do other kinds of zooming, such as zooming on whatever the current mouse location is, then the basics are the same but it gets a bit more complex. See:

Sign In or Register to comment.