-1

I am trying to save and download div content as an image. I resorted to this solution which suggests using html2canvas.

I have implemented the code below but cannot get the div content to be saved and downloaded as an image. How can I do this in jQuery or JavaScript?

Here is my code so far:

<!doctype html>
<html>

<head>

  <script type="text/javascript" src="html2canvas-master/dist/html2canvas.js"></script>

</head>

<body>
  <h1> Div Data to be Save and Download</h1>
  <div class="div1" id='div1'>
    <h2> Iam Div1</h2>
    <img src='images/div1_image.jpg' width='100' height='100'>

  </div><br/>
  <input type='button' id='but_screenshot' value='Download as Image' onclick='download();'><br/><br/>





  <!-- Script -->
  <script type='text/javascript'>
    function download() {
      // html2canvas(document.body).then(function(canvas) {

      html2canvas(document.getElementById('div1')).then(function(canvas) {

        document.body.appendChild(canvas);
      });
    }
  </script>

</body>

</html>
halfer
  • 19,824
  • 17
  • 99
  • 186
Nancy Moore
  • 2,322
  • 2
  • 21
  • 38

1 Answers1

0

Extend your download() function with the next code:

    function download() {
         html2canvas(document.getElementById("div1")).then(function(canvas) {
            document.body.appendChild(canvas);

            const image = canvas.toDataURL("image/png", 1.0);
            const link = document.createElement("a");

            link.download = "my-image.png";
            link.href = image;
            link.click();
      });
     }

You will get that as downloaded file after click enter image description here

Pasha
  • 621
  • 8
  • 21
  • Thanks @Pasha. it only save and download only the text in the div `

    Iam Div1

    ` but the image inside the div is not captured and downloaded along with the text `` what could be the problem.between thanks
    – Nancy Moore Jan 26 '20 at 15:40
  • @NancyMooree hmm, I took your code and put example image. I can see it in downloaded file. Try to check path to the file 'src=' – Pasha Jan 26 '20 at 16:11
  • Your are right. you will need to host the application statically or run it through server eg Wamp/xampp for the image to appear. Thank you – Nancy Moore Jan 26 '20 at 16:27