I have searched for a solution to this question multiple times, but none of the answers I came across seem to work for me. Currently, I am able to allow the user to scale an image with a simple scale(factor)
call. However, now I am attempting to implement scaling based on the mouse pointer location, which is proving to be more challenging. Although I can create a zoom effect centered around the pointer, the issue arises when the mouse moves and the image follows suit, as demonstrated in this example:
I tried multiplying the coordinates of the second translation by the scale factor, but that did not yield the desired result. What could I be overlooking?
let sf = 1; // scaleFactor
let x = 0; // pan X
let y = 0; // pan Y
let mx, my; // mouse coords;
function setup() {
createCanvas(400, 400);
}
function draw() {
mx = mouseX;
my = mouseY;
background(255);
translate(mx, my);
scale(sf);
translate(-mx, -my);
translate();
rect(100, 100, 100, 100);
if (mouseIsPressed) {
x -= pmouseX - mouseX;
y -= pmouseY - mouseY;
}
}
window.addEventListener("wheel", function(e) {
if (e.deltaY > 0)
sf *= 1.05;
else
sf *= 0.95;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>