kirqe
kirqe

Reputation: 2470

how to grab div with html2canvas?

I'm trying to use html2canvas. I need to grab a specific div and add it to the body.

The code from official site works fine as a demonstration. But When I try to select my div, nothing happens.

Here's what's working

html2canvas(document.body, {
  onrendered: function(canvas) {
    document.body.appendChild(canvas);
  },
  width: 500,
  height: 500
});

and here's what's not working

html2canvas($("#div_name"), {
  onrendered: function(canvas) {
    document.body.appendChild(canvas);
  },
  width: 500,
  height: 500
});

what am I doing wrong? ty

up

 <div id="dsf" class="sdf">
   <%= render "share_form" %>
 </div>

up

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<script type="text/javascript">
html2canvas($("#dsf"), {
  onrendered: function(canvas) {
    document.body.appendChild(canvas);
  }
});
</script>

if I use document.body it works both with or withour $( document ).ready(function() {

Upvotes: 0

Views: 1024

Answers (2)

movabo
movabo

Reputation: 411

You have to execute the script when the document is loaded. So you have to replace

<script type="text/javascript">
html2canvas($("#dsf"), {
  onrendered: function(canvas) {
    document.body.appendChild(canvas);
  }
});
</script>

with

<script type="text/javascript">
$(document).ready(function () {
  html2canvas($("#dsf"), {
    onrendered: function(canvas) {
      document.body.appendChild(canvas);
    }
  });
});
</script>

(For more information see http://learn.jquery.com/using-jquery-core/document-ready/)

Upvotes: 1

Born2Code
Born2Code

Reputation: 1075

try

html2canvas(document.getElementById("div_name"), {
  onrendered: function(canvas) {
    document.body.appendChild(canvas);
  },
  width: 500,
  height: 500
});

and make sure you have a div with an id of div_name

Upvotes: 1

Related Questions