Get the Coordinate of Original Image

34 Views Asked by At

I need to customize my image with CSS and I plan to dot 2 point and get the coordinate of image base on original size of image and the we can dot over the image only(Note: the coordinate not base the size that i custom with CSS or on screen).

import React, { useState } from 'react';
import src from "../assets/testCoordinate.jpeg";
import ReactPlayer from 'react-player'
import Select from "react-select"
const ImageDetection = () => {
    const [isSelecting, setIsSelecting] = useState(false);
    const [startX, setStartX] = useState(null);
    const [startY, setStartY] = useState(null);
    const [endX, setEndX] = useState(null);
    const [endY, setEndY] = useState(null);
    const [imageWidth, setImageWidth] = useState(null);
    const [imageHeight, setImageHeight] = useState(null);

    const handleClick = (event) => {
        const { offsetX, offsetY } = event.nativeEvent;
        const { width, height } = event.currentTarget.getBoundingClientRect();
      

        if (isSelecting) {
            setEndX(offsetX);
            setEndY(offsetY);
            setIsSelecting(false);
            console.log(`End clicked at: (${offsetX}, ${offsetY})`);
        } else {
            setStartX(offsetX);
            setStartY(offsetY);
            setIsSelecting(true);
            console.log(`Start clicked at: (${offsetX}, ${offsetY})`);
        }
    };

    const startMarkerStyle = {
        position: 'absolute',
        left: `${startX}px`,
        top: `${startY}px`,
        width: '10px',
        height: '10px',
        backgroundColor: 'green',
        borderRadius: '50%',
    };

    const endMarkerStyle = {
        position: 'absolute',
        left: `${endX}px`,
        top: `${endY}px`,
        width: '10px',
        height: '10px',
        backgroundColor: 'red',
        borderRadius: '50%',
    };

    const lineStyle = {
        position: 'absolute',
        zIndex: 1,
        left: 0,
        top: 0,
        width: '100%',
        height: '100%',
    };

    const handleImageLoad = (event) => {
        const { naturalWidth, naturalHeight } = event.target;
        setImageWidth(naturalWidth);
        setImageHeight(naturalHeight);
    };

    return (
        <div style={{ position: 'relative', }} >
            {/* <h1>Set the Strict Line</h1>
            <Select
            className='w-[240px] h-[60px]'
                options={[
                    { value: 'video', label: 'Video' },
                    { value: 'image', label: 'Image' }
                ]}
            /> */}

            <img
                src={src}
                alt="Test Image"
                onClick={handleClick}
                className='w-[740px] h-[540px]'
                onLoad={handleImageLoad}
            />
            {/* <ReactPlayer url='https://buyme-now-bucket.s3.ap-southeast-2.amazonaws.com/huh.mp4' /> */}
            {startX !== null && (
                <div style={startMarkerStyle}>
                    {/* Start point marker */}
                </div>
            )}
            {endX !== null && (
                <div style={endMarkerStyle}>
                    {/* End point marker */}
                </div>
            )}
            {startX !== null && endX !== null && (
                <svg style={lineStyle}>
                    <line x1={startX} y1={startY} x2={endX} y2={endY} stroke="blue" strokeWidth="2" />
                </svg>
            )}
            {imageWidth && imageHeight && (
                <p>Image Original Size: {imageWidth} x {imageHeight}</p>
            )}
        </div>
    );
};

export default ImageDetection;

I want a Point of image base on its original width and Height

1

There are 1 best solutions below

1
Mr. Terminix On

You have to calculate the ratio between the original image width and height compared to sized image on the screen. I can see in the code provided the sized image width and height are 'w-[740px] h-[540px]'. If there is an image with width 370px and height 270px, the ratio will be 2 (or 0.5 if you divide the real size on the screen size). The code is:

const handleClick = (event) => {
    const { offsetX, offsetY } = event.nativeEvent;
    const { width, height } = event.currentTarget.getBoundingClientRect();

    // Calculate the width ratio
    const ratioX = width / imageWidth
    
    // Calculate the height ratio
    const ratioY = height / imageHeight

    // Calculate the offset X for the real size 
    const imageOffsetX = offsetX / ratioX
    // Calculate the offset Y for the real size 
    const imageOffsetY = offsetY / ratioY

  
    if (isSelecting) {
        setEndX(offsetX);
        setEndY(offsetY);
        setIsSelecting(false);
        console.log(`End clicked at: (${offsetX}, ${offsetY})`);
    } else {
        setStartX(offsetX);
        setStartY(offsetY);
        setIsSelecting(true);
        console.log(`Start clicked at: (${offsetX}, ${offsetY})`);
    }
};

If the user clicks on 100h 100w on the screen size, the point on the real size image will be 50h 50w.