Capture a screenshot of an element in either jpg or png format and proceed to save it to your device using Javascript

I am looking to create a JavaScript function that can capture a screenshot of an element and then allow the user to download it.

<body>
    <h1>Sample text</h1>
    <h2>Sample text</h2>
    <table width="1080px" height="1920px" border="1" style="border-collapse:collapse">
        <tbody><tr>
            <td colspan="2">
                <img src="https://inspectiondoc.com/wp-content/uploads/2014/08/sample-icon.png" width="600px">
            </td>
            <td>
                Sample text
            </td>
        </tr>
        <tr style="background:#b6ff00">
            <td>
                Sample text
            </td>
            <td>
                Sample text
            </td>
            <td>
                Sample text
            </td>
        </tr>
    </tbody></table>
    <h1>
        sample text
    </h1>
    <h2>Sample text</h2>
    <br><br>
    <input type="button" value="Capture" onclick="capture()">

</body>

Upon clicking the capture button, I aim to have the element with td colspan="2" captured as a screenshot and available for download in jpg or png format.

Answer №1

To convert an element into a canvas, consider using the html2canvas tool. Simply add the data as a URL into an 'a' element for easy conversion.

function download(canvas, filename) {
  const data = canvas.toDataURL("image/png;base64");
  const downloadLink = document.querySelector("#download");
  downloadLink.download = filename;
  downloadLink.href = data;
}

html2canvas(document.querySelector(".card")).then((canvas) => {
  // document.body.appendChild(canvas);
  download(canvas, "example");
});

For a complete demonstration, you can check out this example: https://codepen.io/koseare/pen/NWpMjeP

Answer №2

Consider using the html2canvas library;

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="all">
      <h2>Sample text</h2>
      <table width="1080px" height="1920px" style="border-collapse: collapse">
        <tbody>
          <tr>
            <td colspan="2">
              <img
                src="https://inspectiondoc.com/wp-content/uploads/2014/08/sample-icon.png"
                width="600px"
              />
            </td>
            <td>Sample text</td>
          </tr>
          <tr style="background: #b6ff00">
            <td>Sample text</td>
            <td>Sample text</td>
            <td>Sample text</td>
          </tr>
        </tbody>
      </table>
    </div>
    <br />
    <input type="button" id="btn" value="Download" />
    <script>
      
      document.getElementById("btn").addEventListener(
        "click",
        function () {
          var text = document.getElementById("all").value;
          var filename = "output.txt";
          download(filename, function makeScreenshot() {
        html2canvas(document.getElementById("screenshot"), {scale: 1}).then(canvas => {
            document.body.appendChild(canvas);
        });
    });
        },
        false
      );
    </script>
  </body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble retrieving the ID of the clicked element in AngularJS?

I have successfully implemented a function in angularjs to retrieve the id of the clicked element. Below is my code snippet html <a href="#faqinner/contactform" class="clearfix" ng-click="getCateId($event)" id="{{option.id}}"> <span class= ...

Renaming the month in Material-UI React

Using DatePicker from Material Ui, I am trying to change the name of the month. How can this be achieved? For instance, I need to change August to Avqust or March to Mart enter image description here This is my code: <LocalizationProvider ...

AngularJS Error: $element.find(...) does not support iteration

I'm attempting to utilize a datatable in my AngularJS application. Below is the HTML code I've implemented: <div ng-app="datatable"> <div ng-controller="voucherlistcontroller"> ...

No matter what I attempt, my presentation refuses to align in the center

My slideshow, which is powered by jQuery/JS and involves absolute positioning for each image, is causing me trouble when trying to horizontally center it on the page. No matter what I do, I can't seem to get it right. The challenge is not only getting ...

unable to display images from a folder using v-for in Vue.js

Just getting started with Vuejs and I have two pictures stored on my website. The v-for loop is correctly populating the information inside databaseListItem. The path is /opt/lampp/htdocs/products_db/stored_images/cms.png https://i.stack.imgur.com/969U7.p ...

Guide to implement a confirmation box in PHP

I recently set up a Joomla article and integrated the Sourcerer Joomla extension to include JavaScript and PHP in my project. Currently, I am developing a course purchase site where users can buy courses from owners and credits are deducted upon every purc ...

Steps to create an if statement using jQuery

.data( "autocomplete" )._renderItem = function( ul, item ) { return $( "<li></li>" ) .data( "item.autocomplete", item ) if ( ( item.parent_term_id == "16" ) ) { .append( "<a>" + (item.child_term ? item.child ...

Storing data in a TypeBuffer and then retrieving it from a file can lead to surprising outcomes

Upon executing the following code: var list = new Uint32Array(16); for (var i=0; i<16; ++i) list[i] = i; fs.writeFileSync("list", new Uint8Array(list).buffer); console.log([].slice.call(new Uint32Array(fs.readFileSync("list")))); We anticipate the out ...

Performing an AJAX GET request to the API after a set time interval

The API is constantly updating with live values, so I am attempting to fetch the data every second and display it on the webpage. Although I used a GET request call every N seconds using set_interval(), the values only load once and do not update with eac ...

"Concealing specific routes in Vue Router depending on a certain condition - what's the

I need to determine which routes to hide based on a condition that evaluates to true or false. I have a collection of routes, such as: - Products - Clients For instance, if a user logs in but does not have the permission to edit products, then the updated ...

What is causing the error to appear in the Android web-view when using vue.js?

During the development of my web app using Vue.js, I encountered a strange issue where everything was functioning correctly in desktop browsers but not on mobile devices. To troubleshoot this problem, I decided to install an Android emulator and use remote ...

Notifier - The Best HTML Notification System for Web Applications

Currently, I am developing a notification system using Play Framework 2.3 (Java) in combination with MySQL. The system is designed to retrieve notifications from a "notifications" table stored in MySQL database. I initially attempted to use AJAX polling ...

Node.js: Capturing requests and responses for console logging

I'm currently working on a Hapi server using Good to log all requests and responses to the console. I've been able to successfully log responses but I'm facing issues with logging the body of the response, and for requests, I'm not gett ...

Transforming an object containing methods into a string using Javascript specifically for Photoshop

I have a unique universal object that is essential for my Photoshop scripts. It contains various properties and methods like this: var Object = {}; Object.text = "this is some text"; Object.toolbox = new ToolBox(); // specialized object with its own funct ...

Learn how to utilize interpolation within an *ngIf statement in Angular 2 in order to access local template

Consider the following scenario; <div *ngFor="item of items; let i = index;"> <div *ngIf="variable{{i}}">show if variable{{i}} is true</div> </div> Suppose I have variables named "variable0", "variable1",... Is there a way to ac ...

Hiding links in javascript

I currently have a hyperlink <a href="url1">url1</a>. Interestingly, I have noticed that some websites utilize JavaScript to display this as url1 but in reality, it redirects to url2. When you hover over the link, the original url is not visib ...

Transferring information from the main function to getServerSideProps

I've been facing challenges while trying to pass data from a function component to the getServerSideProps method in Next.js. As a beginner in learning Next.js, I am struggling to understand this concept. My approach involves using context from _app, b ...

Tips on creating a keypress function for a div element with the contenteditable attribute

Hey there, I have managed to create a textarea within a div by using -webkit-appearance. However, I am currently struggling to add an event to this div on key press. I have been trying my best to figure it out but seem to be missing something. If you coul ...

The Datalist feature in HTML5 offers an auto-suggest functionality that displays a list of options beginning with the

In my project, I am utilizing HTML5 Datalist for autosuggestion. By default, HTML5 follows the keyword contains approach rather than the starts with approach. For example, if my datalist includes one, two, three and I type "o" in the search box, it displ ...

Script fails to load upon accessing page through index hyperlink

I am facing an issue with my JavaScript elements not loading when I navigate to a form page from a link in the index. However, if I enter the URL manually or redirect from the login page, the JavaScript loads perfectly fine. The JavaScript code is consolid ...