Utilizing React and Next.js to accurately position and assign tags to image coordinates

I am currently working on capturing the coordinates of an image in order to add tags to it. While I can successfully add a tag, the issue arises when I resize the browser - the tag does not adjust to the corresponding position of the image. As the browser expands or scales down, the image maintains its aspect ratio, but the tag remains static relative to the current viewport position and not the actual location of the image. Although, if I scroll, the tag does eventually move to its correct area, but only after scrolling takes place.

const initialPosition = {
  x: "",
  y: "",
};
const MediaPage = ({ user, mediaId }) => {
  const [tagPosition, setTagPosition] = useState(initialPosition);

  const imageWrapRef = createRef();

  const handleTagClick = (e) => {
    const { left, top } = imageWrapRef.current.getBoundingClientRect();
    const x = e.pageX - left;
    const y = e.pageY - top;
    setTagPosition((prev) => ({ ...prev, x, y }));
  };

  return (
    <div
      onClick={(e) => handleTagClick(e)}
      ref={imageWrapRef}
    >
      <div
        style={{
          left: `${tagPosition.x}px`,
          top: `${tagPosition.y}px`,
          zIndex: 2,
          padding: 10,
          position: "absolute",
       }}
      >
        1
      </div>
      <Image
        onLoad={handleLoadingComplete}
        className="w-full"
        alt=""
        src="URL"
        layout="responsive"
        width={700}
        height={800}
      />
    </div>
}

In essence, my goal is to enable users to click on an image and have a tag appear at the precise position of the image, regardless of any scaling that may occur.

Answer №1

Successfully resolved the issue with a simple solution. I adjusted the parent div to have a relative position, and then updated the x and y values as percentages.

const x = ((e.clientX - left) / width) * 100;
const y = ((e.clientY - top) / height) * 100;

After that, in the styling:

left: `${tagPosition.x}%`,
top: `${tagPosition.y}%`,

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

How come I am unable to expand a collection of objects using Zustand?

I am currently utilizing Zustand in a TypeScript Next.js application. Strangely, whenever I attempt to loop through my state object, I encounter a runtime error message. The structure of the damaged zone object for my car is as follows: const damagedZones ...

Javascript function for repopulating multiple rows using getElementById

Fetching information from a web form using the following code: echo "<tr>"; echo "<td>" . $row['platform_name'] . "</td>"; echo "<td><input name='id[]' type='hidden' value='".$row['id&a ...

Concealing the sub-menu items of a parent category upon clicking on a different parent category

I'm having trouble hiding the child menu of the current parent when clicking on another parent. I want to hide the child menu of the previous parent when a new parent is clicked. Right now, my code is showing the children of both the previous and curr ...

Dynamically inject components onto a React page

I am trying to display 10 elements in a column, such as 1,2,3..., with a timeout of 1 second. However, I am facing difficulties implementing a loop to print messages in my code. I attempted using innerHTML but I feel like it might not be the correct appr ...

Tips for incorporating icons into your navigation drawer

I have successfully added Icons to a custom drawer navigation, but I am curious if it is possible to directly include icons in </Drawer.Navigator> or <Drawer.Screen/> without the need for additional customization? Below is an example of my cur ...

Building on the Vuejs3 and Vuex4 framework, create a conditional rendering feature that triggers upon

I have a unique setup where custom objects are used to hold child objects full of data. The child objects start with null values for all properties, allowing them to be filled with data from remote sources when referenced. This results in a lazy-loading sy ...

What's the best way to continuously increase my counter using the data received from my AJAX calls?

On the final step of my first ajax project, I have implemented a thumbs-up icon that increments a column in the database when clicked. The following code achieves this: Viewable Page HTML and jQuery: <div id="comment_id">+1</div> <div id=" ...

Stylish News Carousel using CSS and HTML

I've been working on creating a news slider for my website, but I'm encountering an issue. Despite completing the HTML and CSS, I'm struggling to make the 'showcase' rotate using JQuery. I've tried various guides and instructi ...

Encountering a 400 status error while trying to fetch data using React Hook Form

My custom book search application allows users to input a query, which then displays the response data. After following the example for schema validation from the React Hook Form documentation, I encountered an Error: Request failed with status code 400. ...

Ways to evaluate two sentences based solely on the spacing in their dynamic sections

I am tasked with comparing two sentences. The first sentence is stored in a database and looks like this: var text1 = "Dear {#dynamic#} {#dynamic#} Welcome to MAX private ltd" The second sentence, which comes from the customer, is as follows: &q ...

Ui Bootstrap (angularjs) sidebar is not functioning properly

I am encountering an issue with a sidenav that I am in the process of creating for one of my projects. The goal is to develop a side menu that shifts the content to the right when opened and returns it to the left when closed, essentially functioning as a ...

Highlighting JavaScript code with React Syntax Highlighter exclusively

I've been struggling to highlight Ruby code, but it seems like no matter what I do, it keeps highlighting JavaScript instead. It's frustrating because I can't seem to get it right. import React from "react"; import atom from "node_module ...

Tips for preventing the addition of a comma at the end of a foreach loop item

Is there a way to prevent adding a comma after the last element, like in the case of ABC1 where a comma should not be added? https://i.sstatic.net/12lNu.png You can find the code sample here >>>Sample methods:{ test(){ this.Aarray.fo ...

Incorporating Bootstrap Content: A Guide to Including a PHP File within Another PHP File

I am encountering an issue when trying to import a PHP file containing my navigation bar into another PHP file. Here's the code for the navigation file: <?php echo " <html> <head> <nav class = "navbar navbar-default navbar-fixed-top ...

Using a CSS style to modify a class based on another class at the same level in the hierarchy

I am working with a jQuery carousel that is adding an 'active' class to images within a div. Within the same div, there is also a span with a 'fade' class that has a CSS style of opacity: 0. Is there a way to change the CSS style of the ...

Looking for a JavaScript or jQuery library that can effectively translate XPath into a user-friendly CSS3 format for easy selection in

Is there a way to transform an XPath expression such as /html/body/div[3]/ul/li[1]/a[5] html > body > div[3] > ul > li[1] > a[5] I am aware that CSS3 selectors do not support indexing....what alternative approach should I take? ...

Steps to invoking an asynchronous function within another async function

Is there a way for me to transform the following function into an Async function? I need to invoke several methods based on the result of the function call when isMaxAttemptExceeded has been fully executed. let isMaxAttemptExceeded = async () =&g ...

Is there a way to load just one model in three.js without loading multiple models simultaneously?

I've been working on a project involving a three.js scene where items are added based on the number of existing items, and a problem I've encountered is that when a user selects "Work at Height", two people are added to the scene. Despite being s ...

Safari and mobile browsers do not support animation functionality

My animation works flawlessly in Chrome, but it's not functioning properly on Safari. Quite odd, right? Here is the code snippet: <header> <div class="ripple-1"></div> <div class="ripple-2"></div> ...

Automatically Parse Value by 100 in Angular FormGroup

Within my Angular form group, I have 3 fields. One of these fields serves as a tool for the user, automatically calculating the value based on another field. Essentially, when a user inputs a number, the tool field displays that value divided by 100. Here ...