Search code examples
javascriptjqueryasp.nethtml2canvas

can't change div element to canvas using html2canvas in asp.net


I use html2canvas and this is how I declare js files and css in Master Page

     <head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.9.1.js" type="text/javascript"></script>
    <script src="Scripts/html2canvas.js" type="text/javascript"></script>
    <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
    <asp:ContentPlaceHolder ID="HeadContent" runat="server">
    </asp:ContentPlaceHolder>
</head>

In My content page ,

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<script type="text/javascript">
    html2canvas(document.getElementById("mainDiv"), {
        onrendered: function (canvas) {
            document.body.appendChild(canvas);
        }
    });
</script>    
<div id="mainDiv" style="background-color: #CCFF66; border-style: solid; border-color: #000000;
    width: 300px; height: 300px;display:block">
</div>    

but it doesn't work with this code document.getElementById("mainDiv") , but when I change to document.body

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

It works , it append image to the bottom of body .
But I don't want to convert the whole body of my page .
I Just want to convert DIV to canvas .
How can I fix this issue ?


Solution

  • dude, your missing the $(document).ready ( function () { ... }) statement in your asp page , hence its not initialised

      $(document).ready ( function () { 
          html2canvas(document.getElementById("mainDiv"), {
               onrendered: function (canvas) {
                  document.body.appendChild(canvas);
               }
           });
       });
    

    Happy Coding :)