How can I build a Chrome extension that allows users to capture a specific area of a webpage as an image?

I’m working on a Chrome extension to capture a specific area of a webpage as an image. I’ve tried several approaches, including using the html2Canvas,, and manipulating the DOM to select the area, but I keep running into various issues and errors. Either the selected area isn’t captured correctly, or sometimes it able to capture but failed on second attempt. I’ve spent a lot of time troubleshooting, but I’m still not able to get it to work as expected. Any guidance or suggestions on how to implement this feature would be greatly appreciated!

Know someone who can answer? or Share a link of your code if you already have build something like this

enter image description here

import React, { useState } from "react";

const ScreenCaptureComponent: React.FC = () => {
  const [screenCapture, setScreenCapture] = useState<string | null>(null);

  const handleCapture = () => {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      if (tabs[0].id) {
        chrome.scripting.executeScript(
          {
            target: { tabId: tabs[0].id },
            files: ["content.js"],
          },
          () => {
            chrome.tabs.sendMessage(
              tabs[0].id!,
              { message: "capture" },
              (response) => {
                if (chrome.runtime.lastError) {
                  console.error("Error:", chrome.runtime.lastError);
                } else if (response && response.imgData) {
                  setScreenCapture(response.imgData);
                } else {
                  console.error("Failed to capture screen");
                }
              }
            );
          }
        );
      }
    });
  };

  const handleSave = () => {
    if (screenCapture) {
      const a = document.createElement("a");
      a.href = screenCapture;
      a.download = "screenshot.png";
      a.click();
    }
  };

  return (
    <div>
      <button onClick={handleCapture}>Capture</button>
      {screenCapture && (
        <div>
          <img src={screenCapture} alt="Screen Capture" />
          <button onClick={handleSave}>Download</button>
        </div>
      )}
    </div>
  );
};

export default ScreenCaptureComponent;