Making a Zoom effect using p5.js

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>

Answer â„–1

The challenge arises when you need to apply the scale incrementally.

When applying a single scale (s1) from a center point (x1, y1), the calculation is:

model = translate(x1, y1) * scale(s1) * translate(-x1, -y1) 

If you wish to incorporate a new scale (s2) around another center point (x2, y2), this formula should be used:

model = translate(x2, y2) * scale(s2) * translate(-x2, -y2) * currentMode;

Where currentMode represents the previous transformation involving scaling.
It's crucial not to confuse this with:

model = translate(x1+x2, y1+y2) * scale(s1*s2) * translate(-(x1+x2), -(y1+y2))

A single scale factor (sf) applied from the center point (mx, my) can be calculated as follows:

let tx = mx - sf * mx;
let ty = my - sf * my;
translate(tx, ty);
scale(sf);

To perform multiple consecutive operations like these, it is advisable to implement a 3x3 Matrix multiplication method:

function matMult3x3(A, B) {
    C = [0, 0, 0, 0, 0, 0];
    for (let k = 0; k < 3; ++ k) {
        for (let j = 0; j < 3; ++ j) {
            C[k*3+j] = A[0*3+j] * B[k*3+0] + A[1*3+j] * B[k*3+1] + A[2*3+j] * B[k*3+2];
        }
    }
    return C;
}

The scale transformation around a central point can be represented by the following 3x3 matrix:

m = [ sf, 0,  0, 
      0,  sf, 0,
      tx, ty, 1];

This setup leads to the handling of mouse wheel events as shown below:

window.addEventListener("wheel", function(e) {

    let mx = mouseX;
    let my = mouseY;

    let s = e.deltaY > 0 ? 1.05 : 0.95;

    let x = mx - s * mx;
    let y = my - s * my;
    m = matMult3x3([s,0,0, 0,s,0, x,y,1], [sf,0,0, 0,sf,0, tx,ty,1]);
    sf = m[0];
    tx = m[6];
    ty = m[7];
} );

To simplify the above code further:

window.addEventListener("wheel", function(e) {

    let mx = mouseX;
    let my = mouseY;

    let s = e.deltaY > 0 ? 1.05 : 0.95;

    sf = sf * s;
    tx = mx - s * mx + s * tx;
    ty = my - s * my + s * ty;
} );

Check out the example provided where the rectangle can be scaled from the mouse cursor position using either the mouse wheel or the +/- keys:

let sf = 1, tx = 0, ty = 0;

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(127);
  translate(tx, ty);
  scale(sf);
  rect(100, 100, 100, 100);
}

function applyScale(s) {
    sf = sf * s;
    tx = mouseX * (1-s) + tx * s;
    ty = mouseY * (1-s) + ty * s;
}

window.addEventListener("wheel", function(e) {
    applyScale(e.deltaY > 0 ? 1.05 : 0.95);
} );

function keyPressed() {
    if (key == '-') {
        applyScale(0.95);
    } else if (key == '+') {
        applyScale(1.05);
    } 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Change the className of an element in React upon clicking it

I just finished developing a menu bar using ReactJS with some basic routing features. Here is the JSX code for the component: class TopBar extends Component { state = { menus: [{id:0,menu:"Home"}, {id:1,menu:"Contact"}, {id:2,menu:"About"}] } a ...

Leveraging angular.forEach for JSON Iteration

In my app and controller, I am working on creating a "flow chart style" question and answer system. To keep track of the current question and answer, I am using variables like $scope.ActiveQuestion and an array named $scope.ActiveAnswers. I am struggling ...

Error message "Undefined error encountered when attempting to display an array of objects using jQuery and PHP through AJAX on the console"

While trying to parse a JSON using jQuery and AJAX, I encountered an issue where some objects in the Array, like the SUM(amountbet) object, are showing up as "undefined" in the console. The image above depicts the SUM(amountbet) object appearing ...

Using Node.js with the express framework for requiring and posting data

main.js: var mainApp = express(); require('./new_file.js')(mainApp); new_file.js: mainApp.post('/example', function(req, res) { console.log(true); }); Error message: mainApp is not defined. Looking for a solution to access exp ...

I am seeking assistance with generating a printed list from the database

Struggling for two full days to successfully print a simple list from the database. Take a look at the current state of the code: function CategoriesTable() { const [isLoading, setLoading] = useState(true); let item_list = []; let print_list; useEffect(( ...

Search through a JSON array to find a specific element and retrieve the entire array linked to that element

Recently, I've been working with a json array that dynamically increases based on user input. Here's a snippet of the json code I'm dealing with: [{"scheduleid":"randomid","datestart":"2020-06-30",&quo ...

I am facing difficulties accessing an element within a controller in Angular

Struggling to access an element inside an AngularJS controller, I attempted the following: var imageInput = document.getElementById("myImage"); Unfortunately, this approach was unsuccessful as the element returned null. Curiously, when placing the statem ...

ng-repeat failing to display the final two divs

I'm having trouble with the following code. The second to last div inside the ng-repeat is not being rendered at all, and the last div is getting thrown out of the ng-repeat. I can't figure out what's wrong with this code. Can anyone spot th ...

Implementing specifications throughout the entire nodejs route

In my Nodejs app, I have a RESTful API where I need to check for a user's role before sending a response with data or 404 error. apiRouter.route('/users') .get(function (req, res) { var currentUser = req.decoded; if(curr ...

Utilize the power of AJAX for efficiently sorting search results retrieved from MySQL

I'm in the process of designing a flight search page. The initial page contains a form, and when the submit button is clicked, the search results are displayed on the second page. Here's the link to the first page: To test it out, please follow ...

Obtain the current name of the Material UI breakpoint

Looking for a MUI function called MaterialUIGiveMeCurrentBreakPointName that can help me execute an action in a component like so: const currentBreakPointName = MaterialUIGiveMeCurrentBreakPointName() if(currentBreakPointName === 'myCustomBreakPointN ...

What is the best method for arranging checkboxes in a vertical line alongside a list of items for uniform alignment?

Trying to come up with a solution to include checkboxes for each item in the list, maintaining even vertical alignment. The goal is to have the checkboxes in a straight vertical line rather than a zigzag pattern. Coffee Nestle ...

What steps can I take to prevent encountering a Typescript Error (TS2345) within the StatePropertyAccessor of the Microsoft Bot Framework while setting a property?

During the process of constructing a bot in Typescript, I encountered TS2345 error with Typescript version 3.7.2. This error is causing issues when attempting to create properties dynamically, even if they are undefined, or referencing them in the statePro ...

Draggable resizing of the Accordion component in React.js using Material-UI

In the visual representation, there are two Accordions—one positioned on the left (30%) and the other on the right (70%). Upon clicking the button, the right accordion disappears, while the one on the left expands to cover the full width (100%). A featu ...

How can we bring in a function into a Vue component?

I'm currently facing an issue with importing a single function into my Vue component. To tackle this problem, I separated the function into its own js file: randomId.js: exports.randomId = () => //My function ... Within my Vue component, I attem ...

Prevent the ability to drag and drop within specific div elements

Having trouble disabling the sortable function when the ui ID is set to "comp". Can't figure out what's going wrong, hoping for some assistance here. $(".sort").sortable({ // start sortable connectWith: ".sort", receive: function ...

The service worker is attempting to access outdated information from the cached script

Within my project, I implement the loading of JSON files asynchronously using import().then. At times, a situation arises where new content is accessible but has not yet been applied, causing the old cached script bundle to attempt loading the JSON files ...

How to show the current week using React Native

Looking to show the current week of the month in a specific format using react-native: (Week 2: 05.10 - 11.10) (for example, displaying week 2 of the current month) Any ideas on how to make this happen? I'm aware of packages like momentjs that can ...

Trouble with AngularJS: Updates not reflecting when adding new items to an Array

I am facing a persistent issue that I have been unable to resolve, despite researching similar problems on StackOverflow. My current project involves building an application with the MEAN stack. However, I am encountering difficulties when trying to dynam ...

Interact with SOAP web service using an Angular application

I have experience consuming Restful services in my Angular applications, but recently a client provided me with a different type of web service at this URL: http://123.618.196.10/WCFTicket/Service1.svc?wsdl. Can I integrate this into an Angular app? I am ...