Zooming in on specific point. (Translate and scale)

So I’m fairly new to graphical programming and I’m stuck at something that I’m guessing has a simple solution.

I want to make some lines out of points and then translate and scale so that my lines will be visible no matter where I decided to put the points. If there is any kind “showDrawn” function that does this for then that’d be great.
I didn’t find that however so I had to resort to trying it myself. First I found the average x and y coordinates and transformed so they were my center point:

translate((width/2)-avgx, (height/2)-avgy);

Everything good so far.
Then I wanted to scale it to fit my screen, the problem is that scaling offsets the translation, my center points seem to veer off towards the bottom right corner when I try to zoom in.
Is there a way to scale while keeping the center I translated to in the center?

Here’s my code:

looks like you first scale and then translate,
better turn that around

s̶h̶o̶u̶l̶d̶n̶’̶t̶ ̶y̶o̶u̶ ̶b̶e̶ ̶u̶s̶i̶n̶g̶ ̶p̶u̶s̶h̶(̶)̶ ̶a̶n̶d̶ ̶p̶o̶p̶(̶)̶ ̶s̶o̶ ̶y̶o̶u̶r̶ ̶t̶r̶a̶n̶s̶l̶a̶t̶i̶o̶n̶s̶ ̶d̶o̶n̶’̶t̶ ̶a̶c̶c̶u̶m̶u̶l̶a̶t̶e̶?̶ ̶a̶l̶s̶o̶ ̶w̶h̶a̶t̶ ̶k̶l̶l̶ ̶s̶a̶i̶d̶ ̶t̶o̶o̶.̶

edit scratch that, what was i thinking. i believe you actually want something like this

Hey There !

Do you mean you want the lines always I’m the middle of the screen ?

How about :

int cameraX , cameraY
cameraX = posX - width/2
cameraY = posY - width/2

This inspired me.
I have come across this before and like to “scale” the plot that I draw and not use scale();
Not p5.js but an example.

Example with embellishments (translating, scaling and some)

long time, timeLast;
float scale = 1;
float theta;
float x,  y;

void setup()
  size(1000, 1000);  
  time = 1000;
  timeLast = millis();
void draw()
  translate(width/2, height/2);

// Rotates in a circle  
  theta += TAU/500;
  x = 150*sin(3*theta);
  y = 150*cos(3*theta);
  translate(x, y);
//  if (timeLast + time < millis())  //Remove comment to see this effect
    timeLast = millis();  
    //scale = 50;
    // modulating scale
    scale = 10*(sin(theta)+1);
    for(float x = 0; x < TAU; x+= TAU/(scale*10) )
      float y = 5*sin(x);
      stroke(255, 255, 0);
      line (0, -10*scale, 0, +10*scale);
      line (0, 0, 10*scale, 0);

yes. you need to break up your translate into two stages, and do the scaling between them, while the center of your coordinate system is still at 0,0.

  1. translate(width/2, height/2);
  2. scale(amt)
  3. translate(-avgx, -avgy);

For a recent related discussion, see:

1 Like