javascript cropping issue for chrome extension

I have a Chrome extension that allows the user to take a screenshot from a selected area of their screen.

The flow looks like this:

User clicks the screenshot button in the Chrome Extension popup menu. The popup sends a message to the Background script to capture the tab.
The background script screenshots the entire tab and sends the URL to the content script.
The content script allows the user to draw a rectangle on the screen and it crops out that area of the screen from the screenshot and sends it to the server.

The Issue: When the user selects the area to crop, the final result is scaled in and shifted to the left and up a bit, I was able to fix this by implementing a ratio system just like in a post by user (https://stackoverflow.com/users/8586250/ryan) I came across during one of my searches. but right now, im struggling making the system work when the page is scrolling (as that disrupts the accuracy ). I also noticed that when it comes to some webpages , even without the page scrolled , the area the user selected is off by a bit, instead of capping out the word I selected , it crops out the area a little bit above the intended area.

here is my current code:

(function() {
    let startX, startY, div;
 
    const dpr = window.devicePixelRatio || 1; // Device Pixel Ratio
    const bodyStyle = window.getComputedStyle(document.body);
    const bodyTransform = bodyStyle.transform || bodyStyle.webkitTransform || bodyStyle.mozTransform || bodyStyle.msTransform;
    const bodyScale = bodyTransform.includes('matrix') ? parseFloat(bodyTransform.split(',')[3]) : 1;

    function getCursorPosition(e) {
        return {
            x: (e.clientX + window.scrollX) * dpr * bodyScale,
            y: (e.clientY + window.scrollY) * dpr * bodyScale
        };
    }
    
 

  

    function onMouseDown(e) {
        
    
       
        let cursorPos = getCursorPosition(e);
        startX = cursorPos.x;
        startY = cursorPos.y;
    
        div = document.createElement('div');
        div.style.position = 'absolute';
        div.style.border = '2px solid black';
        div.style.left = `${startX / (dpr * bodyScale)}px`;
        div.style.top = `${startY / (dpr * bodyScale)}px`;
        div.style.zIndex = '2147483647';
        div.style.pointerEvents = 'none';
        div.style.boxSizing = 'border-box'; // Include border in the width and height calculations
        div.style.transform = `scale(${1 / bodyScale})`; // Counteract the body scaling
        div.style.transformOrigin = 'top left';
        document.body.appendChild(div);
    
        document.addEventListener('mousemove', onMouseMove);
        document.addEventListener('mouseup', onMouseUp);
    }
    
    function onMouseMove(e) {
       
    
        let cursorPos = getCursorPosition(e);
        const width = Math.abs(cursorPos.x - startX);
        const height = Math.abs(cursorPos.y - startY);
    
        div.style.width = `${width / (dpr * bodyScale)}px`;
        div.style.height = `${height / (dpr * bodyScale)}px`;
        div.style.left = `${Math.min(cursorPos.x, startX) / (dpr * bodyScale)}px`;
        div.style.top = `${Math.min(cursorPos.y, startY) / (dpr * bodyScale)}px`;
    }
    
    function onMouseUp(e) {
       
    
        document.removeEventListener('mousemove', onMouseMove);
        document.removeEventListener('mouseup', onMouseUp);
    
        let cursorPos = getCursorPosition(e);
        const bodyPaddingLeft = parseInt(bodyStyle.paddingLeft, 10);
        const bodyPaddingTop = parseInt(bodyStyle.paddingTop, 10);

        const coordinates = {
            left: (Math.min(cursorPos.x, startX) - bodyPaddingLeft) / (dpr * bodyScale),
            top: (Math.min(cursorPos.y, startY) - bodyPaddingTop) / (dpr * bodyScale),
            width: (Math.abs(cursorPos.x - startX)) / (dpr * bodyScale),
            height: (Math.abs(cursorPos.y - startY)) / (dpr * bodyScale)
        };
    
        console.log('Coordinates:', coordinates);
        chrome.runtime.sendMessage({
            action: 'captureSelectedArea',
            coordinates: coordinates
        });
    
        div.parentNode.removeChild(div);
       
    }
})();


// funtion that recieves coordinates 

function processSS(request) {
   
        const img = new Image();
        img.onload = () => {
            console.log('Loaded image size:', img.naturalWidth, img.naturalHeight);

            const ratio = img.naturalWidth / window.innerWidth;
            console.log('Screen to image ratio:', ratio);

            const scaledLeft = request.coordinates.left * ratio;
            const scaledTop = (request.coordinates.top + window.scrollY) * ratio; // Including vertical scroll offset
            const scaledWidth = request.coordinates.width * ratio;
            const scaledHeight = request.coordinates.height * ratio;

            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            canvas.width = request.coordinates.width;
            canvas.height = request.coordinates.height;

            ctx.drawImage(img,
                scaledLeft, scaledTop,
                scaledWidth, scaledHeight,
                0, 0,
                canvas.width, canvas.height
            );

            const croppedDataUrl = canvas.toDataURL('image/png');
            console.log('Cropped image data URL:', croppedDataUrl);

          

        console.log('Image data to load:', request.imageData);
        img.src = request.imageData;
    }).
}