How to Save a Section of Screen as an Image File?

,

You can use this code inside of an HTML-Component.
You will have to expand the code and complete it, to get your wished result!

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Screenshot Capture</title>
<style>
  #capture {
    width: 300px;
    height: 200px;
    background-color: lightblue;
    border: 1px solid black;
  }
</style>
</head>
<body>

<h1 id="capture">Hellooooo</h1>
<button id="btn">Capture</button>

<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
<script>
function capture() {
  const captureElement = document.querySelector('#capture');
  html2canvas(captureElement)
    .then(canvas => {
      const image = canvas.toDataURL('image/png');
      const a = document.createElement('a');
      a.setAttribute('download', 'my-image.png');
      a.setAttribute('href', image);
      a.click();
    });
}

const btn = document.querySelector('#btn');
btn.addEventListener('click', capture);
</script>

</body>
</html>
2 Likes