skip to Main Content

I have a requirement where on clicking on a human body image I have to display a circle on that body part. I’m able to render the circle but not on the body part. And if I scroll and click on the same body part the circle renders in a different place. Here’s the example.

CodeSandBox

This also creates an issue with different screen sizes.

2

Answers


  1. I made some dits to your code, you can cehck if this works for you.

    Code Sandbox

    Login or Signup to reply.
  2. event.target.getBoundingClientRect() returns the size of an element and its position relative to the viewport. And event.target.naturalWidth and event.target.naturalHeight provides the natural width and height of <img/> (original pixels wide)

    so you can calculate absolute position of circle which will be placed on image by event.target.natural(width or height) / rect.(width or height)

    Example

    import React, { useState } from "react";
    import "./styles.css";
    
    import human_body from "./images/human body.png";
    import circle from "./images/hover-circle.png";
    
    export default function App() {
      const [circlePosition, setCirclePosition] = useState({ left: 0, top: 0 });
    
      const imgClick = (event: any) => {
        const rect = event.target.getBoundingClientRect();
        const scaleX = event.target.naturalWidth / rect.width;
        const scaleY = event.target.naturalHeight / rect.height;
        const left = event.nativeEvent.offsetX * scaleX - 20; 
        const top = event.nativeEvent.offsetY * scaleY - 20;
        setCirclePosition({ left, top });
      };
    
      return (
        <div className="App">
          <div>
            {circlePosition.left > 0 && circlePosition.top > 0 && (
              <img
                src={circle}
                alt="hover-body"
                style={{
                  width: 50,
                  height: 50,
                  left: circlePosition.left,
                  top: circlePosition.top,
                  position: "absolute",
                  zIndex: 10
                }}
              />
            )}
            <img id="human_body" onClick={imgClick} src={human_body} alt="body" />
          </div>
        </div>
      );
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search