meks285
meks285

Reputation: 29

How to get correct Image Coordinates in Ionic React

I am currently working on a simple Ionic React project; The mobile app is used to mark coordinates of an uploaded image, add text to each point and upload to a server.

However, when the images are downloaded, the coordinates captured are way of its mark. It seems like the mouse pointer event somehow does not capture the coordinates within the image. I need help to know what exactly I am doing wrong.

Image pointer capture function

const handleImageClick = (event: any) => {
    var e = event.target;
    const imageRect = e.getBoundingClientRect();
    const x = event.clientX - imageRect.left;
    const y = event.clientY - imageRect.top;

    console.log(x,y)
  
    const newAnnotation: Annotation = {
      x,
      y,
      text: currentAnnotationText || 'New Annotation',
    };
  
    setAnnotations([...annotations, newAnnotation]);
    setCurrentAnnotationText('');
  };

Any kind assistance will be appreciated.

FrontEnd

<div className="image-container" style={{ position: 'relative' }}>
  <IonImg
    ref={imageRef}
    src={image}
    alt="Captured or Selected"
    style={{ marginBottom: '20px' }}
    onClick={handleImageClick} // Attach the onClick event directly to the IonImg
  />
  {annotations.map((annotation, index) => (
    <div
      key={index}
      className="annotation"
      style={{
        position: 'absolute',
        top: `${annotation.y}px`,
        left: `${annotation.x}px`,
        backgroundColor: 'rgba(255, 255, 255, 0.7)',
        padding: '4px',
        borderRadius: '4px',
      }}
    >
      {annotation.text}
    </div>

I solved this by using percentages to determine the coordinates.

  const handleImageClick = (event: any) => {

    const e = event.target as HTMLImageElement;
  
    const imageRect = e.getBoundingClientRect();
  

    const x = ((event.pageX - imageRect.left) / imageRect.width) * 100;
    const y = ((event.pageY - imageRect.top) / imageRect.height) * 100;
  
    console.log(x, y);
  
    const newAnnotation: Annotation = {
      x,
      y,
      text: currentAnnotationText || 'New Annotation',
    };
  
    setAnnotations([...annotations, newAnnotation]);
    setCurrentAnnotationText('');
  };

Upvotes: 0

Views: 26

Answers (1)

Najam Us Saqib
Najam Us Saqib

Reputation: 3402

Try this to capture your coordinates:

const handleImageClick = (event: any) => {
   let offsetLeft = 0;
   let offsetTop = 0;
   let el = event.srcElement;
   offsetLeft += el.offsetLeft;
   offsetTop += el.offsetTop;
   let x = ((((event.offsetX) - offsetLeft) / el.offsetWidth * 100));
   let y = ((((event.offsetY) - offsetTop) / el.offsetHeight * 100));
}

Upvotes: 0

Related Questions