Home > Enterprise >  Not getting accurate mouse mouseup and mousedown coordinate
Not getting accurate mouse mouseup and mousedown coordinate

Time:12-29

I am using react with typescript. I have a canvas and I am trying to draw a rectangle inside the canvas based on mouseup and mousedown event. I don't know what I am doing wrong here my rectangles are drawn but in different positions.

This is how my code looks like:

const Home = () => {

    const divRef = useRef<HTMLCanvasElement>(null);

    useEffect(() => {
        let paint = false;
        let StartClientXCord: any;
        let StartClientYCord: any;
        let FinishedClientXCord: any;
        let FinishedClientYCord: any;
        function startPosition(e:any){
            paint = true;
            StartClientXCord = e.clientX;
            StartClientYCord = e.clientY;
        }

        function finishPosition(e:any){
            FinishedClientXCord = e.clientX;
            FinishedClientYCord = e.clientY;
            paint = false;
        }

        function draw(e: any){
            if(!paint){
                return
            }
            if(divRef.current){
                const canvas = divRef.current.getContext('2d');
                if(canvas){
                    canvas?.rect(StartClientXCord, StartClientYCord, FinishedClientXCord - StartClientXCord, FinishedClientYCord - StartClientYCord);
                    canvas.fillStyle = 'rgba(100,100,100,0.5)';
                    canvas?.fill();
                    canvas.strokeStyle = "#ddeadd";
                    canvas.lineWidth = 1;
                    canvas?.stroke();
                }
                
            }
        }

        
        if(divRef.current){
            divRef.current.addEventListener("mousedown", startPosition);
            divRef.current.addEventListener("mouseup", finishPosition);
            divRef.current.addEventListener("mousemove", draw);
        }
    })

    return (
         <canvas className='canvas' style={{height: height, width: width}} ref={divRef}>
            </canvas>
    )
}

I am drawing on a different position box is drawing on a different position. Here I attached the screenshot as well

Output

CodePudding user response:

I believe it's because you are using clientX and clientY, which MDN defines as:

The clientX read-only property of the MouseEvent interface provides the horizontal coordinate within the application's viewport at which the event occurred (as opposed to the coordinate within the page).

This is the absolute position on the entire page. What you want is the is the position reative to the top left corner of the canvas. You want offsetX and offsetY which MDN defines as:

The offsetX read-only property of the MouseEvent interface provides the offset in the X coordinate of the mouse pointer between that event and the padding edge of the target node.

So give this a try:

StartClientXCord = e.offsetX;
StartClientYCord = e.offsetY;
  • Related