Search code examples
javascriptjqueryhtmlhtml2canvas

Capture the div when clicked on it


I want to capture a div element when clicked on it using jquery & HTML2Canvas library in an environment where I have multiple div of that same class name.

This is for a console page on which I want to give user an extra choice to capture the div or not, everyone just don't bother about the event listener here I'm using.

$('.panel.panel-default', this).one("mouseenter", function() {
  html2canvas(document.getElementsByClassName("panel panel-default")).then(canvas => {
    //document.body.appendChild(canvas);
    var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");  
    console.log(image);  
    window.location.href = image;
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="panel panel-default">
  <div class="panel-body">
    <a> this is panel one</a><br><br>
  </div>
</div>
<div class="panel panel-default">
  <div class="panel-body">
    <a> this is panel two</a><br><br>
  </div>
</div>
<div class="panel panel-default">
  <div class="panel-body">
    <a> this is panel three</a><br><br>
  </div>
</div>

Actual result should be like when I click on the this is panel one the event will capture that div into the file.


Solution

  • You need to just pass the right context

      $('.panel-body').on("click", function () {
            html2canvas(this).then(canvas => {
                //document.body.appendChild(canvas);
                var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
                console.log(image);
                window.location.href = image;
            })
        });