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

Dynamically insert <td> elements into <tr> element using both jQuery and JavaScript

I am facing an issue with adding a new table data (td) element dynamically to the first table row (tr) in my JavaScript code. Here is the original table before adding the new td element: <table> <tbody> <tr> <t ...

How can I access the rendered HTML element from a component in Vue 3?

This particular component is known as LayerComponent (placeholder). <script> export default { data() { return { count: 0 } } } </script> <template> <button @click="count++">You have clicked me {{ count ...

Picture fails to load on Ionic app on the device

Currently, I am utilizing Ionic 3 for my project. The location of the images file is \src\assets\img. This pertains to a basic page implementation. export class BasicPage { items = []; constructor(public nav: NavController ,private adm ...

The code "Grunt server" was not recognized as a valid command in the

I recently set up Grunt in my project directory with the following command: npm install grunt However, when I tried to run Grunt server in my project directory, it returned a "command not found" error. Raj$ grunt server -bash: grunt: command not found ...

Create a dynamic table using an array in jQuery

Currently, my goal is to generate a table using an array with the following format: [ { header: 'ID', values: [1, 2] }, { header: 'First Name', values: ['John', 'Jayne'] }, { header: &ap ...

Using PHP to dynamically change the title of a Bootstrap modal

I've been attempting to dynamically update the title of my modal using PHP. The title I wish to display is stored in a variable and is being reassigned based on user input. Below is my PHP code snippet: $studentName = $results['Studentname&apo ...

Trigger an Angular2 component function from an HTML element by simply clicking a button

I'm just starting out with TypeScript and Angular2 and encountering an issue when trying to call a component function by clicking on an HTML button. When I use the **onclick="locateHotelOnMap()"** attribute on the HTML button element, I receive this ...

Is it possible to resolve the error message "Uncaught TypeError: Cannot read property 'node' of undefined" when utilizing d3-tip with npm?

After installing d3": "^3.5.17" and "d3-tip": "^0.7.1" via npm (d3-tip documentation), the following code was added to my index.js file: var d3 = require('d3'); var d3tip = require('d3-tip')(d3); console.log('d3 version', d3. ...

Executing a component's function from a JavaScript file

Is it possible in React to call a function or method of a component from a separate JS file in order to modify the component's state? Here are three example files: First, App.js import React,{Component} from 'react'; import Login from &ap ...

Retrieve data attributes to obtain details about the slider before and after

My task is to create a slider with information about the previous and next slides. For example, in the slider, there are left < and right > arrows. Behind these arrows, there are circles. When you hover over any arrow to change the next or previous ...

Using $window.print() in angularjs results in the print preview displaying an empty page

Encountering a strange issue where using $window.print in angularjs results in only the date, page name, page number, and url appearing on the printed page. The rest of the content is missing even though the original page has plenty of it. I suspect the p ...

Guide to Updating Store State with API Data

My goal is to update my component state with data retrieved from an API using a getter in the store. Within the mounted() lifecycle hook, I call the getProducts() getter which is defined as: export const getters = { async getProducts() { axios.ge ...

Testing the selection of dropdown values in Angular2 using unit tests

I have a dropdown menu for selecting countries. It defaults to a pre-selected value, and when the user changes it, they are redirected to the corresponding country page. However, I am facing an issue while trying to unit test the default value in the sele ...

Using JavaScript and jQuery to toggle visibility of a dynamically created input field

This script dynamically generates a group of elements consisting of four input fields. Once an element is created, you can select or deselect it, which will trigger the corresponding editor to appear. I have implemented a function to specifically hide the ...

Basic math tool using JSP/Servlet combination and Ajax

I have a follow-up question to my previous inquiry on Stack Overflow. I believe this topic deserves its own discussion due to the thorough response I received. My goal is to develop a straightforward calculator using JSP. The calculator will include two t ...

"Observed Issue: Ionic2 Array Fails to Update in HTML Display

I am struggling with updating an array in Ionic2 and Angular2. I have tried updating it on the front end but it's not working, even though it updates perfectly on the backend (ts) as confirmed by checking the console. I need assistance with this. Her ...

Personalizing the Twitter Embedded Timeline

I am curious about how much customization options are available for the Embedded Timeline. I searched through the documentation but still have some unanswered questions - maybe I missed something. My goal is to initially display only one tweet and then ha ...

Generating a fresh array of unique objects by referencing an original object without any duplicates

I can't seem to figure out how to achieve what I want, even though it doesn't seem too complicated. I have an array of objects: { "year": 2016, "some stuff": "bla0", "other stuff": 20 }, "year": 2017, "some stuff": "bla1", ...

Triggering a JQuery slider event on each individual slider handle within the range

Can events be triggered based on the movement of individual slider handles? I am curious because I need to dynamically update a datepicker depending on which handle is moved. However, I'm unsure if there is a way to: Specify an event for a specifi ...

How to extract query string parameters using node.js

I'm currently working on fetching query string parameters from a URL using the node.js restify module. This is an example of the URL I am dealing with: Here is the relevant code snippet: server.use(restify.bodyParser()); server.listen(7779, functi ...