I am facing a specific scenario: I have created a rectangle on the canvas. By using the mouse wheel, the user can zoom in and out based on the position of the mouse cursor. Below is the TypeScript code for zooming:
this.context?.clearRect(
0,
0,
this.width * this.CELL_SIZE,
this.height * this.CELL_SIZE
);
if (event.deltaY == -100) {
this.context?.translate(event.offsetX, event.offsetY);
this.context?.scale(1.05, 1.05);
this.context?.translate(-event.offsetX, -event.offsetY);
} else if (event.deltaY == 100) {
this.context?.translate(event.offsetX, event.offsetY);
this.context?.scale(0.95, 0.95);
this.context?.translate(-event.offsetX, -event.offsetY);
}
this.draw_Grid();
My issue arises when I manipulate the context with scaling and translation, causing the position of the rectangle to shift. Is there a method to determine the new coordinates of the rectangle? I need to identify the updated x and y starting points of the shape.
Despite conducting extensive research, I have not come across a satisfactory answer online.
UPDATE:
I came across this post, where it demonstrates detecting the distance of the shape from the canvas border using mouse movement. However, my goal in the code is to automatically compute the distance of the shape after translating and zooming the context, rather than relying on the mouse move event.
Here is a screenshot that may help clarify what I aim to achieve:
https://i.sstatic.net/EGSEg.png
Any pointers or solutions would be greatly appreciated.
Thank you :)