简体   繁体   中英

html2canvas Generates Blank if canvas is NOT added to body

The idea is simple and widely described: Take a screenshot using html2canvas plugin, then, send the image using Ajax to server.

To do so, I use

html2canvas(document.querySelector("body"))
    .then(canvas => {

        document.body.appendChild(canvas) // => pay attention to this line

        const b64 = canvas.toDataURL("image/png").replace(/.*,/, '');
        theFunctionThatSendB64UsingAjax(b64)
        return;
     })

So, this elegant piece of code works pretty fine, It generates a canvas element. attach it to body and then send a base64 format string to the server.

But I don't want to display the canvas nor the image. So, the obvious is to remove the line:

document.body.appendChild(canvas)

When I do so, the generated image is always blank.

PS: this issue only happens on Firefox ! it works fine on Chrome

So, is there anybody out there with at least a clue?, Or. an alternative to html2canvas.

And, if matters, the server is running a golang script that store the image in a mongodb. The server side works fine !

html2canvas version 1.0.0-rc.5 !

EDIT:

This issue does not happens on v0.4 as described in answer below !

EDIT:

I Opened an issue on github:

https://github.com/niklasvh/html2canvas/issues/2254

 window.takeScreenShot = function() { html2canvas(document.body, { onrendered: function (canvas) { const b64 = canvas.toDataURL("image/png").replace(/.*,/, ''); console.log("data:image/png;base64, "+b64 ) //document.getElementById("test").src="data:image/png;base64, "+b64 } }); }
 #target{ width:300px; height:200px; background:blue; color:#fff; padding:10px; } button{ display:block; height:20px; margin-top:10px; margin-bottom:10px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script> <div id="target"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque quis eleifend elit. Donec lectus sem, scelerisque sit amet facilisis quis, gravida a lacus. Nunc at lorem egestas, gravida lorem quis, pulvinar ante. Quisque id tempus libero. Mauris hendrerit nunc risus, ac laoreet lectus gravida et. Nam euismod magna ac enim posuere sagittis. Fusce at egestas enim, eu hendrerit enim. </div> <button onclick="takeScreenShot()">to image</button>

Maybe you should try this: https://ekoopmans.github.io/html2pdf.js/

html2pdf.js converts any web page or element into a printable PDF entirely client-side using html2canvas and jsPDF.

I tried it and i worked well for input form (not range type though).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM