Zooming and moving canvas

So I tried implementing a zoom and drag function but its not behaving as expected, I can about the steps to get it to behave like I want it
here is a great example of what I was expecting: Desmos | Graphing Calculator
on here the four points can be dragged around with the mouse and when you zoom (scroll) in and out their positions change relatively to the mouse.
here is my approach https://openprocessing.org/sketch/1162013, I got somewhere but I can figure out what do do next
any advice or guides to help implement the correct behavior? and what I am missing

Maybe How to zoom into an image (but at a certain point) with scale

If you want something simple, you can use the translate() and scale() functions.

You can track how much you moved with some event from the mouse like you did but with extra variables to have a bit more control on how it all works:

let dx, dy;
let curDx, curDy;
let pmx, pmy;
let isTranslating;
let scaleFactor;

function setup() {
  createCanvas(600, 600);
  dx = 0;
  dy = 0;
  scaleFactor = 1;
}

function draw() {
  background(40);
  
  if(isTranslating) {
    curDx = mouseX - pmx;
    curDy = mouseY - pmy;
  } else {
    curDx = 0;
    curDy = 0;
  }
  
  translate(dx + curDx, dy + curDy);
  scale(scaleFactor);
  
  noStroke();
  color(220);
  ellipse(100, 100, 20);
  ellipse(200, 100, 20);
  ellipse(200, 200, 20);
  ellipse(100, 200, 20);
}

function mousePressed() {
  pmx = mouseX;
  pmy = mouseY;
  isTranslating = true;
}

function mouseReleased() {
  dx += (mouseX - pmx);
  dy += (mouseY - pmy);
  isTranslating = false;
}

function mouseWheel(event) {
  print(event.delta);
  scaleFactor += event.delta * 0.001;
  if (scaleFactor < 0.01) {
    scaleFactor = 0.1;
  }
}

If you want something more robust, the idea will remain the same but you may want to perform extra check, have special class to handle the way your objects are drawn and so on…

For example, if you want to draw a line, it is easy you call line(x1, y1, x2, y2) and it would work as long as the limit of the line are outside of the drawing window. But let’s say you scale down or move really really high in you canvas, then the line will maybe not be drawn anymore because your x1, y1, x2, y2 can be so big… In that case you would want a special class that handle the drawing of that line based on the current viewing region. You might also want to create a Region class to keep track of which region is displayed.

1 Like