How to Retrieve Rectangle Positions on a Canvas

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 :)

Answer №1

To determine the updated position in relation to the original transformation matrix, utilize the DOMMatrix retrieved from ctx.getTransform() for transforming your initial coordinates. This can be achieved through its transformPoint() method:

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
ctx.translate(10, 75);
ctx.scale(2.4, 1.3);
ctx.rotate(Math.PI / 3);
ctx.translate(-10, -75);

ctx.fillRect(30, 30, 20, 20);

const mat = ctx.getTransform();
const point = { x: 30, y: 30 }; // Coordinates of top left corner
const trans = mat.transformPoint(point);
console.log(trans);
// Adjust red rectangle to new position
document.querySelector(".witness").style.top = `${trans.y}px`
document.querySelector(".witness").style.left = `${trans.x}px`
.witness, canvas {
  position: absolute;
  top: 0;
  left: 0;
}
.witness {
  width: 10px;
  height: 10px;
  translate: -5px -5px; /* Centered positioning */
  background: #FF0000AA;
}
<canvas></canvas>
<div class=witness></div>

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

"Exploring Angular 9: A guide to retrieving form data with an array of objects [Revised as of July 29th, 2020

I am encountering an issue with my Angular 9 form code. I am getting the error "ERROR TypeError: Cannot read property 'mobile_number' of undefined" and I need help in resolving this problem. <form (ngSubmit)="processForm()"> & ...

Restrictive discriminated union via function argument

I am in possession of a shop that organizes a variety of types based on their IDs interface Dog { type: "dog"; woofs: string; } interface Cat { type: "cat"; meows: string; } type Pet = Dog | Cat; type AnimalState = Record<string, Pet ...

Exploring Angular 6: Step-by-step guide to nesting objects within objects

I have a problem with posting data to my API built with Spring Boot. workflow : any = { name : "CMD1", items : [ { name : "work1", content : null }, { name : "work2", content : null } ] } In Angular, I created a ...

Error in Angular Typescript: Utilize the return value of "filter" function to fix the issue

Encountering a sonar error: The return value of "filter" should be utilized Despite using the filter, the error persists. What might be the issue here? array.filter(item => { item.value.split(' ').forEach( i => { if ( doSomething(i) ...

Unable to append item to document object model

Within my component, I have a snippet of code: isLoaded($event) { console.log($event); this.visible = $event; console.log(this.visible); this.onClick(); } onClick() { this.listImage = this.imageService.getImage(); let span = docu ...

Learning to handle data fetching and looping in NextJs

I'm facing an issue with fetching data through a loop in getStaticProps. The array ends up empty due to asynchronous code. If I pass the ID array and implement the logic within the React component, it works fine. Should I continue using the component ...

Error in Angular compiler-cli: The namespace 'ts' does not contain the exported member 'ResolutionMode'

Currently working on a web application using Angular 16 in Webstorm. The application is still in the pre-release stage, with only minimal functionality completed so far. While editing with ng serve running to test changes as they were made, encountered an ...

Encountering an issue with TypeScript after applying a wrapper to a Material-UI button - specifically, the error message states that the type '{ children: string; color: "light-green"; }' is lacking certain properties

I'm currently working on creating wrapped components using MUI (@material-tailwind/react) within the environment of Next.js 14. However, I've run into a typescript error specifically in the MaterialButton component. Type '{ children: string; ...

Using Angular, you can effortlessly inject elements into the editable div from any location on the page

Currently, I am working on developing an HTML interface that allows users to input text and send it as a notification to our mobile application. However, I am encountering challenges with the text and dynamically inserted elements using Angular 5; The te ...

Definition of a generator in Typescript using an interface

I am in the process of converting some code to TypeScript which currently looks like this: const saga = function* (action) { yield put({ type: actions.SUCCESS, payload: action.payload }); }; const sagaWatche ...

Type definition for Vuex store functionality

Working on creating a versatile type to provide typing hints for mutations in Vuex. After reading an inspiring article on Vuex + TypeScript, I decided to develop something more generic. Here is what I came up with: export type MutationType<S, P, K exten ...

Testing a React component that uses useParams: A step-by-step guide

I've been working on creating a BBS App using TypeScript, React, React Router, and React Testing Library. However, I've encountered an issue where a component utilizing useParams is not passing a test. Interestingly, it seems to be working correc ...

What could have caused the sudden halt of fetching on all server branches in the backend?

Following a code refactor on a separate branch, the fetch function ceases to work in any branch despite everything else functioning correctly. The error message reads: ...server/KE/utils.ts:44 const response = await fetch( ^ ReferenceError ...

Can someone assist me in creating mongoose models?

Currently, I am focused on managing products and categories These are the two types I have created: type Category = { parent: Category | null; // Is this acceptable? name: String; }; type Product = { categories: Category[]; name: String; ...

What is the best way to ensure that the base class Resolver finishes before allowing the derived class Resolver to execute?

I have a situation where many of my resolvers (@angular/router Resolve) need to query the same data before executing their route-specific queries. To streamline this process, I want to create a resolver base class that resolves the initial data before the ...

Guide to transforming an IdentityMap<String, dynamic> into a UInt8List

I have a cloud function that generates a JavaScript Buffer object, which looks something like this: functions .region("europe-west2") .runWith({ timeoutSeconds: 20, memory: "128MB", }) .https .onCall(asyn ...

Utilizing a loaded variable containing data from an external API request within the useEffect() hook of a React component

Essentially, I have an API request within the useEffect() hook to fetch all "notebooks" before the page renders, allowing me to display them. useEffect(() => { getIdToken().then((idToken) => { const data = getAllNotebooks(idToken); ...

Converting TypeScript into JavaScript files within an ASP.NET SPA application

As I work on my current project using ASP.NET spa and Vue.js, I have been serving the dist folder from the Vue.js client app statically. This dist folder contains the compiled result of the client app's /src directory, where all .Vue and .ts files are ...

Using Angular to Bind Checkbox Value in Typescript

I have a challenge of creating a quiz where a card is displayed with 4 questions structured like this: <div class="col-md-6"> <div class="option" id="Answer1"> <label class="Answer1"> <input value= "Answer1" type="checkbox ...

You are not able to use *ngIf nested within *ngFor in Angular 2

I am currently working in Angular2 and trying to bind data from a service. The issue I am facing is that when loading the data, I need to filter it by an ID. Here is what I am trying to achieve: <md-radio-button *ngFor="#item of items_list" ...